<!-- 计量数据管理 -->
<script lang="ts" setup>
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { ref } from 'vue'
import dayjs from 'dayjs'
import EnvironmentalDialog from '../components/environmentalDialog.vue'
import selectSignature from '../components/selectSignature.vue'
import selectReportTemplate from '../components/selectReportTemplate.vue'
import SelectOrderSamplesDialog from '../components/selectOrderSamplesDialog.vue'
import SelectSamplesDialog from '../components/selectSamplesDialog.vue'
import selectMeasureDevice from '../components/selectMeasureDevice.vue'
import selectMyMeasureDialog from './dialog/selectMyMeasureDialog.vue'
import type { IEquipmentList, IForm, ISampleList } from './measureData-interface'
import selectMeasueDataDialog from './dialog/selectMeasueDataDialog.vue'
import selectTechFilesDialog from './dialog/selectTechFilesDialog.vue'
import selectApproverDialog from '@/components/Approval/selectApproverDialog.vue'
import ApprovalDialog from '@/components/Approval/ApprovalDialogCustom.vue'
import { getCustomerList } from '@/api/customer/customer'
import { getPhotoUrl, listPageApi } from '@/api/system/tool'
import { SCHEDULE } from '@/utils/scheduleDict'
import { UploadFile } from '@/api/measure/file'
import { updateSample } from '@/api/customer/sampleList'
import ExcelEdit from '@/views/business/lab/excelEdit/excelEditDialog.vue'
import { importFile, importSjsFile } from '@/views/business/lab/excelEdit'
import { getStaffList } from '@/api/measure/person'
// import ApprovalDialog from '@/components/Approval/ApprovalDialogByProcess.vue'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { addMeasureData, downLoadTemplate, draftUpdateMeasureData, failUpdateMeasureData, getMeasureDataDetail, submit } from '@/api/business/lab/measureData'
import { cancelApproval, fetchApproval, submitApproval } from '@/api/approval'
import showPhoto from '@/views/system/tool/showPhoto.vue'
import { getDictByCode } from '@/api/system/dict'
import useUserStore from '@/store/modules/user'
import selectOrder from '@/views/business/schedule/interchangeReceipt/selectOrder.vue'
import { download, downloadFile } from '@/utils/download'
import type { dictType } from '@/global'
import { getOrderDetail } from '@/api/business/schedule/order'
import { exportFile } from '@/utils/exportUtils'
import customApproval from '/public/config/customApproval.json'

const user = useUserStore() // 用户信息
const showSaveBtn = ref(true)
const textMap: { [key: string]: string } = {
  edit: '编辑',
  add: '新建',
  detail: '详情',
}// 字典
const { proxy } = getCurrentInstance() as any
const $router = useRouter() // 关闭页面使用
const $route = useRoute()
const query = $route.query
const approvalDialog = ref() // 审批对话ref
const pageType = ref('add') // 页面类型: add, edit, detail
const infoId = ref('') // 列表id
const submitId = ref('') // 新建提交时所用的id
const orderVisible = ref(false) // 控制委托单对话框显隐
const ruleFormRef = ref<FormInstance>() as any
const form = ref<IForm>({
  invalid: 0, // 替代已生成证书
  formId: SCHEDULE.BUSINESS_REPORT_ON_CREDENTIALS,
  oldCertificateCode: '', // 原证书
  calibrationMajor: '', // 检校专业
  calibrationMajorName: '', // 检校专业名称
  certificateReportCategory: '', // 证书类别
  certificateReportCategoryName: '', // 证书类别名称
  certificateReportCode: '', // 证书编号
  certificateReportName: '', // 证书名称
  measurePerson: '', // 检定员
  measurePersonId: '', // 检定员id
  calibrationTime: '', // 检校日期

  orderCode: '', // 委托单编号
  orderId: '', // 委托单id
  customerName: '', // 委托方名称
  customerAddress: '', // 委托方地址
  certificationCompany: '', // 证书单位名称
  certificationCompanyAddress: '', // 证书单位地址
  calibrationPlace: '', // 检校地点

  repeatTime: undefined, // 复校时间
  deliverTime: '', // 接收时间
  measureResult: '', // 检定结果
  environmentCode: '', // 环境记录单编号
  environmentId: '', // 环境记录单id
  temperature: '', // 温度
  humidity: '', // 湿度
  techFilesName: '', // 依据的技术文件名称
  signId: '', // 	电子签章id
  signName: '', // 	电子签章名称
  approvalSignIds: '', // 认可标志专用章id
  approvalSignName: '', // 认可标志专用章名称
  remark: '', // 备注
  busPersonId: '', //	业务员id
  busPersonName: '', // 业务员名字
  templateId: '', // 证书模板
  templateName: '', // 证书模板
  certificateReportFile: '', // 证书报告附件
})

// 校验规则
const formRules = ref<FormRules>({
  oldCertificateCode: [{ required: true, message: '原证书必填', trigger: ['blur', 'change'] }],
  calibrationMajor: [{ required: true, message: '检校专业必填', trigger: ['blur', 'change'] }],
  certificateReportCategory: [{ required: true, message: '证书类别必填', trigger: ['blur', 'change'] }],
  certificateReportName: [{ required: true, message: '证书名称必填', trigger: ['blur', 'change'] }],
  customerName: [{ required: true, message: '委托方名称必填', trigger: ['blur', 'change'] }],
  customerAddress: [{ required: true, message: '委托方地址必填', trigger: ['blur', 'change'] }],
  certificationCompany: [{ required: true, message: '证书单位名称必填', trigger: ['blur', 'change'] }],
  certificationCompanyAddress: [{ required: true, message: '证书单位地址必填', trigger: ['blur', 'change'] }],
  calibrationPlace: [{ required: true, message: '检校地点必填', trigger: ['blur', 'change'] }],
  measurePerson: [{ required: true, message: '检定员必填', trigger: ['blur', 'change'] }],
  calibrationTime: [{ required: true, message: '检校日期必填', trigger: ['blur', 'change'] }],
  // repeatTime: [{ required: true, message: '复校时间必填', trigger: ['blur', 'change'] }],
  deliverTime: [{ required: true, message: '接收时间必填', trigger: ['blur', 'change'] }],
  measureResult: [{ required: true, message: '检定结果必填', trigger: ['blur', 'change'] }],
  temperature: [
    { required: true, message: '温度必填', trigger: ['blur', 'change'] },
    { pattern: /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/, message: '温度只能为数字', trigger: ['blur', 'change'] },
  ],
  humidity: [{ required: true, message: '相对湿度必填', trigger: ['blur', 'change'] },
    { pattern: /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/, message: '相对湿度只能为数字', trigger: ['blur', 'change'] },
  ],
  signName: [{ required: true, message: '电子签章必填', trigger: ['blur', 'change'] }],
  techFilesName: [{ required: true, message: '所依据的技术文件必填', trigger: ['blur', 'change'] }],
})

