<script lang="ts" setup name="BusinessSettlementEdit">
import { onMounted, reactive, ref } from 'vue'
import type { Ref } from 'vue'
import dayjs from 'dayjs'
import type { FormInstance, FormRules } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { el } from 'element-plus/es/locale'
import type { IForm, IsampleList } from './businessSettlement-interface'
import multiTable from '@/components/MultiHeaderTable/index.vue'
import { getDictByCode } from '@/api/system/dict'
import { UploadFile } from '@/api/measure/file'
import { calc } from '@/utils/useCalc'
import showPhoto from '@/views/system/tool/showPhoto.vue'
import type { dictType } from '@/global'
import { getTaskDetail } from '@/api/business/schedule/task'
import useUserStore from '@/store/modules/user'
import selectOrder from '@/views/business/schedule/interchangeReceipt/selectOrder.vue'
import type { IOrderList } from '@/views/business/schedule/order/orderList_interface'
import { getOrderDetail } from '@/api/business/schedule/order'
import { isNumber, validateMoney } from '@/utils/validate'
import useCheckList from '@/utils/useCheckList'
import { addBusinessSettlement, getBusinessSettlementDetail, updateBusinessSettlement } from '@/api/finance/businessSettlement'
const user = useUserStore() // 用户信息
const $route = useRoute()
const pageType = ref('detail') // add/detail/edit
const infoId = ref('') // 列表id
const textMap: { [key: string]: string } = {
  edit: '编辑',
  add: '新建',
  detail: '详情',
}// 字典
// 表单数据
const form = ref<IForm>({
  orderCode: '', // 委托单编号
  orderId: '', // 委托单id
  customerName: '', // 委托方名称
  orderTime: '', // 委托日期
  sampleCount: '', // 样品数量
  certificationCompany: '', // 证书单位名称
  certificationCompanyAddress: '', // 证书单位地址
  deliverer: '', // 联系人
  delivererTel: '', // 联系方式
  sampleWarehouse: '未入库', // 样品库房
  certWarehouse: '未入库', // 证书库房
  feeStatus: '未录费', // 费用状态
  received: '未到账', // 是否到账
  actualTestFee: 0, // 检测费(实)(元)
  shouldTestFee: 0, // 检测费(应)(元)
  actualTotalFee: 0, // 实收合计(元)
  receivedAmount: 0, // 到账金额(元)
  invoiceAmount: 0, // 开票金额(元)
  remark: '', // 备注
  orderType: '', // 任务单类型 1检测委托单、2校准委托单
})
// 表单校验规则
const rules = reactive<FormRules>({
  orderCode: [{ required: true, message: '委托单编号必填', trigger: 'blur' }],
  customerName: [{ required: true, message: '委托方名称必填', trigger: 'blur' }],
  orderTime: [{ required: true, message: '委托日期必填', trigger: 'blur' }],
  sampleCount: [{ required: true, message: '样品数量必填', trigger: 'blur' }],
  certificationCompany: [{ required: true, message: '证书单位名称必填', trigger: 'blur' }],
  certificationCompanyAddress: [{ required: true, message: '证书单位地址必填', trigger: 'blur' }],
  deliverer: [{ required: true, message: '联系人必填', trigger: 'blur' }],
  delivererTel: [{ required: true, message: '联系电话必填', trigger: 'blur' }],
  sampleWarehouse: [{ required: true, message: '样品库房必填', trigger: 'blur' }],
  certWarehouse: [{ required: true, message: '证书库房必填', trigger: 'blur' }],
  feeStatus: [{ required: true, message: '费用状态必填', trigger: 'blur' }],
  received: [{ required: true, message: '是否到账必填', trigger: 'blur' }],
  actualTestFee: [{ required: true, message: '检测费(实)(元)必填', trigger: 'blur' }],
  shouldTestFee: [{ required: true, message: '检测费(应)(元)必填', trigger: 'blur' }],
  actualTotalFee: [{ required: true, message: '实收合计(元)必填', trigger: 'blur' }],
  receivedAmount: [{ required: true, message: '到账金额(元)必填', trigger: 'blur' }],
  invoiceAmount: [{ required: true, message: '开票金额(元)必填', trigger: 'blur' }],
})
const ruleFormRef = ref<FormInstance>() as any
const orderVisible = ref(false) // 控制委托单对话框显隐

