<template>
  <div>
    <!-- 搜索工作栏 -->
    <div>
      <el-form
        :model="searchForm"
        ref="moreSearchRef"
        inline
        label-width="0"
        style="display: inline"
      >
        <el-form-item style="margin-bottom: 10px">
          <el-select
            v-model="searchForm.signProduct"
            placeholder="选择成交产品"
            filterable
            @change="searchForm.specsId = undefined"
          >
            <el-option
              v-for="item in prodOptions"
              :key="item.productId"
              :label="item.productName"
              :value="item.productId"
            />
          </el-select>
        </el-form-item>
        <el-form-item style="margin-bottom: 10px">
          <el-select
            v-model="searchForm.specsId"
            placeholder="选择规格"
            filterable
            :disabled="!searchForm.signProduct"
          >
            <el-option
              v-for="item in specsOptions(searchForm.signProduct)"
              :key="item.specsId"
              :label="item.specsName"
              :value="item.specsId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <Search
        v-if="!loading"
        ref="searchRef"
        :schema="allSchemas.searchSchema"
        inlineBlock
        labelWidth="0"
      >
        <template #actionMore>
          <el-button @click="getTableList" v-hasPermi="['clue:order:search']"> 搜索 </el-button>
          <el-button @click="resetQuery" v-hasPermi="['clue:order:reset']"> 重置 </el-button>
        </template>
      </Search>
    </div>
    <!-- 列表 -->
    <SSTable
      v-if="!loading"
      class="mt-10px"
      v-model:tableObject="tableObject"
      :tableColumns="allSchemas.tableColumns"
      @get-list="getTableList"
    >
      <el-table-column type="expand">
        <template #default="{ row }">
          <div class="p-10px flex justify-center">
            <el-table :data="row.signProducts" stripe style="width: 900px">
              <el-table-column prop="productName" label="成交产品" />
              <el-table-column prop="specsName" label="产品规格" />
              <el-table-column prop="signNum" label="成交数量" />
              <el-table-column prop="warehouseName" label="发货仓库" />
              <el-table-column label="发货备注">
                <template #default="scope">
                  <el-popover
                    placement="top"
                    width="500px"
                    trigger="click"
                    v-if="scope.row.warehouseName && scope.row.sendRemark"
                  >
                    <template #reference>
                      <el-button type="primary" style="padding: 0" text>点击查看</el-button>
                    </template>
                    <div v-dompurify-html="scope.row.sendRemark"></div>
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100px">
                <template #default="scope">
                  <el-button
                    type="primary"
                    class="mr-10px"
                    link
                    :disabled="!!scope.row.warehouseName"
                    style="padding: 0; margin-left: 0"
                    v-hasPermi="['clue:order:send']"
                    @click="handleDelivery(scope.row)"
                  >
                    发货
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        v-for="item in allSchemas.tableColumns"
        :key="item.field"
        :prop="item.field"
        :label="item.label"
        min-width="120px"
      >
        <template #default="{ row }">
          <el-popover
            placement="top"
            width="500px"
            trigger="click"
            v-if="item.field == 'remark' && row.remark"
          >
            <template #reference>
              <el-button type="primary" style="padding: 0" text>点击查看</el-button>
            </template>
            <div v-dompurify-html="row.remark"></div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240px" fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            class="mr-10px"
            link
            style="padding: 0; margin-left: 0"
            v-hasPermi="['clue:order:detail']"
            @click="handleDetail(scope.row)"
          >
            详情
          </el-button>
          <el-button
            type="primary"
            class="mr-10px"
            link
            style="padding: 0; margin-left: 0"
            v-hasPermi="['clue:order:after-sale']"
            @click="sellAfter(scope.row)"
          >
            售后
          </el-button>
          <el-button
            type="primary"
            class="mr-10px"
            link
            style="padding: 0; margin-left: 0"
            v-if="scope.row.isPayoff == false"
            v-hasPermi="['clue:order:return']"
            @click="feeBack(scope.row)"
          >
            回款
          </el-button>
          <el-button
            type="primary"
            class="mr-10px"
            link
            style="padding: 0; margin-left: 0"
            v-hasPermi="['clue:order:add-fee']"
            @click="handleAddFee(scope.row)"
          >
            添加支出
          </el-button>
          <el-button
            type="primary"
            class="mr-10px"
            link
            style="padding: 0; margin-left: 0"
            v-hasPermi="['clue:pool:enroll']"
            @click="cancelDeal(scope.row)"
          >
            取消登记
          </el-button>
        </template>
      </el-table-column>
    </SSTable>

    <!-- 详情 -->
    <DialogOrder ref="orderDetailDialog" />
    <DialogFeeback ref="feedbackDialog" />
    <DialogAfterSale ref="afterSaleDialog" />
    <DialogExtraFee ref="extraFeeDialog" />
    <DialogDelivery ref="deliveryDialog" @success="getTableList" />
  </div>