// 从路由中获取页面类型参数
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string
  console.log(pageType.value)

  if ($route.params.id) {
    infoId.value = $route.params.id as string
  }
}
// ---------------------------------------字典--------------------------------------------
const certificationTypeMap = ref<dictType[]>([]) // 证书类别
const calibrationMajorMap = ref<dictType[]>([]) // 校检专业
const signTypeMap = ref<dictType[]>([]) // 签章类型

// 获取字典值
async function getDict() {
  // 校检专业
  const response = await getDictByCode('calibrationMajor')
  calibrationMajorMap.value = response.data
  // 证书类别
  const rescertificationType = await getDictByCode('certificationType')
  certificationTypeMap.value = rescertificationType.data

  // 签章类型
  const resSignType = await getDictByCode('signType')
  signTypeMap.value = resSignType.data
}
getDict()

// -------------------------------------原证书--------------------------------------------
const selectMeasueDataDialogRef = ref() // 选择原证书组件ref
// 点击选择原证书
const selectOrigin = () => {
  selectMeasueDataDialogRef.value.initDialog()
}
// 选好原证书
const selectMeasueDataConfirm = (val: any) => {
  getDetail(val.id, val.certificateReportCode)
}

// -------------------------------选择环境记录单----------------------------------------
const businessEnvironmentRecord = ref({}) as any // 环境记录单信息
// 选择环境记录单Ref
const environmentalDialog = ref()
// 选择环境记录单
const environmentalClick = () => {
  environmentalDialog.value.initDialog()
}
// 选择环境记录单表格确认
const environmentalAdd = (data: any) => {
  businessEnvironmentRecord.value = data
  form.value.environmentId = data.id // 环境记录单id
  form.value.environmentCode = data.environmentCode // 环境记录单编号
  form.value.temperature = data.temperature // 温度
  form.value.humidity = data.humidity // 湿度
}
// --------------------------------------选择签章-----------------------------------
// 选择签章Ref
const signatureDialog = ref()
// 选择签章模板
const handleClickSignature = () => {
  signatureDialog.value.initDialog('1', form.value.signId)
}
// 选择签章确认
const confirmCheckoutSignature = (val: any) => {
  form.value.signId = val[0].id // 电子签章id
  form.value.signName = val[0].signName || '' // 电子签章名称
}

// --------------------------------------选择认可标志专用章-----------------------------------
// 选择认可标志专用章ref
const specialSignatureDialog = ref()
// 选择认可标志专用章
const handleClickSpecialSignature = () => {
  specialSignatureDialog.value.initDialog('2')
}
// 选择认可标志专用章确认
const confirmCheckoutSpecialSignature = (val: any) => {
  let ids = '' // id
  let names = '' // 名字
  val.forEach((item: any, index: number) => {
    if (index === 0) {
      ids = ids + item.id
      names = names + item.signName
    }
    else {
      ids = `${ids},${item.id}`
      names = `${names},${item.signName}`
    }
  })
  form.value.approvalSignIds = ids // 认可标志专用章id
  form.value.approvalSignName = names // 认可标志专用章名称
}

// -----------------------------------------所依据的技术文件----------------------------------
const selectTechFilesRef = ref()
const fileList = ref([]) as any // 依据的技术文件
// 点击所依据的技术文件
const selectTechFiles = () => {
  selectTechFilesRef.value.initDialog('10', true)
}
// 选好依据的技术文件
const selectTechFilesConfirm = (val: any) => {
  fileList.value = val
  form.value.techFilesName = val.map((item: { fileName: string; fileCode: string }) => item.fileCode + item.fileName).join(',')
}

