<template>
  <Dialog title="成交详情" v-model="show" width="800px">
    <el-tabs v-model="tabName">
      <el-tab-pane label="线索信息" name="clueInfo" v-if="checkPermi(['clue:pool:detail'])">
        <Descriptions :data="clueInfo" :schema="clueSchema" :columns="2" labelWidth="130px" />
      </el-tab-pane>
      <el-tab-pane label="成交信息" name="orderInfo">
        <Descriptions :data="orderInfo" :schema="orderSchema" :columns="2" labelWidth="130px" />
        <template v-if="orderInfo.signProducts && orderInfo.signProducts.length">
          <el-divider direction="horizontal" content-position="left">
            成交产品<span v-if="prodTotalPrice">，应收：{{ prodTotalPrice }}</span>
          </el-divider>
          <el-table :data="orderInfo.signProducts" border stripe>
            <el-table-column type="index" width="50" />
            <el-table-column prop="productName" label="成交产品" />
            <el-table-column prop="specsName" label="产品规格" />
            <el-table-column prop="signNum" label="成交数量" width="100px" />
            <el-table-column label="发货状态" prop="sendState" width="100px" />
            <el-table-column label="发货备注">
              <template #default="scope">
                <el-popover
                  placement="top"
                  width="500px"
                  trigger="click"
                  v-if="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>
        </template>
        <el-divider direction="horizontal" content-position="left">
          其他费用<span v-if="extraTotalPrice">，应收：{{ extraTotalPrice }}</span>
        </el-divider>
        <el-table :data="orderInfo.extraPay" border stripe>
          <el-table-column type="index" width="50" />
          <el-table-column prop="extraPayType" label="费用项" />
          <el-table-column prop="extraPayMoney" label="金额" />
          <el-table-column prop="remark" label="备注" />
        </el-table>
        <el-divider
          v-if="prodTotalPrice + extraTotalPrice"
          direction="horizontal"
          content-position="left"
        >
          合计应收：{{ prodTotalPrice + extraTotalPrice }}
        </el-divider>
        <div v-if="checkPermi(['clue:order:add-fee'])">
          <el-divider direction="horizontal" content-position="left">
            额外支出<span v-if="extraPayTotalFee">，合计：{{ extraPayTotalFee }}</span>
          </el-divider>
          <el-table :data="extraPayList" border stripe>
            <el-table-column type="index" width="50" />
            <el-table-column prop="extraPayType" label="支出项" />
            <el-table-column prop="extraPayMoney" label="金额" />
            <el-table-column prop="remark" label="备注" />
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane label="回款记录" name="returnRecord">
        <el-table :data="returnRecordList" border stripe>
          <el-table-column type="index" width="50" />
          <el-table-column
            v-if="checkPermi(['clue:order:return-list'])"
            prop="money"
            label="回款金额"
          />
          <el-table-column prop="personProfit" label="员工利润" />
          <el-table-column prop="applyTime" label="申请日期" />
          <el-table-column prop="isPayoff" label="是否结清" />
          <el-table-column prop="stateName" label="审核状态" />
        </el-table>
      </el-tab-pane>
      <el-tab-pane
        label="售后记录"
        name="afterSale"
        v-if="checkPermi(['clue:order:after-sale-list'])"
      >
        <el-table :data="aftersaleList" border stripe>
          <el-table-column type="index" width="50" />
          <el-table-column prop="reason" label="售后原因" />
          <el-table-column prop="refundAmount" label="退款金额" />
          <el-table-column prop="isReturns" label="是否退货" />
          <el-table-column prop="applyTime" label="申请日期" width="180px" />
          <el-table-column prop="stateName" label="审核状态" />
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <div class="mb-15px"></div>
  </Dialog>
</template>

<script setup name="DialogOrder">
import * as ClueApi from '@/api/clue'
import * as OrderApi from '@/api/clue/sign'
import { getSimpleFieldList as getClueFieldList } from '@/api/clue/clueField'
import { getSimpleFieldList as getOrderFieldList } from '@/api/clue/orderField'
import { getPaymentPage } from '@/api/clue/payment'
import { getAfterSalePage } from '@/api/clue/afterSale'

import { checkPermi } from '@/utils/permission'
import { formatDate } from '@/utils/formatTime'

const tabName = ref('clueInfo')
const show = ref(false)
const clueInfo = ref({})
const orderInfo = ref({
  signProducts: [],
  extraPay: []
})
const returnRecordList = ref([])
const aftersaleList = ref([])
const extraPayList = ref([])

const prodTotalPrice = computed(() => {
  return (
    orderInfo.value.signProducts?.reduce(
      (pre, cur) => pre + (cur?.price || 0) * (cur?.signNum || 0),
      0
    ) || 0
  )
})

// 其他费用
const extraTotalPrice = computed(() => {
  return orderInfo.value.extraPay.reduce((pre, cur) => pre + cur.extraPayMoney, 0)
})

// 额外支出
const extraPayTotalFee = computed(() => {
  return extraPayList.value.reduce((pre, cur) => pre + cur.extraPayMoney, 0)
})

function open(clueId, orderId) {
  try {
    show.value = true
    tabName.value = 'clueInfo'
    getFields()
    ClueApi.getClue(clueId).then((data) => {
      clueInfo.value = { ...data, ...data.diyParams }
    })
    OrderApi.getSign(orderId).then((data) => {
      orderInfo.value = { ...data, ...data.diyParams }
      orderInfo.value.dealDate = formatDate(orderInfo.value.dealDate, 'YYYY-MM-DD HH:mm')
    })
    OrderApi.getSignExtraPayList({ id: orderId }).then((data) => {
      extraPayList.value = data
    })
    getPaymentPage({ signId: orderId, pageNo: 1, pageSize: 100 }).then((data) => {
      returnRecordList.value = data.list
    })
    getAfterSalePage({ signId: orderId, pageNo: 1, pageSize: 100 }).then((data) => {
      aftersaleList.value = data.list
    })
  } catch (error) {
    console.log(error)
  }
}

const clueSchema = ref([])
const orderSchema = ref([])
function getFields() {
  getClueFieldList().then((data) => {
    const arr = useCrudSchemas(data).allSchemas.detailSchema

    arr.forEach((it) => {
      if (it.label.includes('日期')) {
        it.dateFormat = 'YYYY-MM-DD'
      }
    })
    if (arr.length % 2 != 0) {
      arr.push({})
    }
    clueSchema.value = [
      ...arr,
      {
        field: 'requirement',
        label: '诉求',
        span: 2
      },
      {
        field: 'remark',
        label: '备注',
        span: 2,
        isEditor: true
      }
    ]
  })

  getOrderFieldList().then((data) => {
    const list = useCrudSchemas(data).allSchemas.detailSchema
    const arr = []
    list.forEach((it) => {
      if (it.label.includes('日期')) {
        it.dateFormat = 'YYYY-MM-DD'
      }
      if (it.field == 'receivedMoney') {
        checkPermi(['clue:order:return-list']) && arr.push(it)
      } else {
        arr.push(it)
      }
    })
    if (arr.length % 2 != 0) {
      arr.push({})
    }
    orderSchema.value = [
      ...arr,
      {
        field: 'remark',
        label: '备注',
        span: 2,
        isEditor: true
      }
    ]
  })
}

defineExpose({
  open
})
</script>

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