</template>

<script setup name="ClueOrderList">
import { getSimpleFieldList } from '@/api/clue/orderField'
import * as SignApi from '@/api/clue/sign'
import { getSimpleUserList as getUserOption } from '@/api/system/user'
import { getSimpleProductList } from '@/api/mall/product'

import DialogOrder from './DialogOrder.vue'
import DialogFeeback from './DialogFeeback.vue'
import DialogAfterSale from './DialogAfterSale.vue'
import DialogExtraFee from './DialogExtraPay.vue'
import DialogDelivery from './DialogDelivery.vue'

import { removeNullField } from '@/utils'

const message = useMessage() // 消息弹窗

const allSchemas = ref({})

const orderDetailDialog = ref()
const searchRef = ref()
const prodOptions = ref([])

const specsOptions = computed({
  get() {
    return (prodId) => {
      if (prodId) {
        return prodOptions.value.find((it) => it.productId == prodId).productSpecList
      }
      return []
    }
  }
})

const searchForm = ref({
  signProduct: undefined
})

const tableObject = ref({
  tableList: [],
  loading: false,
  total: 1,
  pageSize: 20,
  currentPage: 1
})

function resetQuery() {
  searchForm.value = {
    signProduct: undefined
  }
  searchRef.value.reset()
  tableObject.value.currentPage = 1
  getTableList()
}
// 查询
async function getTableList() {
  // 查询
  tableObject.value.loading = true
  try {
    const queryParams = await searchRef.value.getFormModel()
    const params = {
      ...queryParams,
      ...searchForm.value,
      pageNo: tableObject.value.currentPage,
      pageSize: tableObject.value.pageSize
    }
    const data = await SignApi.getSignPage(removeNullField(params))
    tableObject.value.tableList = data.list.map((it) => ({ ...it, ...it.diyParams }))
    tableObject.value.total = data.total
  } finally {
    tableObject.value.loading = false
  }
}

const loading = ref(true)
async function getCurdSchemas() {
  loading.value = true
  try {
    const data = await getSimpleFieldList()
    data.forEach((elem) => {
      if (elem.field == 'createUser') {
        elem.search.options = userOptions.value
      }
    })
    allSchemas.value = useCrudSchemas(data).allSchemas
  } finally {
    loading.value = false
    nextTick(() => {
      getTableList()
    })
  }
}

// 详情
function handleDetail(row) {
  orderDetailDialog.value.open(row.clueId, row.signId)
}

const feedbackDialog = ref()
const afterSaleDialog = ref()
// 售后
function sellAfter(row) {
  afterSaleDialog.value.open(row.signId)
}

// 回款
function feeBack(row) {
  feedbackDialog.value.open(row.signId)
}

// 取消登记
async function cancelDeal(row) {
  try {
    // 二次确认
    await message.confirm('是否确认取消登记该线索？')
    // 发起删除
    await SignApi.cancelDeal(row.signId)
    message.success('取消登记成功！')
    // 刷新列表
    await getTableList()
  } catch (err) {
    console.log(err)
  }
}

const extraFeeDialog = ref()
function handleAddFee(row) {
  extraFeeDialog.value.open(row.signId)
}

function getOptions() {
  // 产品
  getSimpleProductList().then((data) => {
    prodOptions.value = data
  })
}
const deliveryDialog = ref()
function handleDelivery(row) {
  deliveryDialog.value.open(row.id)
}

const userOptions = ref([])
onMounted(() => {
  getUserOption().then((data) => {
    userOptions.value = data
    getCurdSchemas()
  })
  getOptions()
})
</script>

<style lang="scss" scoped></style>