// ---------------------------------文件上传（上传证书）-------------------------------------------
const fileRef = ref()
const onFileChange = (event: any) => {
  // 原生上传
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('multipartFile', event.target.files[0])
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    UploadFile(fd).then((res) => {
      if (res.code === 200) {
        form.value.certificateReportFile = res.data[0]
        loading.close()
        ElMessageBox.confirm(
          '文件上传成功，是否保存上传的文件?',
          '提示',
          {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
          },
        )
          .then(() => {
            handleSave('saveUploadFile')
          })
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}

// ----------------------------------------------样品--------------------------------------------
const selectOrderSamplesDialogRef = ref() // 选择委托书下的样品清单组件ref
const selectMyMeasureDialogRef = ref() // 选择我的检测下的样品ref
const selectSamplesDialogRef = ref() // 选择样品库中的样品组件ref
const sampleList = ref<ISampleList[]>([])// 表格数据
const checkoutSampleList = ref<ISampleList[]>([])// 多选样品列表
// 表头
const sampleColumns = ref<TableColumn[]>([
  { text: '样品编号', value: 'sampleNo', align: 'center', width: '160' },
  { text: '样品名称', value: 'sampleName', align: 'center' },
  { text: '型号', value: 'sampleModel', align: 'center' },
  { text: '出厂编号', value: 'manufacturingNo', align: 'center' },
  { text: '生产厂家', value: 'manufacturer', align: 'center' },
  { text: '备注', value: 'remark', align: 'center' },
])

// 选中行
const handleSelectionSampleChange = (e: any) => {
  checkoutSampleList.value = e
}

// 点击批量添加/选择
const addSample = () => {
  // if (form.value.orderCode) { // 选择委托单下的样品
  // selectOrderSamplesDialogRef.value.initDialog(form.value.orderId, false)
  selectMyMeasureDialogRef.value.initDialog('', false, form.value.invalid)
  // selectMyMeasureDialogRef.value.initDialog(form.value.orderCode, false)
  // }
  // else { // 选择样品库中的样品
  //   selectSamplesDialogRef.value.initDialog()
  // }
}

// 选好样品
const confirmSelectSample = (val: any, type: 'warehouse' | 'order') => {
  // if (type === 'order') { // 先选委托方，再选样品(样品室委托方下面的样品)
  //   sampleList.value = [{ ...val[0], id: val[0].sampleId, remark: val[0].sampleRemark }]
  // }
  // else { // 没选委托方，直接选择样品库中的样品
  //   sampleList.value = [{ ...val[0] }]
  //   if (val[0].orderId) { // 如果有委托单
  //     // 请求委托单详情
  //     getOrderDetail({ id: val[0].orderId }).then((res) => {
  //       form.value.orderId = val[0].orderId // 委托单id
  //       form.value.orderCode = res.data.orderCode // 委托单
  //       form.value.customerId = res.data.customerId// 委托方id
  //       form.value.customerName = res.data.customerName// 委托方名称
  //       form.value.customerAddress = res.data.customerAddress// 委托方地址
  //       form.value.certificationCompany = res.data.certificationCompany// 证书单位名称
  //       form.value.certificationCompanyAddress = res.data.certificationCompanyAddress// 证书单位地址
  //       form.value.certificationCompanyAddress = res.data.certificationCompanyAddress// 证书单位地址
  //       form.value.busPersonId = res.data.busPersonId// 业务员id
  //       form.value.busPersonName = res.data.busPersonName// 业务员名字
  //     })
  //   }
  //   else { // 没有委托单
  //     // 没有委托单去请求委托方的信息把委托方填上
  //     if (val[0].customerNo) {
  //       const params = {
  //         businessSize: '', // 业务规模
  //         customerName: '', // 公司名称
  //         customerNo: val[0].customerNo, // 客户编号
  //         grade: '', // 履约评级
  //         offset: 1,
  //         limit: 20,
  //       }
  //       getCustomerList(params).then((res) => {
  //         if (res && res.data && res.data.rows && res.data.rows.length) {
  //           form.value.customerId = res.data.rows[0].id// 委托方id
  //           form.value.customerName = res.data.rows[0].customerName// 委托方名称
  //           // 处理委托方地址
  //           if (res.data.rows[0].addressProvinceName && res.data.rows[0].addressCityName && (res.data.rows[0].addressProvinceName === res.data.rows[0].addressCityName)) {
  //             form.value.customerAddress = res.data.rows[0].addressCountryName + res.data.rows[0].addressProvinceName + res.data.rows[0].addressAreaName + res.data.rows[0].fullAddress
  //           }
  //           else {
  //             if (res.data.rows[0].addressAreaName) {
  //               form.value.customerAddress = res.data.rows[0].addressCountryName + res.data.rows[0].addressProvinceName + res.data.rows[0].addressCityName + res.data.rows[0].addressAreaName + res.data.rows[0].fullAddress
  //             }
  //             else {
  //               form.value.customerAddress = res.data.rows[0].addressCountryName + res.data.rows[0].addressProvinceName + res.data.rows[0].addressCityName + res.data.rows[0].fullAddress
  //             }
  //           }
  //         }
  //       })
  //     }
  //   }
  // }
  sampleList.value = [{ ...val[0], id: val[0].sampleId, remark: val[0].sampleRemark }]
  getOrderDetail({ id: val[0].orderId }).then((res) => {
    form.value.orderId = val[0].orderId // 委托单id
    form.value.orderCode = res.data.orderCode // 委托单
    form.value.customerId = res.data.customerId// 委托方id
    form.value.customerName = res.data.customerName// 委托方名称
    form.value.customerAddress = res.data.customerAddress// 委托方地址
    form.value.certificationCompany = res.data.certificationCompany// 证书单位名称
    form.value.certificationCompanyAddress = res.data.certificationCompanyAddress// 证书单位地址
    form.value.certificationCompanyAddress = res.data.certificationCompanyAddress// 证书单位地址
    form.value.busPersonId = res.data.busPersonId// 业务员id
    form.value.busPersonName = res.data.busPersonName// 业务员名字
    form.value.deliverTime = res.data.planDeliverTime ? dayjs(res.data.planDeliverTime).format('YYYY-MM-DD') : res.data.planDeliverTime// 接收时间
  })
}

// 删除样品
const delSample = () => {
  if (!checkoutSampleList.value.length) {
    ElMessage.warning('请选中要删除的样品')
    return false
  }
  checkoutSampleList.value.forEach((item: ISampleList) => {
    sampleList.value.forEach((element, index) => {
      if (element.sampleNo === item.sampleNo) {
        sampleList.value.splice(index, 1)
      }
    })
  })
}

// 修改样品
const clickUpdateSample = () => {
  sampleList.value = sampleList.value.map((item) => {
    return {
      ...item,
      editable: true, // 表格是否可修改
    }
  })
}
// ----------------------------------------------所用的计量标准器具--------------------------------------------
const equipmentVisible = ref(false) // 选择设备对话框显隐
const equipmentInfoList = ref<IEquipmentList[]>([])// 表格数据
const checkoutEquipmentList = ref<IEquipmentList[]>([])// 多选设备
// 表头
const equipmentColumns = ref<TableColumn[]>([
  { text: '设备编号', value: 'equipmentNo', align: 'center', width: '160' },
  { text: '设备名称', value: 'equipmentName', align: 'center' },
  { text: '型号', value: 'modelNo', align: 'center' },
  { text: '出厂编号', value: 'manufacturingNo', align: 'center' },
  { text: '测量范围', value: 'mesureRange', align: 'center' },
  { text: '不确定度', value: 'uncertainty', align: 'center' },
  { text: '溯源机构', value: 'mesureDeptName', align: 'center' },
  { text: '证书编号', value: 'certificateNo', align: 'center' },
  { text: '有效日期', value: 'validDate', align: 'center' },
])

// 选中行
const handleSelectionEquipmentChange = (e: any) => {
  checkoutEquipmentList.value = e
}

// 修改测量设备对话框显隐
const changeEquipmentVisible = (val: boolean) => {
  equipmentVisible.value = val
}
// 点击批量添加/选择
const addEquipment = () => {
  equipmentVisible.value = true
}

// 选中设备
const confirmSelectEquipment = (val: any) => {
  val.forEach((item: IEquipmentList) => {
    // 只添加列表里不存在的
    const index = equipmentInfoList.value.findIndex((i: IEquipmentList) => item.id === i.id)
    if (index === -1) {
      equipmentInfoList.value.push(item)
    }
  })
}

// 删除计量标准器具
const delEquipment = () => {
  if (!checkoutEquipmentList.value.length) {
    ElMessage.warning('请选中要删除的计量标准器具')
    return false
  }
  checkoutEquipmentList.value.forEach((item: IEquipmentList) => {
    equipmentInfoList.value.forEach((element, index) => {
      if (element.equipmentNo === item.equipmentNo) {
        equipmentInfoList.value.splice(index, 1)
      }
    })
  })
}
// ------------------------------------委托单(暂时弃用、委托单目前不让选择)------------------------------------------
// 点击选择委托单编号
const handleClickOrder = () => {
  orderVisible.value = true
}
// 修改委托单对话框显隐
const changeOrderVisible = (val: boolean) => {
  orderVisible.value = val
}
// 选好委托单
const confirmCheckoutOrder = (val: any) => {
  if (val && val.length) {
    sampleList.value = []
    form.value.orderId = val[0].id // 委托单id
    form.value.orderCode = val[0].orderCode // 委托单
    form.value.customerId = val[0].customerId// 委托方id
    form.value.customerName = val[0].customerName// 委托方名称
    form.value.customerAddress = val[0].customerAddress// 委托方地址
    form.value.certificationCompany = val[0].certificationCompany// 证书单位名称
    form.value.certificationCompanyAddress = val[0].certificationCompanyAddress// 证书单位地址
    form.value.certificationCompanyAddress = val[0].certificationCompanyAddress// 证书单位地址
    form.value.busPersonId = val[0].busPersonId// 业务员id
    form.value.busPersonName = val[0].busPersonName// 业务员名字
  }
}
// --------------------------------------证书模板------------------------------------------
// 选择证书模板Ref
const templateDialogRef = ref()
// 选择证书模板
const handleClickTemplate = () => {
  templateDialogRef.value.initDialog()
}
// 选择证书模板确认
const confirmCheckoutTemplate = (val: any) => {
  form.value.templateId = val.id // 证书报告模板id
  form.value.templateName = val.templateName || '' // 证书报告模板名称
}

// 点击下载证书附件
const downloadCertFile = () => {
  if (form.value.certificateReportFile) {
    getPhotoUrl(form.value.certificateReportFile).then((res) => {
      download(res.data, form.value.certificateReportFile)
    }).catch(() => {
      ElMessage.error('下载失败')
    })
  }
  else {
    ElMessage.warning('无可下载内容')
  }
}

// 点击下载证书模板按钮
const downloadCertTemplate = () => {
  if (!form.value.templateId) {
    ElMessage.warning('请先选择证书模板')
    return false
  }
  if (!sampleList.value.length) {
    ElMessage.warning('被检样品不能为空')
    return false
  }
  if (!equipmentInfoList.value.length) {
    ElMessage.warning('所用的计量标准器具不能为空')
    return false
  }

  ruleFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const params = solveParams()
      const loading = ElLoading.service({
        lock: true,
        background: 'rgba(255, 255, 255, 0.8)',
      })
      downLoadTemplate(params).then((res) => {
        const contentDisposition = res.headers.get('Content-Disposition')
        const match = contentDisposition.match(/\.([^.]+)$/)
        const fileType = `.${match[1]}`
        exportFile(res.data, `${form.value.certificateReportName}${form.value.templateName}${fileType}`)
        loading.close()
      }).catch(() => {
        loading.close()
      })
    }
  })
}

