<!-- 标准装置台账信息 基本信息 -->
<script name="StandardBookBasic" lang="ts" setup>
import type { Ref } from 'vue'
import dayjs from 'dayjs'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { FormRules } from 'element-plus'
import type { IAccessory, IForm, IInspect, Itech } from '../book-interface'
import selectUnpackRecordDialog from '../dialog/selectUnpackRecordDialog.vue'
import { useCheckList } from '@/commonMethods/useCheckList'
import { useDoubleClickTableRow, useSetAllRowReadable } from '@/commonMethods/useSetAllRowReadable'
import { getDictByCode } from '@/api/system/dict'
import selectTechFiles from '@/views/equipement/standard/book/dialog/selectTechFiles.vue'
import countries from '@/components/AddressSelect/country-code.json'
import type { deptType, dictType } from '@/global'
import { UploadFile } from '@/api/file'
import { getDeptTreeList } from '@/api/system/dept'
import showPhoto from '@/components/showPhoto/index.vue'
import { toTreeList } from '@/utils/structure'
import useUserStore from '@/store/modules/user'
import { SCHEDULE } from '@/utils/scheduleDict'
import { getStaffList } from '@/api/resource/register'
import { addEquipment, failUpdateEquipment, getInfo, submit, updateEquipment } from '@/api/equipment/info/book'
const props = defineProps({
  pageType: { // 页面类型 add新建 edit编辑 detail详情
    type: String,
    require: true,
    default: 'detail',
  },
  id: {
    type: String,
    require: true,
  },
  approvalStatusName: { // 审批状态名称
    type: String,
    require: true,
  },
})
const emits = defineEmits(['submitSuccess', 'addSuccess', 'saveSuccess'])
const user = useUserStore() // 用户信息
const countryList = ref(countries) // 国家列表
const infoId = ref('') // id
const getInfoForm: Ref<{ [key: string]: string }> = ref({})
const form: Ref<IForm> = ref({ // 基本信息表单
  approvalType: '', // 审批类型
  createUserId: '', // 创建人id
  createUserName: '', // 创建人名称
  createTime: '', // 创建时间
  equipmentNo: '', // 统一编号
  equipmentName: '', // 设备名称
  unpackRecordId: '', // 开箱记录id
  purchaseDate: '', // 购进日期
  productCountry: '', // 生产国家
  manufacturer: '', // 生产厂家
  manufactureNo: '', // 出厂编号
  produceDate: '', // 生产日期
  unitPrice: 0, // 设备单价（万元）
  usedYears: '', // 使用年限
  model: '', // 型号规格
  qualityStatus: '', // 质量状况
  usageStatus: '', // 使用状态
  level: '', // 重要等级
  type: '', // 设备类型
  standardType: '', // 标准类型
  deptId: '', // 部门id
  deptName: '', // 所属部门
  directorId: '', // 负责人id
  directorName: '', // 负责人
  category: '', // 设备分类
  measureCycle: 12, // 检定周期
  location: '', // 位置
  remark: '', // 备注
  instructionsFile: '', // 说明书
  fileList: [] as any, // 文件列表
  traceCompany: '', // 溯源单位
  traceDate: '', // 溯源日期
  measureValidDate: '', // 检定有效期
  meterIdentify: '', // 计量标识
  meterStandardName: '', // 所属测量标准
  technicalFile: '', // 所依据的技术文件
})
const rules = reactive<FormRules>({ // 表单验证规则
  equipmentName: [{ required: true, message: '设备名称不能为空', trigger: ['blur', 'change'] }],
  // unpackRecordId: [{ required: true, message: '开箱记录不能为空', trigger: ['blur', 'change'] }],
  purchaseDate: [{ required: true, message: '购进日期不能为空', trigger: ['blur', 'change'] }],
  productCountry: [{ required: true, message: '生产国家不能为空', trigger: ['blur', 'change'] }],
  manufacturer: [{ required: true, message: '生产厂家不能为空', trigger: ['blur', 'change'] }],
  manufactureNo: [{ required: true, message: '出厂编号不能为空', trigger: ['blur', 'change'] }],
  produceDate: [{ required: true, message: '生产日期不能为空', trigger: ['blur', 'change'] }],
  unitPrice: [{ required: true, message: '设备单价不能为空', trigger: ['blur', 'change'] }],
  model: [{ required: true, message: '型号规格不能为空', trigger: ['blur', 'change'] }],
  qualityStatus: [{ required: true, message: '质量状况不能为空', trigger: ['blur', 'change'] }],
  usageStatus: [{ required: true, message: '使用状态不能为空', trigger: ['blur', 'change'] }],
  level: [{ required: true, message: '重要等级不能为空', trigger: ['blur', 'change'] }],
  type: [{ required: true, message: '设备类型不能为空', trigger: ['blur', 'change'] }],
  standardType: [{ required: true, message: '标准类型不能为空', trigger: ['blur', 'change'] }],
  deptId: [{ required: true, message: '所属部门不能为空', trigger: ['blur', 'change'] }],
  directorId: [{ required: true, message: '负责人不能为空', trigger: ['blur', 'change'] }],
  category: [{ required: true, message: '设备分类不能为空', trigger: ['blur', 'change'] }],
  measureCycle: [{ required: true, message: '检定周期不能为空', trigger: ['blur', 'change'] }],
  traceCompany: [{ required: true, message: '溯源单位不能为空', trigger: ['blur', 'change'] }],
  traceDate: [{ required: true, message: '溯源日期不能为空', trigger: ['blur', 'change'] }],
  measureValidDate: [{ required: true, message: '检定有效期不能为空', trigger: ['blur', 'change'] }],
  meterIdentify: [{ required: true, message: '计量标识不能为空', trigger: ['blur', 'change'] }],
})
// -------------------------------------------文件上传--------------------------------------
const fileRef = ref() // 文件上传input
/**
 * 删除附件
 * @param index 索引
 */