// ---------------------------------------路由参数--------------------------------------
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string
  infoId.value = $route.params.id as string
}
// ---------------------------------------字典--------------------------------------

const financeSampleWarehouseList = ref<dictType[]>([]) // 样品库房
const financeCertWarehouseList = ref<dictType[]>([]) // 证书库房
const financeReceivedList = ref<dictType[]>([]) // 是否到账
// 获取字典值
function getDict() {
  // 样品库房
  getDictByCode('financeSampleWarehouse').then((response) => {
    financeSampleWarehouseList.value = response.data
  })
  // 证书库房
  getDictByCode('financeCertWarehouse').then((response) => {
    financeCertWarehouseList.value = response.data
  })
  // 是否到账
  getDictByCode('financeReceived').then((response) => {
    financeReceivedList.value = response.data
  })
}
getDict()
// -----------------------------------到账金额明细--------------------------------------------------
const receivedAmountList = ref([]) as any // 到账金额明细
const checkoutReceivedAmountList = ref([]) as any // 到账金额明细多选
// 表头
const receivedAmountcolumns = ref([
  { text: '到账金额（元）', value: 'money', align: 'center', width: '220', required: true },
  { text: '到账时间', value: 'moneyTime', align: 'center', width: '220', required: true },
  { text: '附件', value: 'attachment', align: 'center', required: false },
])

// -------------------------------------开票金额明细--------------------------------------------------------------
const invoiceAmountList = ref([]) as any // 开票金额明细
const checkoutInvoiceAmountList = ref([]) as any // 开票金额明细多选
// 表头
const invoiceAmountcolumns = ref([
  { text: '开票金额（元）', value: 'money', align: 'center', width: '220', required: true },
  { text: '开票时间', value: 'moneyTime', align: 'center', width: '220', required: true },
  { text: '附件', value: 'attachment', align: 'center', required: false },
])

// 多选发生改变时
const handleSelectionChange = (e: any, type: 'addReceived' | 'invoiceAmount') => {
  if (type === 'addReceived') { // 到账金额明细
    checkoutReceivedAmountList.value = e
  }
  else { // 开票金额明细
    checkoutInvoiceAmountList.value = e
  }
}

// 点击增加行
const addRow = (type: 'addReceived' | 'invoiceAmount') => {
  if (type === 'addReceived') {
    if (useCheckList(receivedAmountList.value, receivedAmountcolumns.value, '到账金额明细')) {
      receivedAmountList.value.push({
        money: undefined,
        moneyTime: '',
        attachment: [],
        moneyType: '1',
      })
    }
  }
  else {
    if (useCheckList(invoiceAmountList.value, invoiceAmountcolumns.value, '开票金额明细')) {
      invoiceAmountList.value.push({
        money: undefined,
        moneyTime: '',
        attachment: [],
        moneyType: '2',
      })
    }
  }
}

// 删除行
const delRow = (type: 'addReceived' | 'invoiceAmount') => {
  if ((type === 'addReceived' && checkoutReceivedAmountList.value.length <= 0) || (type === 'invoiceAmount' && checkoutInvoiceAmountList.value.length <= 0)) {
    ElMessage({
      message: '请选中要删除的行',
      type: 'warning',
    })
  }
  else {
    if (type === 'addReceived') {
      receivedAmountList.value = receivedAmountList.value.filter(
        (item: any) => {
          return !checkoutReceivedAmountList.value.includes(item)
        },
      )
    }
    else {
      invoiceAmountList.value = invoiceAmountList.value.filter(
        (item: any) => {
          return !checkoutInvoiceAmountList.value.includes(item)
        },
      )
    }
  }
}

// ----------------------------------------上传附件----------------------------------------------------
const uploadIndex = ref(0) // 上传附件的索引
const uploadType = ref('receivedAmount') // 上传附件的表格类型
// 删除附件
const del = (index: number, row: any) => {
  row.attachment.splice(index, 1)
}