// -------------------------------------------------------------------------------------------
// 处理保存、下载模板参数
function solveParams() {
  const params = {
    ...form.value,
    repeatTime: `${form.value.repeatTime}` === 'undefined' || `${form.value.repeatTime}` === 'null' ? '' : `${form.value.repeatTime}`,
    businessEnvironmentRecord: businessEnvironmentRecord.value, // 环境记录单
    fileList: fileList.value === '' ? [] : fileList.value, // 依据的技术文件
    equipmentInfoList: equipmentInfoList.value, // 所用的计量标准器具列表/监测设备
    sampleId: sampleList.value[0].id, //	样品id(打印证书接口要必传)
    sampleNo: sampleList.value[0].sampleNo, //	样品编号
    sampleName: sampleList.value[0].sampleName, //	样品名称
    sampleModel: sampleList.value[0].sampleModel, //	样品型号
    manufacturingNo: sampleList.value[0].manufacturingNo, //	出厂编号
    manufacturer: sampleList.value[0].manufacturer, //	生产厂家
    sampleRemark: sampleList.value[0].remark, //	样品备注
    id: infoId.value,
  }
  return params
}

// 获取详情信息
async function getDetail(id?: string, certificateReportCode?: string) {
  const loading = ElLoading.service({
    lock: true,
    background: 'rgba(255, 255, 255, 0.8)',
  })
  const res = await getMeasureDataDetail({ id: infoId.value! || id! })
  loading.close()
  form.value = res.data
  form.value.repeatTime = Number(form.value.repeatTime)
  form.value.processId = ''
  fileList.value = res.data.fileList // 依据的技术文件
  if (Array.isArray(res.data.fileList)) {
    form.value.techFilesName = fileList.value.map((item: { fileName: string; fileCode: string }) => item.fileCode + item.fileName).join(',')
  }
  sampleList.value = [{
    sampleNo: res.data.sampleNo, // 样品编号
    sampleName: res.data.sampleName, // 样品名称
    sampleModel: res.data.sampleModel, // 型号
    manufacturingNo: res.data.manufacturingNo, // 出厂编号
    manufacturer: res.data.manufacturer, // 生产厂家
    remark: res.data.sampleRemark, // 备注
    id: res.data.sampleId,
  }]
  equipmentInfoList.value = res.data.equipmentInfoList.map((item: { validDate: string }) => {
    return {
      ...item,
      validDate: item.validDate ? dayjs(item.validDate).format('YYYY-MM-DD') : item.validDate,
    }
  }) // 所用的计量标准器具

  businessEnvironmentRecord.value = res.data.businessEnvironmentRecord // 环境记录单数据
  form.value.environmentCode = res.data.businessEnvironmentRecord.environmentCode// 环境记录单编号
  if (id && certificateReportCode) {
    form.value.oldCertificateCode = certificateReportCode
    form.value.invalid = 1
    form.value.measurePerson = user.name // 检定员名字
  }
}

