<template>
  <div style="max-height: calc(100vh - 200px); overflow: hidden auto">
    <el-form-item label="订单" :label-position="'top'">
      <el-table :data="formData.data.order" style="width: 100%">
        <el-table-column label="订单号">
          <template v-slot="scope">
            <div>
              <a style="color: #409eff; cursor: pointer; word-break: break-all" @click="clickDetail(scope.row)">
                {{ scope.row.orderNo }}
              </a>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单金额" prop="paymentPrice" />
        <el-table-column label="三梵成本" prop="costAmount" />
        <el-table-column label="预计总利润" prop="expectedProfit" />
      </el-table>
    </el-form-item>
    <el-form-item label="请款" :label-position="'top'">
      <el-table :data="formData.data.payment" style="width: 100%">
        <el-table-column label="请款类型">
          <template v-slot="scope">
            <div>
              {{ dictKeyValue(scope.row.type, expenseType) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="请款金额" prop="amount" />
        <el-table-column label="请款时间" prop="requestsTime" />
        <el-table-column label="打款时间" prop="remitTime" />
      </el-table>
    </el-form-item>
    <el-form-item label="客户付款" :label-position="'top'">
      <el-table :data="formData.data.fundReceived" style="width: 100%">
        <el-table-column label="客户付款金额" prop="receivedAmount" />
        <el-table-column label="付款时间" prop="receivedTime" />
        <el-table-column label="是否认领" prop="hasReceived">
          <template v-slot="scope">
            <div>
              {{ scope.row.hasReceived ? '是' : '否' }}
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item label="总利润" :label-position="'top'">
      <div style="display: flex; justify-content: space-between; width: 100%">
        <span>{{ calculateTotalProfit() }}</span>
        <el-button type="primary" v-if="rowData.hasSettlement != 1" @click="clickSettlement()">利润结算</el-button>
      </div>
    </el-form-item>

    <a-dialog v-if="dialogVisible" v-model="dialogVisible" title="订单详情" style="width: 90%" :footer="false">
      <div style="max-height: calc(100vh - 160px); overflow: hidden auto">
        <div style="width: 100%">
          <el-table :data="orderDetail.orderItemList" :row-style="{ height: '35px' }" header-row-class-name="tableHeader">
            <el-table-column label="图片" width="130">
              <template #default="props">
                <el-image
                  style="width: 100px; height: 100px; border: 1px solid #ccc"
                  v-if="props.row.picUrls && props.row.picUrls.length > 0 && props.row.picUrls[0]"
                  :src="props.row.picUrls[0]"
                  fit="scale-down"
                  :referrerpolicy="'no-referrer'"
                  :zoom-rate="1.2"
                  :preview-src-list="[props.row.picUrls[0]]"
                  :initial-index="0"
                  preview-teleported
                >
                </el-image>
                <el-image
                  style="width: 100px; height: 100px; border: 1px solid #ccc"
                  v-else
                  :src="props.row.picUrl"
                  fit="scale-down"
                  :referrerpolicy="'no-referrer'"
                  :zoom-rate="1.2"
                  :preview-src-list="[props.row.picUrl]"
                  :initial-index="0"
                  preview-teleported
                >
                </el-image>
              </template>
            </el-table-column>
            <el-table-column label="设计图" width="130">
              <template #default="props">
                <el-image
                  style="width: 100px; border: 1px solid #ccc"
                  v-if="props.row.customizeVo && props.row.customizeVo.blueprintUrl"
                  :src="props.row.customizeVo.blueprintUrl"
                  fit="scale-down"
                  :referrerpolicy="'no-referrer'"
                  :zoom-rate="1.2"
                  :preview-src-list="[props.row.customizeVo.blueprintUrl]"
                  :initial-index="0"
                  preview-teleported
                >
                </el-image>
              </template>
            </el-table-column>
            <el-table-column label="商品信息" min-width="300">
              <template #default="props">
                <div>
                  <div>SKU编码：{{ props.row.skuId }}</div>
                  <div>商品名称：{{ props.row.spuName }}</div>
                  <div>商品属性：{{ props.row.attrValue }}</div>
                  <div v-if="orderDetail.type == 1">颜色：{{ props.row.colour || (props.row.customizeVo ? props.row.customizeVo.colour : '') }}</div>
                  <div>规格：{{ props.row.length }} * {{ props.row.width }} * {{ props.row.height }}</div>
                  <div>其他定制明细：{{ props.row.additionalCustomizeDetails }}</div>
                  <div>其他定制总费用：{{ props.row.additionalCustomizePrice }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="单价" width="120">
              <template #default="props">{{ orderDetail.settlementCurrency }} {{ props.row.salesPrice }}</template>
            </el-table-column>
            <el-table-column label="运费" width="120" v-if="orderDetail.deliveryWay == '1'">
              <template #default="props"> {{ orderDetail.settlementCurrency }} {{ props.row.freightPrice }} </template>
            </el-table-column>
            <el-table-column label="数量" prop="quantity" width="120" v-if="orderDetail.type == 1" />
            <el-table-column label="数量" min-width="300" v-if="orderDetail.type == 2">
              <template #default="props">
                <div v-if="props.row.customizeVo.colourList && props.row.customizeVo.colourList.length > 0">
                  <el-table :data="props.row.customizeVo.colourList" :row-style="{ height: '35px' }" header-row-class-name="tableHeader">
                    <el-table-column label="颜色" prop="colour" />
                    <el-table-column label="图片" width="100">
                      <template #default="item">
                        <div>
                          <el-image
                            v-if="item.row.picUrl"
                            :src="item.row.picUrl"
                            style="max-width: 80px"
                            fit="scale-down"
                            :referrerpolicy="'no-referrer'"
                            :zoom-rate="1.2"
                            :preview-src-list="[item.row.picUrl]"
                            :initial-index="0"
                            preview-teleported
                          >
                          </el-image>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column label="SKU编码" prop="skuId" width="140" />
                    <el-table-column label="数量" prop="quantity" />
                  </el-table>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="定制金额" width="140">
              <template #default="props">{{ orderDetail.settlementCurrency }} {{ computeMoney(props.row) }} </template>
            </el-table-column>
            <el-table-column label="商品总金额" width="160">
              <template #default="props">{{ orderDetail.settlementCurrency }} {{ props.row.paymentPrice }} </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="width: 100%; margin-top: 20px" v-if="orderDetail.packagingList && orderDetail.packagingList.length > 0">
          <el-table :data="orderDetail.packagingList" :row-style="{ height: '35px' }" header-row-class-name="tableHeader">
            <el-table-column label="包材名称" prop="name" />
            <el-table-column label="单价">
              <template #default="props">
                <div>{{ orderDetail.settlementCurrency }} {{ props.row.salesPrice }}</div>
              </template>
            </el-table-column>
            <el-table-column label="数量" prop="quantity" />
            <el-table-column label="包材费用小计" width="120">
              <template #default="props">
                <div>{{ orderDetail.settlementCurrency }} {{ packagingSubtotal(props.row) }}</div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="margin-top: 20px; font-size: 18px; font-weight: bold; color: black">
          <span>订单总金额: {{ orderDetail.settlementCurrency }} {{ orderTotal() }}</span>
          <span style="margin-left: 40px"> 商品总金额: {{ orderDetail.settlementCurrency }} {{ goodsTotal() }} </span>
          <span style="margin-left: 40px"> 包材总金额: {{ orderDetail.settlementCurrency }} {{ packagingTotal() }} </span>
        </div>
      </div>
    </a-dialog>
  </div>
</template>

<script setup>
import { getFundReceived, getPayment, getOrderList, settlementProfit } from '@/api/business/contract/info'
import { getListByCodeApi } from '@/api/system/dictData'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  rowData: Object
})
const formData = reactive({
  data: {
    order: [],
    payment: [],
    fundReceived: []
  }
})
const dialogVisible = ref(false)
const orderDetail = ref({
  orderItemList: [],
  packagingList: []
})
const expenseType = ref([])
const calculateTotalProfit = () => {
  let profit = 0
  if (formData.data.fundReceived && formData.data.fundReceived.length > 0) {
    for (let i = 0; i < formData.data.fundReceived.length; i++) {
      profit = Number(Math.round((profit + formData.data.fundReceived[i].receivedAmount) * 100) / 100)
    }
  }
  if (formData.data.payment && formData.data.payment.length > 0) {
    for (let i = 0; i < formData.data.payment.length; i++) {
      profit = Number(Math.round((profit - formData.data.payment[i].amount) * 100) / 100)
    }
  }
  return profit
}
const clickDetail = (row) => {
  orderDetail.value = row
  dialogVisible.value = true
}
const computeMoney = (item) => {
  let money = 0
  if (item.customizeProcessingPrice > 0 && item.quantity > 0) {
    money = Number(Math.round((money + item.customizeProcessingPrice * item.quantity) * 100) / 100)
  }
  return money
}
const packagingSubtotal = (item) => {
  let money = 0
  if (item.salesPrice && item.quantity) {
    let price = Number(item.salesPrice)
    money = Number(Math.round(price * item.quantity * 100) / 100)
  } else {
    money = 0
  }
  return money
}
const packagingTotal = () => {
  let money = 0
  if (orderDetail.value.packagingList && orderDetail.value.packagingList.length > 0) {
    for (let i = 0; i < orderDetail.value.packagingList.length; i++) {
      money = Number(Math.round((money + packagingSubtotal(orderDetail.value.packagingList[i])) * 100) / 100)
    }
  }
  return money
}
const goodsTotal = () => {
  let money = 0
  if (orderDetail.value.orderItemList && orderDetail.value.orderItemList.length > 0) {
    for (let i = 0; i < orderDetail.value.orderItemList.length; i++) {
      if (orderDetail.value.orderItemList[i].paymentPrice) {
        money = Number(Math.round((money + Number(orderDetail.value.orderItemList[i].paymentPrice)) * 100) / 100)
      }
    }
  }
  return money
}
const orderTotal = () => {
  let money = Number(Math.round((goodsTotal() + packagingTotal()) * 100) / 100)
  return money
}
const dictKeyValue = (value, arr) => {
  if ((value || value === 0) && arr) {
    value = value + ''
    const current = arr.find((x) => x.value == value)
    if (current != undefined && current.label) {
      return current.label
    }
    return ''
  }
  return ''
}
const emit = defineEmits(['clickCancel'])
const clickSettlement = () => {
  ElMessageBox.confirm('你是否确认结算利润', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      settlementProfit({ id: props.rowData.id, hasSettlement: 1, settlementProfit: calculateTotalProfit() }).then(() => {
        ElMessage({
          type: 'success',
          message: '结算成功'
        })
        emit('clickCancel', true)
      })
    })
    .catch(() => {})
}
onMounted(() => {
  getListByCodeApi({ code: 'expense_type' }).then((res) => {
    expenseType.value = res
  })
  getFundReceived({ contractId: props.rowData.id }).then((res) => {
    formData.data.fundReceived = res
  })
  getPayment({ contractId: props.rowData.id }).then((res) => {
    formData.data.payment = res
  })
  getOrderList({ contractId: props.rowData.id }).then((res) => {
    formData.data.order = res
  })
})
</script>

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