const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  // 原生上传
  const files = event.target.files
  if (files.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    for (var i = 0; i < files.length; i++) {
      fd.append('multipartFile', files[i])
    }
    const loading = ElLoading.service({})

    UploadFile(fd).then((res) => {
      if (res.code === 200) {
        res.data.forEach((item: string) => {
          if (uploadType.value === 'receivedAmount') { // 到账金额明细
            receivedAmountList.value[uploadIndex.value].attachment.push(item)
            console.log('receivedAmountList', receivedAmountList.value)
          }
          else { // 开票金额明细
            invoiceAmountList.value[uploadIndex.value].attachment.push(item)
          }
        })
        ElMessage.success('文件上传成功')
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
const upload = (index: number, type: 'receivedAmount' | 'invoiceAmount') => {
  uploadIndex.value = index
  uploadType.value = type
  fileRef.value.click()
}
// ------------------------------------结算明细--------------------------------------------------------------------
const list = ref([]) // 开票金额明细
// 表头
const columns = ref([
  { text: '器具名称', value: 'sampleName', align: 'center', required: true, type: 'text' },
  { text: '型号规格', value: 'sampleModel', align: 'center', width: '180', required: true, type: 'input' },
  { text: '套数/退', value: 'sets', align: 'center', required: true, width: '180', type: 'inputNumber' },
  { text: '出厂编号', value: 'manufacturingNo', align: 'center', width: '180', required: true, type: 'input' },
  { text: '委托日期', value: 'orderTime', align: 'center', required: true, width: '160', type: 'date' },
  { text: '检测规范', value: 'accordStandard', align: 'center', width: '180', required: false, type: 'input' },
  {
    text: '收费（元）含6%增值税',
    value: 'price',
    align: 'center',
    required: false,
    children: [
      { text: '检测费（应）', value: 'shouldTestFee', align: 'center', width: '180', required: true, type: 'inputNumber' },
      { text: '检测费（实）', value: 'actualTestFee', align: 'center', required: true, width: '180', type: 'inputNumber' },
      // { text: '附加费', value: 'extraFee', align: 'center', required: false, width: '180', type: 'inputNumber' },
      // { text: '修理费', value: 'repairFee', align: 'center', required: false, width: '180', type: 'inputNumber' },
      // { text: '其他费', value: 'otherFee', align: 'center', required: false, width: '180', type: 'inputNumber' },
      { text: '小计', value: 'subtotal', align: 'center', required: false, type: 'text' },
    ],
  },
])

// 表头
const columns_measure = ref([
  { text: '样品名称名称', value: 'sampleName', align: 'center', required: true, type: 'text' },
  { text: '检测项目', value: 'measureContent', align: 'center', required: true, type: 'input' },
  { text: '测试规范', value: 'accordStandard', align: 'center', required: true, type: 'input' },
  { text: '检测单价（元）', value: 'shouldTestFee', align: 'center', width: '180', required: false, type: 'inputNumber' },
  { text: '备注', value: 'remark', align: 'center', required: false, type: 'text' },
])

// ------------------------------------委托单---------------------------------------------
// 点击选择委托单编号
const handleClickOrder = () => {
  orderVisible.value = true
}
// 修改委托单对话框显隐
const changeOrderVisible = (val: boolean) => {
  orderVisible.value = val
}
// 选好委托单
const confirmCheckoutOrder = (val: Array<IOrderList>) => {
  if (val && val.length) {
    form.value.orderType = val[0].orderType
    getOrderDetail({ id: val[0].id }).then((res) => { // 样品清单
      form.value.orderCode = res.data.orderCode // 委托单编号
      form.value.orderId = res.data.id // 委托单id
      form.value.customerName = res.data.customerName // 委托方名称
      form.value.orderTime = res.data.createTime // 委托日期（委托单创建时间）
      form.value.certificationCompany = res.data.certificationCompany // 证书单位名称
      form.value.certificationCompanyAddress = res.data.certificationCompanyAddress // 证书单位地址
      form.value.deliverer = res.data.deliverer // 联系人
      form.value.delivererTel = res.data.delivererTel // 联系方式
      form.value.sampleCount = res.data.customerSampleInfoList.length // 样品数量
      list.value = res.data.customerSampleInfoList.map((item: { createTime: string; editable: boolean }) => {
        return {
          ...item,
          orderTime: item.createTime ? dayjs(item.createTime).format('YYYY-MM-DD') : item.createTime, // 委托日期
          editable: pageType.value !== 'detail',
          shouldTestFee: 0, // 检测费（应）
          actualTestFee: 0, // 检测费（实）
          extraFee: 0, // 附加费
          repairFee: 0, // 修理费
          otherFee: 0, // 其他费
          sets: 0, // 套数
          subtotal: 0, // 小计
          id: '',
        }
      })
    })
  }
}
// --------------------------------------------计算----------------------------------------------
// 计算
const handleInputNumberChange = ({ row }: any) => {
  if (form.value.orderType === '2') {
    // 计算小计
    row.subtotal = calc(Number(calc(Number(calc(Number(calc(Number(row.shouldTestFee), Number(row.actualTestFee), '+')), row.extraFee, '+')), row.repairFee, '+')), row.otherFee, '+')
    // 计算检测费(应)(元)
    form.value.shouldTestFee = list.value.reduce((accumulator, current: any) => accumulator + current.shouldTestFee, 0)
    // 计算检测费(实)(元)
    form.value.actualTestFee = list.value.reduce((accumulator, current: any) => accumulator + current.actualTestFee, 0)
    // 实收合计
    form.value.actualTotalFee = list.value.reduce((accumulator, current: any) => accumulator + current.subtotal, 0)
    if (list.value.every((item: { actualTestFee: number }) => item.actualTestFee === 0 || `${item.actualTestFee}` === 'undefined' || `${item.actualTestFee}` === 'null' || `${item.actualTestFee}` === '')) {
      form.value.feeStatus = '未录费'
    }
    else if (list.value.every((item: { actualTestFee: number }) => item.actualTestFee !== 0 || `${item.actualTestFee}` === 'undefined' || `${item.actualTestFee}` === 'null' || `${item.actualTestFee}` === '')) {
      form.value.feeStatus = '已录费'
    }
    else {
      form.value.feeStatus = '部分录费'
    }
  }
  else if (form.value.orderType === '1') {
    // 计算检测单价的和
    form.value.actualTotalFee = list.value.reduce((accumulator, current: any) => accumulator + current.shouldTestFee, 0)
    if (list.value.every((item: { shouldTestFee: number }) => item.shouldTestFee === 0 || `${item.shouldTestFee}` === 'undefined' || `${item.shouldTestFee}` === 'null' || `${item.shouldTestFee}` === '')) {
      form.value.feeStatus = '未录费'
    }
    else if (list.value.every((item: { shouldTestFee: number }) => item.shouldTestFee !== 0 || `${item.shouldTestFee}` === 'undefined' || `${item.shouldTestFee}` === 'null' || `${item.shouldTestFee}` === '')) {
      form.value.feeStatus = '已录费'
    }
    else {
      form.value.feeStatus = '部分录费'
    }
  }
}

const changeTableInputNumber = () => {
  // 到账金额
  form.value.receivedAmount = receivedAmountList.value.reduce((accumulator: any, current: any) => accumulator + current.money, 0)
  // 开票金额
  form.value.invoiceAmount = invoiceAmountList.value.reduce((accumulator: any, current: any) => accumulator + current.money, 0)
}

// ----------------------------------------------------------------------------------------
const $router = useRouter()
// 点击关闭
const close = () => {
  $router.back()
}

// 校验表格
const checkList = () => {
  if (!receivedAmountList.value.length) {
    ElMessage.warning('到账金额明细不能为空')
    return false
  }
  if (!invoiceAmountList.value.length) {
    ElMessage.warning('开票金额明细不能为空')
    return false
  }
  if (!list.value.length) {
    ElMessage.warning('结算明细不能为空')
    return false
  }
  if (!useCheckList(receivedAmountList.value, receivedAmountcolumns.value, '到账金额明细')) {
    return false
  }
  if (!useCheckList(invoiceAmountList.value, invoiceAmountcolumns.value, '开票金额明细')) {
    return false
  }
  console.log(form.value.orderType, 'form.value.orderType')

  if (form.value.orderType === '1') {
    if (!useCheckList(list.value, columns_measure.value, '结算明细')) {
      return false
    }
  }
  else {
    if (!useCheckList(list.value, columns.value, '结算明细')) {
      return false
    }
  }

  return true
}

// 保存
const save = () => {
  if (!checkList()) {
    return false
  }
  ruleFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const loading = ElLoading.service({
        lock: true,
        background: 'rgba(255, 255, 255, 0.8)',
      })
      const receivedAmount = receivedAmountList.value.map((item: any) => {
        return {
          ...item,
          attachment: Array.isArray(item.attachment) ? item.attachment.join(',') : item.attachment,
        }
      })
      const invoiceAmount = invoiceAmountList.value.map((item: any) => {
        return {
          ...item,
          attachment: Array.isArray(item.attachment) ? item.attachment.join(',') : item.attachment,
        }
      })
      const params = {
        id: infoId.value,
        ...form.value,
        amountDetailsList: receivedAmount.concat(invoiceAmount),
        sampleList: list.value,
      }
      // 新建
      if (pageType.value === 'add') {
        addBusinessSettlement(params).then((res) => {
          ElMessage.success('保存成功')
          loading.close()
          close()
        }).catch(() => {
          loading.close()
        })
      }
      // 编辑
      else if (pageType.value === 'edit') {
        updateBusinessSettlement(params).then((res) => {
          ElMessage.success('保存成功')
          loading.close()
          close()
        }).catch(() => {
          loading.close()
        })
      }
    }
    else {
      console.log('表单校验不通过')
    }
  })
}

// 编辑、详情--获取详细信息
const fetchDetail = () => {
  const loading = ElLoading.service({})
  getBusinessSettlementDetail({ id: infoId.value }).then((res) => {
    form.value = res.data
    const amountList = res.data.amountDetailsList.map((item: { attachment: string }) => {
      return {
        ...item,
        attachment: item.attachment ? item.attachment.split(',') : item.attachment,
      }
    })
    receivedAmountList.value = amountList.filter((item: { moneyType: string }) => `${item.moneyType}` === '1')
    invoiceAmountList.value = amountList.filter((item: { moneyType: string }) => `${item.moneyType}` === '2')
    list.value = res.data.sampleDetailsList.map((item: { editable: boolean; orderTime: string }) => {
      return {
        ...item,
        editable: pageType.value !== 'detail',
        orderTime: item.orderTime ? dayjs(item.orderTime).format('YYYY-MM-DD') : item.orderTime,
      }
    })
    form.value.orderTime = res.data.sampleDetailsList[0].orderTime // 委托日期
    form.value.sampleCount = res.data.sampleDetailsList.length // 样品数量
    loading.close()
  }).catch(() => loading.close())
}

onMounted(() => {
  // 编辑、详情获取详情页信息
  if (pageType.value === 'edit' || pageType.value === 'detail') {
    fetchDetail() // 获取详细信息
  }
})
</script>

<template>
  <app-container class="finance-businessSettlement">
    <detail-page :title="`业务结算-${textMap[pageType]}`">
      <template #btns>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="save">
          保存
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <div id="form">
        <el-form
          ref="ruleFormRef"
          :model="form"
          :label-width="120"
          label-position="right"
          :rules="rules"
        >
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="委托单编号:" prop="orderCode">
                <el-input
                  v-model="form.orderCode"
                  :placeholder="pageType === 'detail' ? '' : '请选择委托单编号'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                >
                  <template v-if="pageType !== 'detail'" #append>
                    <el-button size="small" @click="handleClickOrder">
                      选择
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="委托方名称:" prop="customerName">
                <el-input
                  v-model="form.customerName"
                  :placeholder="pageType === 'detail' ? '' : '委托方名称'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="委托日期:" prop="orderTime">
                <el-date-picker
                  v-model="form.orderTime"
                  type="date"
                  class="full-width-input"
                  :placeholder="pageType === 'detail' ? '' : '委托日期'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="样品数量:" prop="sampleCount">
                <el-input
                  v-model="form.sampleCount"
                  :placeholder="pageType === 'detail' ? '' : '样品数量'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="证书单位名称:" prop="certificationCompany">
                <el-input
                  v-model="form.certificationCompany"
                  :placeholder="pageType === 'detail' ? '' : '证书单位名称'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="证书单位地址:" prop="certificationCompanyAddress">
                <el-input
                  v-model="form.certificationCompanyAddress"
                  :placeholder="pageType === 'detail' ? '' : '证书单位地址'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系人" prop="deliverer">
                <el-input
                  v-model="form.deliverer"
                  :placeholder="pageType === 'detail' ? '' : '联系人'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系电话" prop="delivererTel">
                <el-input
                  v-model="form.delivererTel"
                  :placeholder="pageType === 'detail' ? '' : '联系电话'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="样品库房" prop="sampleWarehouse">
                <el-select
                  v-model="form.sampleWarehouse"
                  :disabled="pageType === 'detail'"
                  placeholder="请选择样品库房"
                  style="width: 100%;"
                  filterable
                >
                  <el-option v-for="item in financeSampleWarehouseList" :key="item.id" :label="item.name" :value="item.name" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="证书库房" prop="certWarehouse">
                <el-select
                  v-model="form.certWarehouse"
                  :disabled="pageType === 'detail'"
                  placeholder="请选择证书库房"
                  style="width: 100%;"
                  filterable
                >
                  <el-option v-for="item in financeCertWarehouseList" :key="item.id" :label="item.name" :value="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="费用状态" prop="feeStatus">
                <el-input
                  v-model="form.feeStatus"
                  :placeholder="pageType === 'detail' ? '' : '费用状态'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否到账" prop="received">
                <el-select
                  v-model="form.received"
                  :disabled="pageType === 'detail'"
                  placeholder="请选择是否到账"
                  style="width: 100%;"
                  filterable
                >
                  <el-option v-for="item in financeReceivedList" :key="item.id" :label="item.name" :value="item.name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="form.orderType === '2'" :span="6">
              <el-form-item label="检测费(实)(元)" prop="actualTestFee">
                <el-input
                  v-model="form.actualTestFee"
                  :placeholder="pageType === 'detail' ? '' : '检测费(实)(元)'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col v-if="form.orderType === '2'" :span="6">
              <el-form-item label="检测费(应)(元)" prop="shouldTestFee">
                <el-input
                  v-model="form.shouldTestFee"
                  :placeholder="pageType === 'detail' ? '' : '检测费(应)(元)'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="form.orderType === '2' ? '实收合计(元) : ' : '报价合计(元) : '" prop="actualTotalFee">
                <el-input
                  v-model="form.actualTotalFee"
                  :placeholder="pageType === 'detail' ? '' : '实收合计(元)'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="到账金额(元)" prop="receivedAmount">
                <el-input
                  v-model="form.receivedAmount"
                  :placeholder="pageType === 'detail' ? '' : '到账金额(元)'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="开票金额(元)" prop="invoiceAmount">
                <el-input
                  v-model="form.invoiceAmount"
                  :placeholder="pageType === 'detail' ? '' : '开票金额(元)'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="备注:">
                <el-input
                  v-model.trim="form.remark"
                  :placeholder="pageType === 'detail' ? '' : '请输入备注'"
                  class="full-width-input"
                  type="textarea"
                  autosize
                  clearable
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </detail-page>
    <input v-show="false" ref="fileRef" type="file" name="upload" multiple @change="onFileChange">
    <detail-block title="到账金额明细">
      <template #btns>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="addRow('addReceived')">
          增加行
        </el-button>
        <el-button v-if="pageType !== 'detail'" type="info" @click="delRow('addReceived')">
          删除行
        </el-button>
      </template>
      <el-table
        :data="receivedAmountList"
        border
        style="width: 100%;"
        max-height="600"
        @selection-change="(e) => handleSelectionChange(e, 'addReceived')"
      >
        <el-table-column v-if="pageType !== 'detail'" type="selection" width="38" />
        <el-table-column align="center" label="序号" width="80" type="index" />
        <el-table-column
          v-for="item in receivedAmountcolumns"
          :key="item.value"
          :prop="item.value"
          :label="item.text"
          :width="item.width"
          align="center"
        >
          <template #header>
            <span v-show="item.required" style="color: red;">*</span><span>{{ item.text }}</span>
          </template>
          <template #default="scope">
            <el-input-number
              v-if="item.value === 'money' && pageType !== 'detail'"
              v-model="scope.row[item.value]"
              class="full-width-input"
              :min="0"
              @change="changeTableInputNumber"
            />
            <el-date-picker
              v-if="item.value === 'moneyTime' && pageType !== 'detail'"
              v-model="scope.row[item.value]"
              type="date"
              class="full-width-input"
              :placeholder="pageType === 'detail' ? '' : '到账时间'"
              :class="{ 'detail-input': pageType === 'detail' }"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />

            <div v-if="item.value === 'attachment'">
              <el-button v-if="pageType !== 'detail'" type="primary" :style="{ 'margin-right': '20px', 'float': 'right' }" @click="upload(scope.$index, 'receivedAmount')">
                {{ '上传' }}
              </el-button>
              <div v-for="(item, index) in scope.row.attachment" :key="index" style="display: flex;padding: 6px 0;justify-content: center;">
                <show-photo :minio-file-name="item">
                  <span v-if="pageType !== 'detail' && item" class="photo-close" @click="del(index, scope.row)">×</span>
                </show-photo>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </detail-block>
    <detail-block title="开票金额明细">
      <template #btns>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="addRow('invoiceAmount')">
          增加行
        </el-button>
        <el-button v-if="pageType !== 'detail'" type="info" @click="delRow('invoiceAmount')">
          删除行
        </el-button>
      </template>

      <el-table
        :data="invoiceAmountList"
        border
        style="width: 100%;"
        max-height="600"
        @selection-change="(e) => handleSelectionChange(e, 'invoiceAmount')"
      >
        <el-table-column v-if="pageType !== 'detail'" type="selection" width="38" />
        <el-table-column align="center" label="序号" width="80" type="index" />
        <el-table-column
          v-for="item in invoiceAmountcolumns"
          :key="item.value"
          :prop="item.value"
          :label="item.text"
          :width="item.width"
          align="center"
        >
          <template #header>
            <span v-show="item.required" style="color: red;">*</span><span>{{ item.text }}</span>
          </template>
          <template #default="scope">
            <el-input-number
              v-if="item.value === 'money' && pageType !== 'detail'"
              v-model="scope.row[item.value]"
              class="full-width-input"
              :min="0"
              @change="changeTableInputNumber"
            />
            <el-date-picker
              v-if="item.value === 'moneyTime' && pageType !== 'detail'"
              v-model="scope.row[item.value]"
              type="date"
              class="full-width-input"
              :placeholder="pageType === 'detail' ? '' : '到账时间'"
              :class="{ 'detail-input': pageType === 'detail' }"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />

            <div v-if="item.value === 'attachment'">
              <el-button v-if="pageType !== 'detail'" type="primary" :style="{ 'margin-right': '20px', 'float': 'right' }" @click="upload(scope.$index, 'invoiceAmount')">
                {{ '上传' }}
              </el-button>
              <div v-for="(item, index) in scope.row.attachment" :key="index" style="display: flex;padding: 10px 0;justify-content: center;">
                <show-photo :minio-file-name="item">
                  <span v-if="pageType !== 'detail' && item" class="photo-close" @click="del(index, scope.row)">×</span>
                </show-photo>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </detail-block>
    <detail-block title="结算明细" style="margin-bottom: 32px;">
      <multi-table
        v-if="form.orderType === '2'"
        :table-data="list"
        :table-header="columns"
        :need-index="true"
        :min="0"
        @handleInputNumberChange="handleInputNumberChange"
      />

      <multi-table
        v-if="form.orderType === '1'"
        :table-data="list"
        :table-header="columns_measure"
        :need-index="true"
        :min="0"
        @handleInputNumberChange="handleInputNumberChange"
      />
    </detail-block>
    <!-- 选择委托单组件 -->
    <select-order v-model:visible="orderVisible" @confirmCheckout="confirmCheckoutOrder" @changeVisible="changeOrderVisible" />
  </app-container>
</template>

<style lang="scss" scoped>
// 样式
.create-check {
  margin-top: 10px;

  .top-info {
    display: flex;
    flex-direction: column;
    width: 100%;
    padding-right: 10px;
    border-radius: 10px;
    background-color: #fff;
    // padding: 10px;

    .title-button {
      display: flex;
      align-items: center;

      &::before {
        content: "";
        flex: 1;
      }

      .button-group {
        flex: 1;
        display: flex;
        justify-content: flex-end;
      }
    }

    .form-area {
      margin-top: 40px;
    }
  }
}
</style>

<style lang="scss">
.finance-businessSettlement {
  // 单元格样式
  .el-table__cell {
    position: static !important; // 解决el-image 和 el-table冲突层级冲突问题
  }
}
</style>