// 关闭新增页面的回调
const close = () => {
  $router.back()
}

// 样品编辑
const handleUpdateSample = () => {
  const allRequest = [] as any // 所有的请求
  sampleList.value.forEach((item) => {
    const params = {
      id: item.id,
      sampleNo: item.sampleNo, // 样品编号
      sampleName: item.sampleName, // 样品名称
      sampleModel: item.sampleModel, // 样品型号
      manufacturingNo: item.manufacturingNo, // 出厂编号
      remark: item.remark, // 备注
    }
    const request = updateSample(params)
    allRequest.push(request)
  })
  Promise.all(allRequest)
}

// 保存
function handleSave(type = '') {
  if (!sampleList.value.length) {
    ElMessage.warning('被检样品不能为空')
    return false
  }
  if (!equipmentInfoList.value.length) {
    ElMessage.warning('所用的计量标准器具不能为空')
    return false
  }
  ruleFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const loading = ElLoading.service({
        lock: true,
        background: 'rgba(255, 255, 255, 0.8)',
      })
      const params = solveParams()
      if (pageType.value === 'add' && !infoId.value) { // 新建
        addMeasureData({ ...params, processId: '' }).then((res) => {
          submitId.value = res.data.data.id
          infoId.value = res.data.data.id
          form.value.certificateReportCode = res.data.data.certificateReportCode
          form.value.certificateReportName = res.data.data.certificateReportName
          handleUpdateSample()
          ElMessage.success('保存成功')
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }

      else if (pageType.value === 'edit' || (pageType.value === 'add' && infoId.value)) { // 编辑
        // if (query.approvalStatusName === '未通过-驳回') { // 未通过-驳回
        //   const param = {
        //     ...params,
        //     processId: form.value.processId,
        //     // assignees: approverList,
        //   }
        //   failUpdateMeasureData(params).then((res) => {
        //     handleUpdateSample()
        //     ElMessage.success('保存成功')
        //     // showSaveBtn.value = false
        //     pageType.value = 'detail'
        //     loading.close()
        //   }).catch(() => {
        //     loading.close()
        //   })
        // }
        // else { // 草稿箱和已取消
        draftUpdateMeasureData(params).then((res) => {
          handleUpdateSample()
          submitId.value = res.data
          ElMessage.success('保存成功')
          loading.close()
        }).catch(() => {
          loading.close()
        })
        // }
      }
    }
  })
}
// -----------------------------------提交-------------------------------------------------------
const selectApproverRef = ref() // 审批人自选组件ref
// 选好审批人
const confirmSelectApprover = async (approverList: string[] = []) => {
  if (!approverList.length) {
    ElMessage.warning('无审批人，无法提交！')
    return false
  }
  console.log('审批人', approverList)
  console.log('processId', form.value.processId)

  // if (form.value === null || form.value.processId === undefined || form.value.processId === '') {
  // 流程id为空 表示还未进入流程中 直接提交

  ElMessageBox.confirm(`是否提交计量数据管理 ${form.value.certificateReportCode}-${form.value.certificateReportName}`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    if (submitId.value) {
      const loading = ElLoading.service({
        lock: true,
        background: 'rgba(255, 255, 255, 0.8)',
      })
      const params = {
        id: submitId.value,
        formId: SCHEDULE.BUSINESS_REPORT_ON_CREDENTIALS, // 表单id
        assignees: approverList,
        processId: form.value.processId,
      }
      submit(params).then(() => {
        ElMessage.success('提交成功')
        loading.close()
        close()
      }).catch(() => {
        loading.close()
      })
    }
    else {
      ElMessage.warning('请先保存！')
    }
  })
  // }
}
// 提交按钮
const handleSubmit = () => {
  selectApproverRef.value.initDialog()
}

// ------------------------------------------审批-----------------------------------------