const delFile = (index: number) => {
  form.value.fileList.splice(index, 1)
  form.value.instructionsFile = form.value.fileList.map((item: any) => {
    return item.instructionsFile
  })
}

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({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    UploadFile(fd).then((res) => {
      if (res.code === 200) {
        // res.data.forEach((item: string) => {
        //   form.value.fileList.push({
        //     instructionsFile: item,
        //   })
        // })
        // form.value.instructionsFile = form.value.fileList.map((item: any) => {
        //   return item.instructionsFile
        // })
        form.value.instructionsFile = res.data[0]
        console.log(form.value.instructionsFile, 'lll')

        ElMessage.success('文件上传成功')
        loading.close()
      }
      else {
        loading.close()
        ElMessage.error(res.message)
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}

// -----------------------------------------开箱记录-----------------------------------------------------------
const selectUnpackRecordDialogRef = ref() // 开箱记录组件ref
// 点击选择开箱记录
const selectUnpackRecordList = () => {
  ElMessage.info('敬请期待')
  // selectUnpackRecordDialogRef.value.initDialog()
}
// 选择好开箱记录
const confirmSelectUnpackRecord = () => {

}
// 详情时点击开箱记录链接
const handleClickUnpackRecordLink = () => {}

// --------------------------------------打印-------------------------------------------------------------------
// 点击打印计量标识
const printMeterIdentify = () => {
  ElMessage.info('敬请期待')
}
// -----------------------------------------技术指标\主附件信息\核查点-------------------------------------------
const technicalTargetList = ref<Itech[]>([]) // 技术指标列表
const techRef = ref() // 技术指标表格ref
const checkoutTechList = ref([]) as any // 技术指标表格选中
const checkoutAttachmentList = ref([]) as any // 主附件表格选中
const checkoutInspectList = ref([]) as any // 主附件表格选中
const addTechObj: Itech = { // 技术指标对象
  id: '',
  equipmentNo: '', // 设备编号
  measureParam: '', // 检定参数名称
  measureRange: '', // 测量范围
  uncertainty: '', // 不确定度或允许误差极限或准确度等级
  errorCalculateIndicators: '', // 误差计算指标
  editable: true,
}
const technicalIndexColumns = [ // 技术指标表头
  { text: '检定参数名称', value: 'measureParam', required: true },
  { text: '测量范围', value: 'measureRange', required: true },
  { text: '不确定度或允许误差极限或准确度等级', value: 'uncertainty', required: true },
  { text: '误差计算指标', value: 'errorCalculateIndicators', required: true },
]

const accessoryRef = ref() // 主附件信息表格ref
const attachmentList = ref<IAccessory[]>([]) // 主附件信息
const addAccessoryObj: IAccessory = { // 主附件信息对象
  id: '', // 主键
  equipmentNo: '', // 设备编号
  name: '', // 名称
  information: '', // 信息
  location: '', // 位置
  editable: true,
}
const accessoryColumns = [ // 主附件信息
  { text: '名称', value: 'name', required: true },
  { text: '信息', value: 'information', required: true },
  { text: '位置', value: 'location', required: true },
]

const inspectRef = ref() // 核查点表格ref
const checkpointList = ref<IInspect[]>([]) // 核查点
const addInspectObj: IInspect = { // 核查点对象
  id: '', // 主键
  equipmentNo: '', // 设备编号
  item: '', // 核查项目
  checkPoint: '', // 核查点
  unit: '', // 单位
  upperLimit: '', // 上限
  lowerLimit: '', // 下限
  routine: '', // 是否例行
  traceValue: '', // 溯源值
  editable: true,
}
const isRoutineMap = [ // 是否例行字典
  {
    id: '1',
    label: '是',
  },
  {
    id: '0',
    label: '否',
  },
]
const inspectColumns = [ // 核查点表头
  { text: '核查项目', value: 'item', required: true },
  { text: '核查点', value: 'checkPoint', required: true },
  { text: '单位', value: 'unit', required: true },
  { text: '上限', value: 'upperLimit', required: true },
  { text: '下限', value: 'lowerLimit', required: true },
  { text: '是否例行', value: 'routine', required: true },
  { text: '溯源值', value: 'traceValue', required: true },
]
/**
 * 点击增加行
 * @param val 操作的表格类型 tech技术指标、accessory主附件信息、inspect核查点
 */
const addRow = (val: string) => {
  if (val === 'tech') { // 技术指标
    if (useCheckList(technicalTargetList.value, technicalIndexColumns, '技术指标')) {
      useSetAllRowReadable(technicalTargetList.value)
      technicalTargetList.value.push({ ...addTechObj })
    }
  }
  if (val === 'accessory') { // 主附件信息
    if (useCheckList(attachmentList.value, accessoryColumns, '主附件信息')) {
      useSetAllRowReadable(attachmentList.value)
      attachmentList.value.push({ ...addAccessoryObj })
    }
  }
  if (val === 'inspect') { // 核查点
    if (useCheckList(checkpointList.value, inspectColumns, '核查点')) {
      useSetAllRowReadable(checkpointList.value)
      checkpointList.value.push({ ...addInspectObj })
    }
  }
}

/**
 * 点击删除行
 * @param val 操作的表格类型 tech技术指标、accessory主附件信息、inspect核查点
 */
const deleteRow = (val: string) => {
  if ((val === 'tech' && technicalTargetList.value.length <= 0) || (val === 'accessory' && checkoutAttachmentList.value.length <= 0) || (val === 'inspect' && checkoutInspectList.value.length <= 0)) {
    ElMessage({
      message: '请选中要删除的行',
      type: 'warning',
    })
    return false
  }
  if (val === 'tech') { // 技术指标
    technicalTargetList.value = technicalTargetList.value.filter((item: Itech) => {
      return !checkoutTechList.value.includes(item)
    })
  }
  if (val === 'accessory') { // 主附件信息
    attachmentList.value = attachmentList.value.filter((item: IAccessory) => {
      return !checkoutAttachmentList.value.includes(item)
    })
  }
  if (val === 'inspect') { // 核查点
    checkpointList.value = checkpointList.value.filter((item: IInspect) => {
      return !checkoutInspectList.value.includes(item)
    })
  }
}
// 技术指标选中
const handleTechSelectionChange = (e: any) => {
  checkoutTechList.value = e
}
// 主附件信息选中
const handleAccessorySelectionChange = (e: any) => {
  checkoutAttachmentList.value = e
}
// 双击主附件信息
const rowDblclickAccessory = (row: IAccessory) => {
  if (props.pageType !== 'detail') {
    useDoubleClickTableRow(row, attachmentList.value)
  }
}
// 双击核查点
const rowDblclickInspect = (row: IInspect) => {
  if (props.pageType !== 'detail') {
    useDoubleClickTableRow(row, checkpointList.value)
  }
}
// 双击技术指标
const rowDblclickTech = (row: Itech) => {
  if (props.pageType !== 'detail') {
    useDoubleClickTableRow(row, technicalTargetList.value)
  }
}
// 核查点选中
const handleInspectSelectionChange = (e: any) => {
  checkoutInspectList.value = e
}
// 点击所属依据标准
const handleClickMeterStandardLink = () => {
// 跳转标准装置详情页
}

// --------------------------------------------选择依据的技术文件------------------------------------
const techFileRef = ref() // 所依据的技术文件组件ref
// 点击选择依据的技术文件
const selectTechFile = () => {
  techFileRef.value.initDialog()
}

// 点击所依据的技术文件
const handleClickTechFileLink = () => {
// 跳转依据文件详情
}

// 选好技术文件
const confirmSelectTechFile = (val: any) => {
  form.value.technicalFile = val[0].file
}

// ------------------------------------------字典----------------------------------------------
const meterIdentifyDict = ref<dictType[]>([]) // 计量标识
const usageStatusList = ref<dictType[]>([]) // 使用状态
const levelList = ref<dictType[]>([]) // 重要等级
const typeList = ref<dictType[]>([]) // 设备类型
const standardTypeList = ref<dictType[]>([]) // 标准类型
const useDeptList = ref<deptType[]>([]) // 所属部门列表
const userList = ref<{ [key: string]: string }[]>([]) // 用户列表
const categoryList = ref<dictType[]>([]) // 设备分类
const approveTypeList = ref<dictType[]>([]) // 审批类型
const approveTypeMap = ref({}) as any // 审批类型{1: 新建}

/**
 * 获取字典
 */
function getDict() {
  // 计量标识
  getDictByCode('bizMeterIdentify').then((response) => {
    meterIdentifyDict.value = response.data
  })
  // 使用状态
  getDictByCode('bizUsageStatus').then((response) => {
    usageStatusList.value = response.data
  })
  // 重要等级
  getDictByCode('bizEquipmentLevel').then((response) => {
    levelList.value = response.data
  })
  // 设备类型
  getDictByCode('bizEquipmentType').then((response) => {
    typeList.value = response.data
  })
  // 标准类型
  getDictByCode('bizStandardType').then((response) => {
    standardTypeList.value = response.data
  })
  // 获取部门列表
  getDeptTreeList().then((res) => {
    // 转成树结构
    useDeptList.value = toTreeList(res.data, '0', true)
  })
  // 获取用户列表
  getStaffList({ offset: 1, limit: 999999 }).then((res: any) => {
    userList.value = res.data.rows
  })
  // 设备分类
  getDictByCode('bizEquipmentCategory').then((response) => {
    categoryList.value = response.data
  })
  // 审批类型
  getDictByCode('approvalType').then((response) => {
    response.data.forEach((item: any) => {
      approveTypeMap.value[`${item.value}`] = item.name
    })
    approveTypeList.value = response.data
  })
}
// ----------------------------------------------- 保存---------------------------------------
const ruleFormRef = ref() // 基本信息表单ref
const sourceFormRef = ref()// 溯源表单ref
/**
 * 点击保存
 * @param ruleFormRef 基本信息表单ref
 * @param sourceFormRef 溯源表单ref
 */
function saveForm() {
  if (!useCheckList(technicalTargetList.value, technicalIndexColumns, '技术指标')) {
    return false
  }
  if (!technicalTargetList.value.length) {
    ElMessage.warning('技术指标不能为空')
    return false
  }
  if (!useCheckList(attachmentList.value, accessoryColumns, '主附件信息')) {
    return false
  }
  if (!attachmentList.value.length) {
    ElMessage.warning('主附件信息不能为空')
    return false
  }
  if (form.value.type === '1') { // 设备类型为标准设备时需要检查核查点
    if (!useCheckList(checkpointList.value, inspectColumns, '核查点')) {
      return false
    }
    if (!checkpointList.value.length) {
      ElMessage.warning('核查点不能为空')
      return false
    }
  }
  ruleFormRef.value.validate((valid: boolean) => {
    if (valid) { // 基本信息表单通过校验
      sourceFormRef.value.validate((validIn: boolean) => {
        if (validIn) { // 溯源表单信息通过校验
          ElMessageBox.confirm(
            '确认保存吗？',
            '提示',
            {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning',
            },
          ).then(() => {
            const params = {
              attachmentList: attachmentList.value.map((item) => { return { ...item, equipmentNo: form.value.equipmentNo } }), // 主附件信息
              checkpointList: checkpointList.value.map((item) => { return { ...item, equipmentNo: form.value.equipmentNo } }), // 核查点
              technicalTargetList: technicalTargetList.value.map((item) => { return { ...item, equipmentNo: form.value.equipmentNo } }), // 技术指标
              equipmentInfoApproval: {
                ...form.value,
                id: form.value.id,
                measureCycle: `${form.value.measureCycle}`,
              },
            }
            const loading = ElLoading.service({
              lock: true,
              text: '加载中...',
              background: 'rgba(255, 255, 255, 0.6)',
            })
            if (props.pageType === 'add') { // 新建
              addEquipment(params).then((res) => {
                loading.close()
                form.value.equipmentNo = res.data.equipmentNo // 设备编号
                infoId.value = res.data.id // id
                emits('addSuccess', form.value.equipmentNo, infoId.value)
                ElMessage.success('已保存')
              }).catch(() => {
                loading.close()
              })
            }
            else if (props.pageType === 'edit') { // 编辑
              switch (props.approvalStatusName) {
                case '草稿箱':
                  updateEquipment(params).then((res) => {
                    loading.close()
                    ElMessage.success('已保存')
                    emits('saveSuccess')
                    window.sessionStorage.setItem('infoParamType', '0')
                    useSetAllRowReadable(attachmentList.value)
                    useSetAllRowReadable(checkpointList.value)
                    useSetAllRowReadable(technicalTargetList.value) // 三个表格退出编辑模式
                  }).catch(() => {
                    loading.close()
                  })
                  break
                case '全部': // 全部的编辑-保存相当于新建一个草稿
                  params.equipmentInfoApproval.id = ''
                  params.equipmentInfoApproval.approvalType = '2' // 审批类型
                  addEquipment(params).then((res) => {
                    loading.close()
                    form.value.equipmentNo = res.data.equipmentNo // 设备编号
                    infoId.value = res.data.id // id
                    emits('addSuccess', form.value.equipmentNo, infoId.value)
                    window.sessionStorage.setItem('infoParamType', '0') // 全部编辑相当于新建一个草稿，所以去查草稿箱的详情传0
                    ElMessage.success('已保存')
                  }).catch(() => {
                    loading.close()
                  })
                  break
                default: // '未通过' || '已取消'
                  failUpdateEquipment(params).then((res) => {
                    loading.close()
                    ElMessage.success('已保存')
                    emits('submitSuccess', form.value.equipmentNo, infoId.value)
                    window.sessionStorage.setItem('infoParamType', '0')
                    fetchInfo() // 获取详情信息
                    useSetAllRowReadable(attachmentList.value)
                    useSetAllRowReadable(checkpointList.value)
                    useSetAllRowReadable(technicalTargetList.value) // 三个表格退出编辑模式
                  }).catch(() => {
                    loading.close()
                  })
                  break
              }
            }
          })
        }
      })
    }
  })
}

// -------------------------------------------获取详情信息----------------------------------------
/**
 * 获取详情
 * @param isCopy 是否备份，判断基本信息是否变化
 */
function fetchInfo(isCopy = false) {
  getInfo({ id: infoId.value!, type: window.sessionStorage.getItem('infoParamType')! }).then((res) => {
    attachmentList.value = res.data.attachmentList // 主附件信息
    checkpointList.value = res.data.checkpointList // 核查点
    technicalTargetList.value = res.data.technicalTargetList // 技术指标
    form.value = res.data.equipmentInfoApproval
    form.value.approvalType = `${res.data.equipmentInfoApproval.approvalType}` // 审批类型
    form.value.purchaseDate = dayjs(res.data.equipmentInfoApproval.purchaseDate).format('YYYY-MM-DD') // 购进日期
    form.value.produceDate = dayjs(res.data.equipmentInfoApproval.produceDate).format('YYYY-MM-DD')
    form.value.usedYears = dayjs().diff(res.data.equipmentInfoApproval.purchaseDate, 'year') // 使用年限
    const tempGetInfoForm = window.sessionStorage.getItem('equipmentGetInfoForm') ? JSON.parse(window.sessionStorage.getItem('equipmentGetInfoForm')!) : window.sessionStorage.getItem('equipmentGetInfoForm')
    if (isCopy && !tempGetInfoForm.equipmentName) {
      getInfoForm.value = {
        equipmentName: res.data.equipmentInfoApproval.equipmentName, // 设备名称
        unpackRecordId: res.data.equipmentInfoApproval.unpackRecordId, // 开箱记录id
        productCountry: res.data.equipmentInfoApproval.productCountry, // 生产国家
        manufacturer: res.data.equipmentInfoApproval.manufacturer, // 生产厂家
        manufactureNo: res.data.equipmentInfoApproval.manufactureNo, // 出厂编号
        purchaseDate: dayjs(res.data.equipmentInfoApproval.purchaseDate).format('YYYY-MM-DD'), // 购进日期
        produceDate: dayjs(res.data.equipmentInfoApproval.produceDate).format('YYYY-MM-DD'), // 生产日期
        unitPrice: res.data.equipmentInfoApproval.unitPrice, // 设备单价（万元）
        model: res.data.equipmentInfoApproval.model, // 型号规格
        qualityStatus: res.data.equipmentInfoApproval.qualityStatus, // 质量状况
        usageStatus: res.data.equipmentInfoApproval.usageStatus, // 使用状态
        level: res.data.equipmentInfoApproval.level, // 重要等级
        type: res.data.equipmentInfoApproval.type, // 设备类型
        standardType: res.data.equipmentInfoApproval.standardType, // 标准类型
        deptId: res.data.equipmentInfoApproval.deptId, // 部门id
        deptName: res.data.equipmentInfoApproval.deptName, // 所属部门
        directorId: res.data.equipmentInfoApproval.directorId, // 负责人id
        directorName: res.data.equipmentInfoApproval.directorName, // 负责人
        category: res.data.equipmentInfoApproval.category, // 设备分类
        measureCycle: res.data.equipmentInfoApproval.measureCycle, // 检定周期
        location: res.data.equipmentInfoApproval.location, // 位置
        remark: res.data.equipmentInfoApproval.remark, // 备注
        instructionsFile: res.data.equipmentInfoApproval.instructionsFile, // 说明书
      } // 保存用于比较修改需要审批的字段
      window.sessionStorage.setItem('equipmentGetInfoForm', JSON.stringify(getInfoForm.value))
    }
  })
}
// ----------------------------------------------提交--------------------------------------------
// 提交
/**
 *
 * @param processId 流程实例id
 * @param approvalType // 审批类型 1新建、2编辑、3删除
 * @param changeFlag // 基本信息是否变化 1、信息没变化、0信息有变化
 */
const handleSubmit = (processId: string, approvalType: string, changeFlag?: string) => {
  submit({ id: infoId.value!, formId: SCHEDULE.EQUIPMENT_BOOK_APPROVAL, processId, approvalType, changeFlag }).then((res) => {
    if (props.approvalStatusName === '草稿箱' && changeFlag === '1') { // 已经保存到草稿箱了
      infoId.value = res.data.id || infoId.value // id
      ElMessage.success('无基本信息变更，无需审批，更新成功')
    }
    else {
      ElMessage.success('已提交')
    }
    emits('submitSuccess', form.value.equipmentNo, infoId.value)
    fetchInfo(false) // 获取详细信息
  })
}
const submitForm = (processId = '') => {
  if (infoId.value) {
    // 未通过编辑、已取消编辑、新建正常走审批流程
    if (props.approvalStatusName === '未通过' || props.approvalStatusName === '已取消' || form.value.approvalType === '1') {
      // 未通过、已取消直接进流程，所以不需要查看基本信息有没有变化
      handleSubmit(processId, '')
    }
    if (props.approvalStatusName === '全部' || props.approvalStatusName === '草稿箱') {
      const tempGetInfoForm = JSON.parse(window.sessionStorage.getItem('equipmentGetInfoForm')!)
      // 检查基本信息有没有变化
      for (const key in tempGetInfoForm) {
        if (tempGetInfoForm[key] != form.value[key]) {
          handleSubmit(processId, '2', '0') // 信息有变化正常走审批流程
          return false
        }
      }
      // 信息没变化
      handleSubmit(processId, '2', '1')
      window.sessionStorage.setItem('infoParamType', '1')
    }
  }
  else {
    ElMessage.warning('请先保存')
  }
}

// ---------------------------------------------钩子----------------------------------------------
// 监听购进日期计算设备使用年限
watch(() => form.value.purchaseDate, (newValue) => {
  form.value.usedYears = dayjs().diff(newValue, 'year')
})

// 监听pageType处理审批类型
watch(() => props.pageType, (newValue) => {
  console.log('监听页面类型', newValue)
  form.value.approvalType = newValue === 'add' ? '1' : newValue === 'edit' ? '2' : ''
}, { immediate: true })

// 监听pageType处理审批类型
watch(() => props.approvalStatusName, (newValue) => {
  console.log('approvalStatusName')

  if (newValue === '全部') {
    window.sessionStorage.setItem('infoParamType', '1')
    // infoParamType.value = '1' // 从全部过来第一次传1，保存之后传0（因为保存到草稿箱里面了）
  }
  else {
    // infoParamType.value = '0'
    window.sessionStorage.setItem('infoParamType', '0')
  }
})

watch(() => props.id, (newValue) => {
  infoId.value = newValue!
  if (newValue) {
    if (props.approvalStatusName) {
      fetchInfo(false) // 获取详情信息
    }
  }
}, { immediate: true })

onMounted(async () => {
  await getDict() // 获取字典
  form.value.createUserId = user.id// 创建人id
  form.value.createUserName = user.name // 创建人
  form.value.createTime = dayjs().format('YYYY-MM-DD HH-mm:ss')// 申请时间
  if (props.pageType !== 'add') {
    console.log('onMounted')
    if (window.sessionStorage.getItem('equipmentGetInfoForm')) {
      fetchInfo(false) // 获取详情信息
    }
    else {
      fetchInfo(true) // 获取详情信息
    }
  }
})

defineExpose({ saveForm, submitForm })
</script>

<template>
  <detail-block title="">
    <el-form
      ref="ruleFormRef"
      :model="form"
      :label-width="120"
      label-position="right"
      :rules="rules"
    >
      <el-row v-if="props.approvalStatusName !== '全部' && props.approvalStatusName !== '草稿箱'" :gutter="24" class="marg">
        <el-col :span="6">
          <el-form-item label="审批类型:">
            <el-select
              v-model.trim="form.approvalType"
              placeholder=" "
              clearable
              size="default"
              disabled
              class="full-width-input"
            >
              <el-option
                v-for="item in approveTypeList"
                :key="item.id"
                :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="form.createUserName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="创建时间:">
            <el-date-picker
              v-model="form.createTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              disabled
              class="full-width-input"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" class="marg">
        <el-col :span="6">
          <el-form-item label="统一编号:" prop="equipmentNo">
            <el-input v-model="form.equipmentNo" disabled placeholder="系统自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="设备名称:" prop="equipmentName">
            <el-input
              v-model.trim="form.equipmentName"
              :placeholder="pageType === 'detail' ? '' : '请输入设备名称'"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="对应开箱记录:" prop="unpackRecordId">
            <span v-if="pageType === 'detail'" class="link" @click="handleClickUnpackRecordLink">{{ form.unpackRecordId }}</span>
            <el-input
              v-else
              v-model.trim="form.unpackRecordId"
              :placeholder="pageType === 'detail' ? ' ' : '请选择开箱记录'"
              disabled
              class="full-width-input"
              clearable
            >
              <template v-if="pageType !== 'detail'" #append>
                <el-button
                  size="small"
                  @click="selectUnpackRecordList"
                >
                  选择
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="购进日期:" prop="purchaseDate">
            <el-date-picker
              v-model="form.purchaseDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :placeholder="pageType === 'detail' ? ' ' : '请选择购进日期'"
              :disabled="pageType === 'detail'"
              class="full-width-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="生产国家:" prop="productCountry">
            <el-select
              v-model="form.productCountry"
              filterable
              :placeholder="pageType === 'detail' ? ' ' : '请选择生产国家'"
              :disabled="pageType === 'detail'"
              class="full-width-input"
            >
              <el-option v-for="country of countryList" :key="country.code" :label="country.CNName" :value="country.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="生产厂家:" prop="manufacturer">
            <el-input
              v-model.trim="form.manufacturer"
              :placeholder="pageType === 'detail' ? '' : '请输入生产厂家'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
              class="full-width-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="出厂编号:" prop="manufactureNo">
            <el-input
              v-model.trim="form.manufactureNo"
              :placeholder="pageType === 'detail' ? '' : '请输入出厂编号'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
              class="full-width-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="生产日期:" prop="produceDate">
            <el-date-picker
              v-model="form.produceDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :placeholder="pageType === 'detail' ? ' ' : '请选择生产日期'"
              :disabled="pageType === 'detail'"
              class="full-width-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="设备单价(万元)" prop="singlePrice">
            <el-input-number
              v-model="form.unitPrice"
              :placeholder="pageType === 'detail' ? '' : '请输入设备单价'"
              :disabled="pageType === 'detail'"
              :precision="4"
              :step="0.1"
              :min="0"
              class="full-width-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="使用年限:" prop="usedYears">
            <el-input
              v-model="form.usedYears"
              :placeholder="pageType === 'detail' ? '' : ''"
              :class="{ 'detail-input': pageType === 'detail' }"
              disabled
              class="full-width-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="型号规格" prop="model">
            <el-input
              v-model.trim="form.model"
              :placeholder="pageType === 'detail' ? '' : '请输入型号规格'"
              :disabled="pageType === 'detail'"
              class="full-width-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="质量状况" prop="qualityStatus">
            <el-input
              v-model.trim="form.qualityStatus"
              :placeholder="pageType === 'detail' ? '' : '请输入质量状况'"
              :disabled="pageType === 'detail'"
              class="full-width-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="使用状态:" prop="usageStatus">
            <el-select
              v-model.trim="form.usageStatus"
              clearable
              :placeholder="pageType === 'detail' ? '' : '请选择使用状态'"
              size="default"
              :disabled="pageType === 'detail'"
              class="full-width-input"
            >
              <el-option
                v-for="item in usageStatusList"
                :key="item.id"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="重要等级:" prop="level">
            <el-select
              v-model.trim="form.level"
              clearable
              :placeholder="pageType === 'detail' ? '' : '请选择重要等级'"
              size="default"
              :disabled="pageType === 'detail'"
              class="full-width-input"
            >
              <el-option
                v-for="item in levelList"
                :key="item.id"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="设备类型:" prop="type">
            <el-select
              v-model.trim="form.type"
              clearable
              :placeholder="pageType === 'detail' ? '' : '请选择设备类型'"
              size="default"
              :disabled="pageType === 'detail'"
              class="full-width-input"
            >
              <el-option
                v-for="item in typeList"
                :key="item.id"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标准类型:" prop="standardType">
            <el-select
              v-model.trim="form.standardType"
              clearable
              :placeholder="pageType === 'detail' ? '' : '请选择标准类型'"
              size="default"
              :disabled="pageType === 'detail'"
              class="full-width-input"
            >
              <el-option
                v-for="item in standardTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属部门" prop="deptId">
            <dept-select v-model="form.deptId" :data="useDeptList" :disabled="pageType === 'detail'" :placeholder="pageType === 'detail' ? ' ' : '所属部门'" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="负责人" prop="directorId">
            <el-select
              v-model.trim="form.directorId"
              placeholder="请选择负责人"
              filterable
              :disabled="pageType === 'detail'"
              class="full-width-input"
            >
              <el-option v-for="item in userList" :key="item.id" :label="item.staffName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="设备分类:" prop="category">
            <el-select
              v-model.trim="form.category"
              clearable
              :placeholder="pageType === 'detail' ? '' : '请选择设备分类'"
              size="default"
              :disabled="pageType === 'detail'"
              class="full-width-input"
            >
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="检定周期(月)" prop="measureCycle">
            <el-input-number
              v-model="form.measureCycle"
              :placeholder="pageType === 'detail' ? '' : '请输入检定周期'"
              :disabled="pageType === 'detail'"
              class="full-width-input"
              :min="0"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" class="marg">
        <el-col :span="12">
          <el-form-item label="位置信息:">
            <el-input
              v-model="form.location"
              type="textarea"
              autosize
              :placeholder="pageType === 'detail' ? '' : '请输入位置信息'"
              :disabled="pageType === 'detail'"
              :class="{ 'detail-input': pageType === 'detail' }"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" class="marg">
        <el-col :span="12">
          <el-form-item label="备注:">
            <el-input
              v-model="form.remark"
              type="textarea"
              autosize
              :placeholder="pageType === 'detail' ? '' : '请输入备注'"
              :disabled="pageType === 'detail'"
              :class="{ 'detail-input': pageType === 'detail' }"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" class="marg">
        <el-col :span="24">
          <el-form-item label="说明书:">
            <show-photo :minio-file-name="form.instructionsFile" width="100%" height="125px" />
            <el-button v-if="pageType !== 'detail'" type="primary" :disabled="pageType === 'detail'" :style="{ 'margin-left': form.instructionsFile === '' ? '0px' : '20px' }" @click="upload">
              {{ form.instructionsFile === '' ? '上传' : '更换附件' }}
            </el-button>
            <input v-show="pageType === ''" ref="fileRef" type="file" name="upload" multiple @change="onFileChange">
            <!-- <el-button v-if="pageType !== 'detail'" id="file" type="primary" :disabled="pageType === 'detail'" :style="{ 'margin-right': '20px' }" @click="upload">
              {{ !form.instructionsFile.length ? '上传' : '上传' }}
            </el-button>
            <div v-for="(item, index) in form.instructionsFile" :key="index" style="display: flex;">
              <show-photo :minio-file-name="item">
                <span v-if="pageType !== 'detail'" class="photo-close" @click="delFile(index)">×</span>
              </show-photo>
            </div>
            <span v-if="pageType === 'detail' && !form.instructionsFile.length">无</span>
            <input v-show="pageType === ''" ref="fileRef" type="file" name="upload" multiple @change="onFileChange"> -->
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="font-size: 13px;padding: 20px 0 10px 20px;color: #606266;">
      说明：以上信息发生变动时，需要经过审批才可生效
    </div>
  </detail-block>
  <!-- 溯源信息表单 -->
  <detail-block title="">
    <el-form
      ref="sourceFormRef"
      :model="form"
      :label-width="120"
      label-position="right"
      :rules="rules"
      style="display: flex;flex-wrap: nowrap;"
    >
      <el-form-item label="溯源单位:" prop="traceCompany" style="flex: 1;">
        <el-input
          v-model="form.traceCompany"
          :disabled="pageType === 'detail'"
          :placeholder="pageType === 'detail' ? ' ' : '请输入溯源单位'"
        />
      </el-form-item>
      <el-form-item label="溯源日期:" prop="traceDate" style="flex: 1;">
        <el-date-picker
          v-model="form.traceDate"
          type="date"
          :placeholder="pageType === 'detail' ? ' ' : '请选择日期'"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :disabled="pageType === 'detail'"
          class="full-width-input"
        />
      </el-form-item>
      <el-form-item label="检定有效期:" prop="measureValidDate" style="flex: 1;">
        <el-date-picker
          v-model="form.measureValidDate"
          type="date"
          :placeholder="pageType === 'detail' ? ' ' : '请选择日期'"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :disabled="pageType === 'detail'"
          class="full-width-input"
        />
      </el-form-item>
      <el-form-item label="计量标识:" prop="meterIdentify" style="flex: 1;">
        <el-select
          v-model="form.meterIdentify"
          :placeholder="pageType === 'detail' ? ' ' : '请选择计量标识'"
          :disabled="pageType === 'detail'"
          class="full-width-input"
        >
          <el-option v-for="item of meterIdentifyDict" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-button v-if="props.pageType === 'detail' && approvalStatusName === '全部'" type="primary" style="margin-left: 10px;" @click="printMeterIdentify">
        打印
      </el-button>
    </el-form>
  </detail-block>
  <!-- 技术指标 -->
  <detail-block title="技术指标">
    <div v-if="!(pageType === 'detail' && !form.meterStandardName && !form.technicalFile)" class="file-area">
      <span v-if="form.meterStandardName">所属测量标准：<span class="link" @click="handleClickMeterStandardLink">{{ form.meterStandardName }}</span></span>
      <div class="tech-file">
        <span v-if="pageType === 'detail' && form.technicalFile || pageType !== 'detail'" class="file-text">依据的技术文件: </span>
        <el-input
          v-if="pageType !== 'detail'"
          v-model.trim="form.technicalFile"
          :placeholder="pageType === 'detail' ? '' : '请选择技术文件'"
          disabled
          width="220"
        >
          <template v-if="pageType !== 'detail'" #append>
            <el-button
              size="small"
              @click="selectTechFile"
            >
              选择
            </el-button>
          </template>
        </el-input>
        <show-photo v-if="pageType === 'detail'" :minio-file-name="form.technicalFile!" width="100%" height="125px" />
      </div>
    </div>
    <template v-if="pageType !== 'detail'" #btns>
      <el-button type="primary" @click="addRow('tech')">
        增加行
      </el-button>
      <el-button type="info" @click="deleteRow('tech')">
        删除行
      </el-button>
    </template>
    <el-table
      ref="techRef"
      :data="technicalTargetList"
      border
      style="width: 100%;"
      @selection-change="handleTechSelectionChange"
      @row-dblclick="rowDblclickTech"
    >
      <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 technicalIndexColumns"
        :key="item.value"
        :prop="item.value"
        :label="item.text"
        align="center"
      >
        <template #header>
          <span v-show="item.required" style="color: red;">*</span><span>{{ item.text }}</span>
        </template>
        <template #default="scope">
          <span v-if="!scope.row.editable">{{ scope.row[item.value] }}</span>
          <el-input v-else v-model="scope.row[item.value]" :autofocus="true" :placeholder="`${item.text}`" class="input" />
        </template>
      </el-table-column>
    </el-table>
  </detail-block>
  <!-- 主附件信息 -->
  <detail-block title="主附件信息">
    <template v-if="pageType !== 'detail'" #btns>
      <el-button type="primary" @click="addRow('accessory')">
        增加行
      </el-button>
      <el-button type="info" @click="deleteRow('accessory')">
        删除行
      </el-button>
    </template>
    <el-table
      ref="accessoryRef"
      :data="attachmentList"
      border
      style="width: 100%;"
      @selection-change="handleAccessorySelectionChange"
      @row-dblclick="rowDblclickAccessory"
    >
      <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 accessoryColumns"
        :key="item.value"
        :prop="item.value"
        :label="item.text"
        align="center"
      >
        <template #header>
          <span v-show="item.required" style="color: red;">*</span><span>{{ item.text }}</span>
        </template>
        <template #default="scope">
          <span v-if="!scope.row.editable">{{ scope.row[item.value] }}</span>
          <el-input v-else v-model="scope.row[item.value]" :autofocus="true" :placeholder="`${item.text}`" class="input" />
        </template>
      </el-table-column>
    </el-table>
  </detail-block>
  <!-- 核查点（设备类型为标准设备下才显示） -->
  <detail-block v-if="form.type === '1'" title="核查点">
    <template v-if="pageType !== 'detail'" #btns>
      <el-button type="primary" @click="addRow('inspect')">
        增加行
      </el-button>
      <el-button type="info" @click="deleteRow('inspect')">
        删除行
      </el-button>
    </template>
    <el-table
      ref="inspectRef"
      :data="checkpointList"
      border
      style="width: 100%;"
      @selection-change="handleInspectSelectionChange"
      @row-dblclick="rowDblclickInspect"
    >
      <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 inspectColumns"
        :key="item.value"
        :prop="item.value"
        :label="item.text"
        align="center"
      >
        <template #header>
          <span v-show="item.required" style="color: red;">*</span><span>{{ item.text }}</span>
        </template>
        <template #default="scope">
          <span v-if="!scope.row.editable">
            <!-- 是否例行不可编辑状态 -->
            <span v-if="item.value === 'routine'">
              {{ scope.row[item.value] === '1' ? '是' : '否' }}
            </span>
            <!-- 其他列不可编辑状态 -->
            <span v-else>{{ scope.row[item.value] }}</span>
          </span>
          <!-- 是否例行可编辑状态 -->
          <el-select
            v-if="item.value === 'routine' && scope.row.editable"
            v-model="scope.row[item.value]"
            filterable
            :placeholder="pageType === 'detail' ? ' ' : `${item.text}`"
          >
            <el-option v-for="i of isRoutineMap" :key="i.id" :label="i.label" :value="i.id" />
          </el-select>
          <!-- 其他列可编辑状态 -->
          <el-input v-if="item.value !== 'routine' && scope.row.editable" v-model="scope.row[item.value]" :autofocus="true" :placeholder="`${item.text}`" class="input" />
        </template>
      </el-table-column>
    </el-table>
  </detail-block>
  <!-- 选择所依据的技术文件 -->
  <select-tech-files ref="techFileRef" @confirm="confirmSelectTechFile" />
  <!-- 选择开箱记录 -->
  <select-unpack-record-dialog ref="selectUnpackRecordDialogRef" @confirm="confirmSelectUnpackRecord" />
</template>

<style lang="scss" scoped>
.link {
  text-decoration: underline;
  color: #3d7eff;
  cursor: pointer;
}

.file-area {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #60627f;
  margin-bottom: 10px;
  margin-left: 40px;
  white-space: nowrap;

  .tech-file {
    display: flex;
    align-items: center;
    margin-left: 20px;

    .file-text {
      margin-right: 10px;
    }
  }
}
</style>