const approvalRecordData = ref([]) // 审批流程数据
// 查询审批记录
function getApprovalRecord(processId: string) {
  if (pageType.value !== 'add') {
    if (processId) {
      fetchApproval(processId).then((res) => {
        approvalRecordData.value = res.data
      })
    }
    else {
      ElMessage.warning('流程实例id为空')
    }
  }
}
// 审批结束回调
const approvalSuccess = () => {
  close() // 返回上一页
}
// 审批
const handleApprove = (val: string, title = '') => {
  if (val === '取消') {
    const params = {
      processInstanceId: form.value.processId!,
      comments: '',
    }
    ElMessageBox.confirm(
      '确认取消该审批吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(() => {
        cancelApproval(params).then((res) => {
          ElMessage({
            type: 'success',
            message: '取消成功',
          })
          close()
        })
      })
  }

  else if (val === '同意') {
    approvalDialog.value.initDialog('agree', query.taskId, infoId.value, query.decisionItem, form.value.processId, query.sampleId, query.orderId, form.value.invalid, query.measurePersonId)
  }
  else if (val === '驳回') {
    approvalDialog.value.initDialog('reject', query.taskId, infoId.value, query.decisionItem)
  }
  else if (val === '拒绝') {
    approvalDialog.value.initDialog('refuse', query.taskId, infoId.value, query.decisionItem)
  }
}
// ------------------------------------事件-------------------------------------------------
// 检校专业变化
const changeCalibrationMajor = (val: string) => {
  const index = calibrationMajorMap.value.findIndex((item: { value: string }) => item.value === val)
  if (index !== -1) {
    form.value.calibrationMajorName = calibrationMajorMap.value[index].name
  }
  console.log(form.value.calibrationMajorName)
}
// 证书类别变化
const changeCertifications = (val: string) => {
  const index = certificationTypeMap.value.findIndex((item: { value: string }) => item.value === val)
  if (index !== -1) {
    form.value.certificateReportCategoryName = certificationTypeMap.value[index].name
  }
  console.log(form.value.certificateReportCategoryName, val)

  if (val === '3' || val === '1') { // 如果是校准报告\检测报告，电子签章自动选择校准专用章、检测专用章
    const params = {
      signNo: '', // 编号
      signName: '', // 名称
      signDirector: '', // 负责人
      createEndTime: '',
      createStartTime: '',
      ids: [],
      limit: 999999,
      offset: 1,
      signType: signTypeMap.value.filter((item: { name: string }) => item.name === '签章')[0].value,
      signCategory: '1', // 筛选证书用章
    } // 查询参数
    listPageApi(params).then((res) => {
      if (res.code === 200) {
        const resultList = res.data.rows
        let index = -1
        if (val === '3') {
          index = resultList.findIndex((item: { signName: string }) => item.signName === '校准专用章')
        }
        if (val === '1') {
          index = resultList.findIndex((item: { signName: string }) => item.signName === '检测专用章')
        }
        if (index !== -1) {
          form.value.signId = resultList[index].id // 电子签章id
          form.value.signName = resultList[index].signName // 电子签章名称
        }
        else {
          console.log('未获取到校准专用章、检测专用章')
        }
      }
    })
  }
}
// -------------------------------------------------------------------------------------
onMounted(async () => {
  await getDict()
  form.value.processId = query.processId as string // 流程实例
  if (pageType.value !== 'add') { // 编辑、详情
    getDetail().then(() => {
      nextTick(() => {
        form.value.processId = query.processId as string // 流程实例
      })
    })
    if (query.approvalStatusName !== '草稿箱') {
      getApprovalRecord(form.value.processId) // 获取审批流程
    }
  }
  else { // 新建
    // form.value.createUser = user.id // 创建人id
    // form.value.createUserName = user.name // 创建人
    // form.value.applicantTime = proxy.dayjs().format('YYYY-MM-DD HH:mm:ss') // 申请时间
    form.value.measurePerson = user.name // 检定员名字
    form.value.calibrationTime = proxy.dayjs().format('YYYY-MM-DD') // 检校日期
  }
})

// ------------------------------------excel在线编辑--------------------------------------
const excelEditRef = ref()
// 点击ExcelEdit在线编辑按钮，打开ExcelEdit在线编辑工具
const handleClickExcelEdit = () => {
  excelEditRef.value.initDialog()
}
// excel初始化完成
const ExcelEditInitComplete = async (spread: any) => {
  const params = solveParams()
  const loading = ElLoading.service({
    lock: true,
    text: '模板自动导入中，请稍后！',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  console.log('---------------------------------')
  console.log(params)

  // downLoadTemplate(params).then((res) => {
  //   if (res.data) {
  //     loading.close()
  //     excelEditRef.value.handleImportFile(res.data, form)
  //   }
  //   else {
  //     console.log('未获取到模板文件')
  //   }
  // }).catch(() => {
  // loading.close()
  // })
  const res = await getPhotoUrl(form.value.certificateReportFile)
  const certUrl = await fetch(res.data)
  const file = await certUrl.blob()
  excelEditRef.value.handleImportFile(file, form.value)
  loading.close()
  // importFile(spread, file)
}
</script>

<template>
  <app-container class="business-lab-measure-data-edit">
    <detail-page :title="`计量数据管理-${textMap[pageType]}`">
      <template #btns>
        <el-button v-if="proxy.hasPerm(`/lab/excelEditBtn`)" type="warning" @click="handleClickExcelEdit">
          excel在线编辑
        </el-button>
        <el-button v-if="pageType !== 'detail'" type="primary" :disabled="pageType === 'detail'" @click="upload">
          上传证书
        </el-button>
        <el-button v-if="(submitId !== '' && pageType === 'add') || pageType === 'edit'" type="primary" @click="downloadCertTemplate">
          下载证书模板
        </el-button>
        <el-button v-if="pageType === 'detail'" type="primary" @click="downloadCertFile">
          下载证书附件
        </el-button>
        <el-button v-if="pageType === 'detail' && query.approvalStatusName === '待审批'" type="primary" @click="handleApprove('同意')">
          同意
        </el-button>
        <el-button v-if="pageType === 'detail' && query.approvalStatusName === '待审批' && query.decisionItem !== '3'" type="primary" @click="handleApprove('驳回')">
          驳回
        </el-button>
        <el-button v-if="pageType === 'detail' && query.approvalStatusName === '待审批' && query.decisionItem !== '2'" type="danger" @click="handleApprove('拒绝')">
          拒绝
        </el-button>
        <el-button v-if="pageType === 'add' || query.approvalStatusName === '未通过-驳回'" type="primary" @click="handleSubmit">
          提交
        </el-button>
        <el-button v-if="pageType !== 'detail' && showSaveBtn" type="primary" @click="handleSave('')">
          保存
        </el-button>
        <!-- <el-button v-if="pageType === 'detail'" type="primary">
          打印
        </el-button> -->
        <el-button v-if="pageType === 'detail' && query.approvalStatusName === '审批中'" type="info" @click="handleApprove('取消')">
          取消
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <el-form
        ref="ruleFormRef"
        :model="form"
        label-position="right"
        label-width="140"
        :rules="formRules"
      >
        <el-row v-if="pageType === 'add'" :gutter="24">
          <el-col :span="6">
            <el-form-item label="">
              <el-checkbox v-model="form.invalid" :true-label="1" :false-label="0">
                替代已生成证书
              </el-checkbox>
            </el-form-item>
          </el-col>
          <el-col v-if="form.invalid" :span="12">
            <el-form-item label="原证书:" prop="oldCertificateCode">
              <el-input
                v-model="form.oldCertificateCode"
                disabled
                placeholder="请选择原证书"
              >
                <template #append>
                  <el-button
                    size="small"
                    @click="selectOrigin"
                  >
                    选择
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="检校专业:" prop="calibrationMajor">
              <el-select
                v-model="form.calibrationMajor"
                clearable
                :placeholder="pageType === 'detail' ? '' : '请选择检校专业'"
                size="default"
                style="width: 100%;"
                :disabled="pageType === 'detail'"
                @change="changeCalibrationMajor"
              >
                <el-option
                  v-for="item in calibrationMajorMap"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="证书类别:" prop="certificateReportCategory">
              <el-select
                v-model="form.certificateReportCategory"
                clearable
                size="default"
                :placeholder="pageType === 'detail' ? '' : '请选择证书类别'"
                style="width: 100%;"
                :disabled="pageType === 'detail'"
                @change="changeCertifications"
              >
                <el-option
                  v-for="item in certificationTypeMap"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="证书编号:">
              <el-input
                v-model.trim="form.certificateReportCode"
                placeholder="系统自动生成"
                class="full-width-input"
                clearable
                disabled
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="证书名称:" prop="certificateReportName">
              <el-input
                v-model.trim="form.certificateReportName"
                :placeholder="pageType === 'detail' ? '' : '请输入证书名称'"
                class="full-width-input"
                clearable
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="证书名称:">
              <el-input
                v-model.trim="form.certificateReportName"
                placeholder="系统自动生成"
                class="full-width-input"
                clearable
                :disabled="pageType !== 'edit'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="委托单:">
              <el-input
                v-model.trim="form.orderCode"
                :placeholder="pageType === 'detail' ? '' : '请选择委托单'"
                class="full-width-input"
                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.trim="form.customerName"
                :placeholder="pageType === 'detail' ? ' ' : '委托方名称'"
                class="full-width-input"
                clearable
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="委托方地址:" prop="customerAddress">
              <el-input
                v-model.trim="form.customerAddress"
                type="textarea"
                autosize
                :class="{ 'detail-input': pageType === 'detail' }"
                :placeholder="pageType === 'detail' ? '' : '请输入委托方地址'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证书单位名称:" prop="certificationCompany">
              <el-input
                v-model.trim="form.certificationCompany"
                :placeholder="pageType === 'detail' ? ' ' : '请输入证书单位名称'"
                class="full-width-input"
                clearable
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证书单位地址:" prop="certificationCompanyAddress">
              <el-input
                v-model="form.certificationCompanyAddress"
                type="textarea"
                autosize
                :class="{ 'detail-input': pageType === 'detail' }"
                :placeholder="pageType === 'detail' ? '' : '请输入证书单位地址'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检校地点:" prop="calibrationPlace">
              <el-input
                v-model.trim="form.calibrationPlace"
                class="full-width-input"
                clearable
                :placeholder="pageType === 'detail' ? '' : '请输入检校地点'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检定员:" prop="measurePerson">
              <el-input
                v-model.trim="form.measurePerson"
                class="full-width-input"
                clearable
                :placeholder="pageType === 'detail' ? '' : '检定员'"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检校日期:" prop="calibrationTime">
              <el-date-picker
                v-model="form.calibrationTime"
                type="date"
                placeholder="请选择检校日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="form.certificateReportCategory === '3'" :span="6">
            <el-form-item label="复校时间(月):" prop="repeatTime">
              <el-input-number
                v-model="form.repeatTime"
                :placeholder="pageType === 'detail' ? '' : '请输入复校时间'"
                :class="{ 'detail-input': pageType === 'detail' }"
                :disabled="pageType === 'detail'"
                :min="1"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="form.certificateReportCategory === '1'" :span="6">
            <el-form-item label="接收时间:" prop="deliverTime">
              <el-date-picker
                v-model="form.deliverTime"
                type="datetime"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :placeholder="pageType === 'detail' ? '' : '请选择接收时间'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="form.certificateReportCategory === '2'" :span="6">
            <el-form-item label="检定结果:" prop="measureResult">
              <el-input
                v-model.trim="form.measureResult"
                class="full-width-input"
                :placeholder="pageType === 'detail' ? '' : '请输入检定结果'"
                :disabled="pageType === 'detail'"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="环境记录单:" prop="environmentCode">
              <el-input
                v-model.trim="form.environmentCode"
                :placeholder="pageType === 'detail' ? '' : '请选择环境记录单'"
                class="full-width-input"
                disabled
              >
                <template v-if="pageType !== 'detail'" #append>
                  <el-button
                    size="small"
                    @click="environmentalClick"
                  >
                    选择
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="温度(℃):" prop="temperature">
              <el-input
                v-model.trim="form.temperature"
                :placeholder="pageType === 'detail' ? '' : '请输入温度(℃)'"
                class="full-width-input"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="相对湿度(%RH):" prop="humidity">
              <el-input
                v-model.trim="form.humidity"
                :placeholder="pageType === 'detail' ? '' : '请输入相对湿度(%RH)'"
                class="full-width-input"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所依据的技术文件:" prop="techFilesName">
              <el-input
                v-model.trim="form.techFilesName"
                :placeholder="pageType === 'detail' ? '' : '请选择所依据的技术文件'"
                class="full-width-input"
                disabled
              >
                <template v-if="pageType !== 'detail'" #append>
                  <el-button size="small" @click="selectTechFiles">
                    选择
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="电子签章:" prop="signName">
              <el-input
                v-model.trim="form.signName"
                :placeholder="pageType === 'detail' ? '' : '请选择电子签章'"
                class="full-width-input"
                disabled
              >
                <template v-if="pageType !== 'detail'" #append>
                  <el-button size="small" @click="handleClickSignature">
                    选择
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="认可标志专用章:" prop="approvalSignName">
              <el-input
                v-model.trim="form.approvalSignName"
                :placeholder="pageType === 'detail' ? '' : '请选择认可标志专用章'"
                class="full-width-input"
                disabled
              >
                <template v-if="pageType !== 'detail'" #append>
                  <el-button size="small" @click="handleClickSpecialSignature">
                    选择
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item label="备注:">
              <el-input
                v-model.trim="form.remark"
                :placeholder="pageType === 'detail' ? '' : '请输入备注'"
                class="full-width-input"
                clearable
                type="textarea"
                autosize
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务员:">
              <el-input
                v-model.trim="form.busPersonName"
                class="full-width-input"
                clearable
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="证书模板:" prop="templateName">
              <el-input
                v-model.trim="form.templateName"
                :placeholder="pageType === 'detail' ? '' : '请选择证书模板'"
                class="full-width-input"
                disabled
              >
                <template v-if="pageType !== 'detail'" #append>
                  <el-button size="small" @click="handleClickTemplate">
                    选择
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证书附件:" prop="certificateReportFile">
              <input v-show="pageType === ''" ref="fileRef" multiple type="file" @change="onFileChange">
              <span v-if="!form.certificateReportFile">无</span>
              <div v-else style="display: flex;">
                <show-photo :minio-file-name="form.certificateReportFile || ''" style="display: inline-block;" />
              </div>
              <!-- <el-button v-if="pageType !== 'detail'" type="primary" :disabled="pageType === 'detail'" @click="upload">
                {{ form.certificateReportFile ? '更换' : '上传' }}
              </el-button> -->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
    <detail-block title="被检样品">
      <template v-if="pageType !== 'detail'" #btns>
        <el-button type="primary" @click="addSample">
          选择
        </el-button>
        <el-button type="primary" @click="clickUpdateSample">
          修改
        </el-button>
        <el-button type="info" @click="delSample">
          删除行
        </el-button>
      </template>
      <el-table
        :data="sampleList"
        border
        style="width: 100%;"
        max-height="600"
        @selection-change="handleSelectionSampleChange"
      >
        <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 sampleColumns"
          :key="item.value"
          :prop="item.value"
          :label="item.text"
          :width="item.width"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-input
              v-if="pageType !== 'detail' && scope.row.editable && item.value !== 'sampleNo'"
              v-model="scope.row[item.value]"
              :placeholder="item.text"
              type="textarea"
              autosize
            />
          </template>
        </el-table-column>
      </el-table>
    </detail-block>
    <detail-block title="所用的计量标准器具">
      <template v-if="pageType !== 'detail'" #btns>
        <el-button type="primary" @click="addEquipment">
          选择
        </el-button>
        <el-button type="info" @click="delEquipment">
          删除行
        </el-button>
      </template>
      <el-table
        :data="equipmentInfoList"
        border
        style="width: 100%;"
        max-height="600"
        @selection-change="handleSelectionEquipmentChange"
      >
        <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 equipmentColumns"
          :key="item.value"
          :prop="item.value"
          :label="item.text"
          :width="item.width"
          show-overflow-tooltip
          align="center"
        />
      </el-table>
    </detail-block>

    <detail-block v-if="query.approvalStatusName !== '草稿箱' && pageType !== 'add'" title="审批流程">
      <!-- 审批流程 -->
      <approval-record ref="approvalRecord" :approval-record-data="approvalRecordData" />
    </detail-block>
    <!-- 样品增加弹窗 -->
    <!-- <select-sample v-model:visible="sampleVisible" :is-use-customer-no="false" :is-multi="isMulti" @click-confirm-sample="clickConfirmSample" @change-visible="changeSampleVisible" /> -->
    <!-- 审批弹窗 -->
    <approval-dialog ref="approvalDialog" module="meadureData" :last-name="customApproval.approvalLastName.measureData" @on-success="approvalSuccess" />
    <!-- 选择审批人弹窗 -->
    <select-approver-dialog ref="selectApproverRef" @confirm="confirmSelectApprover" />
    <!-- 选择委托单组件 -->
    <select-order v-model:visible="orderVisible" @confirm-checkout="confirmCheckoutOrder" @change-visible="changeOrderVisible" />
    <!-- 选择环境记录单弹窗 -->
    <environmental-dialog ref="environmentalDialog" @add="environmentalAdd" />
    <!-- 选择签章 -->
    <select-signature ref="signatureDialog" @add="confirmCheckoutSignature" />
    <!-- 选择认可标志专用签章 -->
    <select-signature ref="specialSignatureDialog" :is-multi="true" @add="confirmCheckoutSpecialSignature" />
    <!-- 选择证书模板 -->
    <select-report-template ref="templateDialogRef" @confirm="confirmCheckoutTemplate" />
    <!-- 选择委托书下的样品清单 -->
    <select-order-samples-dialog ref="selectOrderSamplesDialogRef" @confirm="(val: any) => confirmSelectSample(val, 'order')" />
    <!-- 选择我的检测的样品 -->
    <select-my-measure-dialog ref="selectMyMeasureDialogRef" @confirm="(val: any) => confirmSelectSample(val, 'order')" />
    <!-- 选择样品库下的样品 -->
    <select-samples-dialog ref="selectSamplesDialogRef" @confirm="(val: any) => confirmSelectSample(val, 'warehouse')" />
    <!-- 选择测量设备 -->
    <select-measure-device v-model:visible="equipmentVisible" :is-multi="true" @confirm-checkout="confirmSelectEquipment" @change-visible="changeEquipmentVisible" />
    <!-- 选择原证书  -->
    <select-measue-data-dialog ref="selectMeasueDataDialogRef" @confirm="selectMeasueDataConfirm" />
    <!-- 选择依据的技术文件  -->
    <select-tech-files-dialog ref="selectTechFilesRef" @confirm="selectTechFilesConfirm" />
    <excel-edit ref="excelEditRef" @init-complete="ExcelEditInitComplete" />
  </app-container>
</template>

<style lang="scss">
.business-lab-measure-data-edit {
  .el-radio__label {
    display: block !important;
  }
}
</style>
