Newer
Older
xc-business-system / src / views / equipement / source / plan / components / basic.vue
dutingting on 16 Jan 47 KB 需求开发、bug修复+4
<!-- 溯源计划管理 基本信息 -->
<script name="SourcePlanApproveBasic" lang="ts" setup>
import type { Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import dayjs from 'dayjs'
import type { IEquipmentInfoList, IForm, ITechnicalTargetList } from '../plan-interface'
import selectSourceDialog from '../dialog/selectSourceDialog.vue'
import SelectStaffDialog from '@/views/business/fieldTest/approve/dialog/selectStaffDialog.vue'
import type { dictType } from '@/global'
import { getDictByCode } from '@/api/system/dict'
import { SCHEDULE } from '@/utils/scheduleDict'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import useUserStore from '@/store/modules/user'
import { validateMobile } from '@/utils/validate'
import { getInfo as getEquipmentInfo, getEquipmentList } from '@/api/equipment/info/book'
import { useCheckList } from '@/commonMethods/useCheckList'
import { useDoubleClickTableRow, useSetAllRowReadable } from '@/commonMethods/useSetAllRowReadable'
import selectEquipmentDialog from '@/views/business/fieldTest/approve/dialog/selectEquipmentDialog.vue'
import { addSourcePlanList, failUpdateSourcePlanList, getInfo, getSourcePlanList, submit, updateSourcePlanList } from '@/api/equipment/source/plan'
import SelectStandardEquipmentDialog from '@/views/equipement/standard/checkData/dialog/selectStandardEquipmentDialog.vue'
const props = defineProps({
  pageType: { // 页面类型 add新建 edit编辑 detail详情
    type: String,
    requre: true,
    default: 'detail',
  },
  id: {
    type: String,
    requre: true,
  },
  approvalStatusName: { // 审批状态名称
    type: String,
    requre: true,
  },
  processId: {
    type: String,
  },
})
const emits = defineEmits(['addSuccess', 'submitSuccess'])
const user = useUserStore() // 用户信息
const form = ref<IForm>({
  id: '', // 列表id
  labCode: '', // 实验室
  groupCode: '', // 部门
  planNo: '', // 计划表编号
  planName: '', // 计划表名称
  createUserId: '', // 创建人id
  createUserName: '', // 创建人
  createTime: '', // 创建时间
  planGroup: '', // 计划表部门
  planYear: '', // 计划表年份

  applyTraceDate: '', // 申请溯源时间
  contacts: '王立', // 联系人
  phone: '18181279372', // 联系电话
})
const equipmentInfoForm = ref<IEquipmentInfoList>({
  equipmentId: '', // 设备id
  equipmentNo: '', // 统一编号
  equipmentName: '', // 设备名称
  model: '', // 规格型号
  manufactureNo: '', // 出厂编号
  manufacturer: '', // 生产厂家
  standardNo: '', // 所属测量标准号
  standardName: '', // 所属测量标准名称
  standardId: '', // 所属测量标准名称id
  standardSituation: '1', // 标准情况字典code
  standardSituationName: '', // 标准情况(字典value)
  equipmentCategory: '', // 所属类别(字典code)
  equipmentCategoryName: '', // 所属类别(字典value)

  meterIdentify: '', // 检定结果
  traceDate: '', // 测试、校准/检定日期
  traceWay: '', // 溯源方式(字典code)
  traceWayName: '', // 溯源方式(字典value)
  supplierId: '', // 溯源机构id
  supplierName: '', // 溯源机构名称
  planTraceTime: '', // 计划溯源时间
  remark: '', // 备注

  measureValidDate: '', // 检定有效期
  usageStatus: '', // 设备状态
  usageStatusName: '', // 设备状态名称

})
const ruleFormRef = ref() // 表单ref
const loading = ref(false) // loading
const infoId = ref('') // id

const validatePhone = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('联系电话不能为空'))
  }
  if (!validateMobile(value)) {
    callback(new Error('请输入正确格式的手机号'))
  }
  callback()
}
const rules = ref<FormRules>({ // 校验规则
  // 表单验证规则
  applyTraceDate: [{ required: true, message: '申请溯源时间不能为空', trigger: ['blur', 'change'] }],
  contacts: [{ required: true, message: '联系人不能为空', trigger: ['blur', 'change'] }],
  phone: [{ required: true, validator: validatePhone, trigger: ['blur', 'change'] }],
  labCode: [{ required: true, message: '实验室不能为空', trigger: ['blur', 'change'] }],
  groupCode: [{ required: true, message: '部门不能为空', trigger: ['blur', 'change'] }],
  planYear: [{ required: true, message: '年不能为空', trigger: ['blur', 'change'] }],
  planGroup: [{ required: true, message: '组不能为空', trigger: ['blur', 'change'] }],
  standardSituation: [{ required: true, message: '标准情况不能为空', trigger: ['blur', 'change'] }],
  equipmentCategory: [{ required: true, message: '所属类别不能为空', trigger: ['blur', 'change'] }],
  standardNo: [{ required: true, message: '所属测量标准号不能为空', trigger: ['blur', 'change'] }],
  standardName: [{ required: true, message: '所属测量标准名称不能为空', trigger: ['blur', 'change'] }],
  traceWay: [{ required: true, message: '溯源方式不能为空', trigger: ['blur', 'change'] }],
  supplierName: [{ required: true, message: '溯源机构名称不能为空', trigger: ['blur', 'change'] }],
  planTraceTime: [{ required: true, message: '计划溯源时间不能为空', trigger: ['blur', 'change'] }],
})

// -----------------------------------------字典--------------------------------------------------------------
const planGroupList = ref<dictType[]>([]) // 计划表部门
const labCodeList = ref<dictType[]>([]) // 实验室
const groupCodeList = ref<dictType[]>([]) // 部门
const meterIdentifyDict = ref<dictType[]>([]) // 计量标识

// 查询字典
const getDict = async () => {
  // 计量标识
  getDictByCode('bizMeterIdentify').then((response) => {
    meterIdentifyDict.value = response.data
  })
  getDictByCode('bizGroupCode').then((response) => {
    planGroupList.value = response.data
  })
  // 实验室
  getDictByCode('bizGroupCodeEquipment').then((response) => {
    labCodeList.value = response.data
  })
  // 部门
  getDictByCode('bizGroupCode').then((response) => {
    groupCodeList.value = response.data
  })
}

// -------------------------------------------表格--------------------------------------------------
const traceWayMap: { [key: string]: string } = {
  1: '自检',
  2: '送检',
  3: '比对',
}
const list = ref([]) as any // 溯源计划
const isShowEquipmentInfo = ref(false) // 是否显示设备信息
const isMulti = ref(false) // 是否多选
const checkoutList = ref([]) as any // 选中的表格
const equipmentInfoFormRef = ref() // 溯源需求组件ref
const selectEquipmentDialogRef = ref() // 选择设备组件
const sourceNeedlist = ref<ITechnicalTargetList[]>([]) // 溯源需求列表
const checkoutSourceNeedList = ref([]) as any // 选中的表格
const editIndex = ref() // 要编辑的是第几行
const selectIndex = ref(0) // 点击选择是第几行
const columns = ref([
  // { text: '统一编号', value: 'equipmentNo', align: 'center', width: '240', required: true },
  { text: '设备名称', value: 'equipmentName', align: 'center', required: true, width: '240' },
  { text: '规格型号', value: 'model', align: 'center', required: true },
  { text: '出厂编号', value: 'manufactureNo', align: 'center', required: true },
  { text: '生产厂家', value: 'manufacturer', align: 'center', required: true },
  { text: '检定有效期', value: 'measureValidDate', align: 'center', required: true, width: '120' },
  { text: '设备状态', value: 'usageStatusName', align: 'center', required: true },
  { text: '所属测量标准名称', value: 'standardName', align: 'center', required: true },
  { text: '溯源方式', value: 'traceWayName', align: 'center', required: true },
  { text: '溯源机构名称', value: 'supplierName', align: 'center', required: true },
  { text: '计划溯源时间', value: 'planTraceTime', align: 'center', width: '90', required: true },
])
const addObj = {
  id: '',
  equipmentId: '', // equipmentId
  equipmentNo: '', // 统一编号
  equipmentName: '', // 设备名称
  model: '', // 规格型号
  standardName: '', // 所属测量标准名称
  traceWayName: '', // 溯源方式
  supplierName: '', // 溯源机构名称
  planTraceTime: '', // 计划溯源时间
  measureValidDate: '', // 检定有效期
  usageStatus: '', // 设备状态
  usageStatusName: '', // 设备状态名称
}
// 多选发生改变时
const handleSelectionChange = (e: any) => {
  checkoutList.value = e
}

// 批量增加
const multiAdd = () => {
  if (!form.value.planYear) {
    ElMessage.warning('请填写年度,用来查询上一年的溯源方式')
    return false
  }
  isMulti.value = true
  selectEquipmentDialogRef.value.initDialog()
}

// 增加行
const addRow = () => {
  if (!form.value.planYear) {
    ElMessage.warning('请填写年度,用来查询上一年的溯源方式')
    return false
  }
  if (useCheckList(list.value, columns.value, '溯源计划')) {
    list.value.push(addObj)
  }
}
// 点击选择
const chooseList = (row: any, index: number) => {
  selectIndex.value = index
  console.log('888888888888888选择第几行设备', selectIndex.value)

  isMulti.value = false
  selectEquipmentDialogRef.value.initDialog()
}

// 删除行
const delRow = () => {
  if (!checkoutList.value.length) {
    ElMessage({
      message: '请选中要删除的行',
      type: 'warning',
    })
    return false
  }
  list.value = list.value.filter((item: any) => {
    return !checkoutList.value.includes(item)
  })
  checkoutList.value.forEach((item: { id: string }) => {
    if (equipmentInfoForm.value.equipmentId === item.id) {
      isShowEquipmentInfo.value = false
    }
  })
}
const lastTraceWay = ref('') // 上一年溯源方式
const lastTraceWayName = ref('')// 上一年溯源方式
const lastSupplierId = ref('')// 上一年溯源
const lastSupplierName = ref('')// 上一年溯源
// 获取上一年溯源信息
const fetchSourceInfoLastyear = () => {
  const year = Number(form.value.planYear) - 1
  console.log('上一年度', year)
  const param = {
    approvalStatus: '0', // 审批状态
    createTimeEnd: '', // 申请时间结束
    createTimeStart: '', // 申请时间开始
    createUserName: '', // 申请人
    formId: SCHEDULE.TRACE_PALN_APPROVAL, // formid
    planName: '', // 文件名称
    planNo: '', // 文件编号
    labCode: '', // 实验室
    groupCode: '', // 部门、部门、
    planYear: year, // 年度
    planStatus: '', // 溯源计划状态
    limit: 20,
    offset: 1,
  }
  getSourcePlanList(param).then((response) => {
    if (response.data.rows.length) {
      getInfo({ id: response.data.rows[0].id }).then((res) => {
        if (res && res.data && res.data.tracePlanEquipmentList && res.data.tracePlanEquipmentList.length) {
          lastTraceWay.value = res.data.tracePlanEquipmentList[0].traceWay
          lastTraceWayName.value = res.data.tracePlanEquipmentList[0].traceWayName
          lastSupplierId.value = res.data.tracePlanEquipmentList[0].supplierId
          lastSupplierName.value = res.data.tracePlanEquipmentList[0].supplierName
          list.value = list.value.map((item: any) => {
            return {
              ...item,
              traceWay: res.data.tracePlanEquipmentList[0].traceWay,
              traceWayName: res.data.tracePlanEquipmentList[0].traceWayName,
              supplierId: res.data.tracePlanEquipmentList[0].supplierId,
              supplierName: res.data.tracePlanEquipmentList[0].supplierName,
            }
          })
        }
      })
    }
  })
}

const haveStandardInfo = ref(false) // 所属标准装置信息是否可编辑
// 点击编辑
const handleClickEdit = (row: any, index: number) => {
  if (!form.value.planYear) {
    ElMessage.warning('请先选择文件名称的年份')
    return false
  }
  console.log('o[po[pki[p]]]', row)

  if (!row.equipmentId) {
    ElMessage.warning('请先选择设备')
    return false
  }
  isShowEquipmentInfo.value = true
  editIndex.value = index
  equipmentInfoForm.value = {
    equipmentId: row.equipmentId, // 设备id
    equipmentNo: row.equipmentNo, // 统一编号
    equipmentName: row.equipmentName, // 设备名称
    model: row.model, // 规格型号
    manufactureNo: row.manufactureNo, // 出厂编号
    manufacturer: row.manufacturer, // 生产厂家
    standardNo: row.standardNo, // 所属测量标准号
    standardName: row.standardName, // 所属测量标准名称
    standardId: row.standardId, // 所属测量标准id
    standardSituation: row.standardSituation, // 标准情况字典code
    standardSituationName: row.standardSituationName, // 标准情况(字典value)
    equipmentCategory: row.equipmentCategory, // 所属类别(字典code)
    equipmentCategoryName: row.equipmentCategoryName, // 所属类别(字典value)

    meterIdentify: row.meterIdentify, // 检定结果(计量标识)
    traceDate: row.traceDate, // 测试、校准/检定日期
    traceWay: row.traceWay, // 溯源方式(字典code)
    traceWayName: row.traceWayName, // 溯源方式(字典value)
    supplierId: row.supplierId, // 溯源机构id
    supplierName: row.supplierName, // 溯源机构名称
    planTraceTime: row.planTraceTime, // 计划溯源时间
    remark: row.remark, // 备注

    measureValidDate: row.measureValidDate, // 检定有效期
    usageStatus: row.usageStatus, // 设备状态
    usageStatusName: row.usageStatusName, // 设备状态名称
  }
  sourceNeedlist.value = row.technicalTargetList || []
  // 这里请求所属标准装置的数据
  getEquipmentInfo({ id: row.equipmentId, type: '1' }).then((res) => {
    const meterStandardList = res.data.standardInfoList.map((item: { standardName: string;standardNo: string;equipmentId: string }) => {
      return {
        standardName: item.standardName,
        standardNo: item.standardNo,
        id: item.equipmentId,
      }
    })
    haveStandardInfo.value = meterStandardList.length
    equipmentInfoForm.value.standardId = meterStandardList.map((item: { id: string }) => item.id).join(',')
    equipmentInfoForm.value.standardNo = meterStandardList.map((item: { standardNo: string }) => item.standardNo).join(',')
    equipmentInfoForm.value.standardName = meterStandardList.map((item: { standardName: string }) => item.standardName).join(',')
  })
  // fetchSourceInfoLastyear() // 获取上一年度溯源信息
}

// 确认选好设备
const confirmSelectedEquipment = (val: any) => {
  if (isMulti.value) { // 多选
    val.forEach((item: any) => {
      // 只添加列表里不存在的
      const index = list.value.findIndex((i: { equipmentId: string }) => item.id === i.equipmentId)
      if (index === -1) {
        list.value.push({
          ...item,
          planTraceTime: item.measureValidDate ? dayjs(item.measureValidDate).format('YYYY-MM') : item.measureValidDate, // 计划溯源时间
          standardName: item.meterStandardName, // 所属测量标准名称
          standardId: item.meterStandardId, // 所属测量标准名称id
          standardNo: item.meterStandardNo, // 所属测量标准编号

          standardSituation: item.standardSituation || '1', // 标准情况字典code
          standardSituationName: item.standardSituationName || '已建', // 标准情况(字典value)
          equipmentCategory: item.equipmentCategory || '1', // 所属类别(字典code)
          equipmentCategoryName: item.equipmentCategoryName || '主标准器', // 所属类别(字典value)

          supplierName: lastSupplierName.value, // 溯源机构名称使用的是上一年的溯源机构名称,不使用从设备带出来的溯源机构名称
          supplierId: lastSupplierId.value,
          traceWay: lastTraceWay.value, // 溯源方式(字典code) 使用的是上一年的溯源机构名称,不使用从设备带出来的溯源机构名称
          traceWayName: lastTraceWayName.value, // 溯源方式(字典value) 使用的是上一年的溯源机构名称,不使用从设备带出来的溯源机构名称
          id: '',
          equipmentId: item.id,
        })
      }
    })
  }
  else { // 单选
    console.log('-------------', list.value)

    const index = list.value.findIndex((i: { equipmentId: string }) => val[0].id === i.equipmentId)
    console.log('[[index]]', index)
    console.log('编辑第几行设备', selectIndex.value)

    if (index === -1) {
      list.value.splice(selectIndex.value, 1, {
        ...val[0],
        planTraceTime: val[0].measureValidDate ? dayjs(val[0].measureValidDate).format('YYYY-MM') : val[0].measureValidDate, // 计划溯源时间
        standardName: val[0].meterStandardName, // 所属测量标准名称
        standardId: val[0].meterStandardId, // 所属测量标准名称id
        standardNo: val[0].meterStandardNo, // 所属测量标准编号

        standardSituation: val[0].standardSituation || '1', // 标准情况字典code
        standardSituationName: val[0].standardSituationName || '已建', // 标准情况(字典value)
        equipmentCategory: val[0].equipmentCategory || '1', // 所属类别(字典code)
        equipmentCategoryName: val[0].equipmentCategoryName || '主标准器', // 所属类别(字典value)

        supplierName: lastSupplierName.value, // 溯源机构名称使用的是上一年的溯源机构名称,不使用从设备带出来的溯源机构名称
        supplierId: lastSupplierId.value,
        traceWay: lastTraceWay.value, // 溯源方式(字典code) 使用的是上一年的溯源机构名称,不使用从设备带出来的溯源机构名称
        traceWayName: lastTraceWayName.value, // 溯源方式(字典value) 使用的是上一年的溯源机构名称,不使用从设备带出来的溯源机构名称
        id: '',
        equipmentId: val[0].id,
      })
      console.log('-------------', list.value)
    }
    else {
      ElMessage.warning('此设备已添加过')
    }
  }
}

// 确认编辑
const conformEquipmentInfo = () => {
  if (!sourceNeedlist.value.length) {
    ElMessage.warning('溯源需求不能为空')
    return false
  }
  equipmentInfoFormRef.value.validate((valid: boolean) => {
    if (valid) {
      console.log('点击确认编辑', equipmentInfoForm.value)

      list.value[editIndex.value] = equipmentInfoForm.value
      list.value[editIndex.value].traceWayName = traceWayMap[`${equipmentInfoForm.value.traceWay}`]
      list.value[editIndex.value].technicalTargetList = sourceNeedlist.value // 溯源需求
      isShowEquipmentInfo.value = false // 隐藏编辑模块
      console.log('点击确认编辑', list.value)
    }
  })
}

// --------------------------------------------选择溯源机构---------------------------------------
const selectSourceDialogRef = ref() // 选择溯源机构组件ref
// 点击选择溯源机构
const selectsupplier = () => {
  selectSourceDialogRef.value.initDialog()
}

// 确定选择溯源机构
const confirmSelectedSource = (val: any) => {
  equipmentInfoForm.value.supplierId = val[0].id // 溯源机构id
  equipmentInfoForm.value.supplierName = val[0].supplierName // 溯源机构名称
}

// ----------------------------------------------溯源需求----------------------------------------

const sourceNeedColumns = ref([
  { text: '参数', value: 'measureParam', align: 'center', required: true },
  { text: '测量范围', value: 'measureRange', align: 'center', required: true },
])

// 点击增加行
const addSourceNeedRow = () => {
  const checkResult = useCheckList(sourceNeedlist.value, sourceNeedColumns.value, '溯源需求') // 检查表格
  if (checkResult) {
    useSetAllRowReadable(sourceNeedlist.value)
    sourceNeedlist.value.push({
      id: '',
      measureParam: '', // 参数
      measureRange: '', // 测量范围
      editable: true,
    })
  }
}

// 多选发生改变时
const handleSelectionSourceNeedChange = (e: any) => {
  console.log(e)
  checkoutSourceNeedList.value = e
}

// 删除行
const delSourceNeedRow = () => {
  console.log(checkoutSourceNeedList.value.length)
  if (!checkoutSourceNeedList.value.length) {
    ElMessage({
      message: '请选中要删除的行',
      type: 'warning',
    })
    return false
  }
  sourceNeedlist.value = sourceNeedlist.value.filter((item: any) => {
    return !checkoutSourceNeedList.value.includes(item)
  })
}

// 双击行
const rowDbClick = (row: any) => {
  if (props.pageType !== 'detail') {
    useDoubleClickTableRow(row, sourceNeedlist.value)
  }
}

// -----------------------------------------------保存----------------------------------------------
// 验证溯源需求
const checkoutTechnicalTargetList = () => {
  for (let i = 0; i < list.value.length; i++) {
    if (!list.value[i].technicalTargetList.length) {
      ElMessage.warning(`溯源计划表格第${i + 1}行【${list.value[i].equipmentName}】设备的【溯源需求】不能为空`)
      return false
    }
  }
  return true
}

/**
 * 点击保存
 * @param formEl 基本信息表单ref
 */
const saveForm = async () => {
  if (!useCheckList(list.value, columns.value, '溯源计划')) {
    return false
  }
  if (!list.value.length) {
    ElMessage.warning('溯源计划不能为空')
    return false
  }
  if (!checkoutTechnicalTargetList()) {
    return false
  }
  await ruleFormRef.value.validate((valid: boolean) => {
    if (valid) { // 基本信息表单通过校验
      ElMessageBox.confirm(
        '确认保存吗?',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        const loading = ElLoading.service({
          lock: true,
          text: '加载中...',
          background: 'rgba(255, 255, 255, 0.8)',
        })
        console.log('props.processId', props.processId)

        const params = {
          ...form.value,
          id: infoId.value,
          planName: `${form.value.planYear}年${form.value.planGroup}组测量设备溯源计划`,
          tracePlanEquipmentList: list.value.map((item: { planTraceTime: string }) => {
            return {
              ...item,
              planTraceTime: `${item.planTraceTime}-01 00:00:00`, // 计划溯源时间后台要求传带有时分秒的数据
            }
          }),
          processId: props.processId,
        }
        if (props.pageType === 'add') { // 新建
          addSourcePlanList(params).then((res) => {
            loading.close()
            form.value.planNo = res.data.planNo // 计划表编号
            infoId.value = res.data.id // id
            emits('addSuccess', infoId.value)
            ElMessage.success('已保存')
          }).catch(() => {
            loading.close()
          })
        }
        else if (props.pageType === 'edit') { // 编辑
          console.log(props.approvalStatusName)
          if (props.approvalStatusName === '草稿箱' || props.approvalStatusName === '全部') {
            updateSourcePlanList(params).then((res) => {
              loading.close()
              emits('addSuccess', infoId.value)
              ElMessage.success('已保存')
            }).catch(() => {
              loading.close()
            })
          }
          else { // '未通过' || '已取消'
            failUpdateSourcePlanList(params).then((res) => {
              loading.close()
              emits('submitSuccess')
              ElMessage.success('已保存')
            }).catch(() => {
              loading.close()
            })
          }
        }
      })
    }
  })
}
// -----------------------------------------选择联系人---------------------------------------
const selectStaffDialogRef = ref()

const handleClickSelectStaff = () => {
  selectStaffDialogRef.value.initDialog()
}

// 选好
const confirmSelectStaff = (val: any) => {
  form.value.contacts = val[0].staffName
  form.value.phone = '' // 联系电话
}

// ----------------------------------------------提交--------------------------------------------
// 提交
/**
 *
 * @param processId 流程实例id
 * @param id
 */
const submitForm = (processId: string, id: string) => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(255, 255, 255, 0.6)',
  })
  submit({ id, formId: SCHEDULE.TRACE_PALN_APPROVAL }).then((res) => {
    ElMessage.success('已提交')
    emits('submitSuccess')
    loading.close()
  })
}
// -----------------------------------------获取详情------------------------------------------
// 获取详情
const fetchInfo = () => {
  loading.value = true
  getInfo({ id: infoId.value }).then((res) => {
    loading.value = false
    form.value = res.data
    form.value.planYear = `${res.data.planYear}`
    list.value = res.data.tracePlanEquipmentList.map((item: { planTraceTime: string }) => {
      return {
        ...item,
        planTraceTime: item.planTraceTime ? dayjs(item.planTraceTime).format('YYYY-MM') : item.planTraceTime, // 计划溯源时间
      }
    }) // 设备列表
  })
}
// ---------------------------------------------钩子----------------------------------------------
watch(() => props.id, (newValue) => {
  infoId.value = newValue!
  if (infoId.value) {
    fetchInfo() // 获取详情信息
  }
}, { immediate: true })
const yearPickerRef = ref()

// 获取设备列表
const fetchEquipmentList = (labCode = '', groupCode = '', planYear = '') => {
  const loading = ElLoading.service({
    lock: true,
    text: '获取设备中,请耐心等待...',
    background: 'rgba(255, 255, 255, 0.6)',
  })
  const params = {
    approvalStatus: '0', //	审批状态类型code,导出接口不用传
    directorId: '', //		负责人id
    equipmentName: '', //		设备名称
    equipmentNo: '', //		设备编号
    formId: SCHEDULE.EQUIPMENT_BOOK_APPROVAL, //		表单id(流程定义对应的表单id,等价于业务id),导出接口不用传
    labCode, // 实验室
    groupCode, // 部门--后台定义用此字段筛选部门(刘翔)
    manufactureNo: '', //		出厂编号
    measureValidDateStart: '', //		检定有效期开始
    measureValidDateEnd: `${planYear}-12-31`, //		检定有效期结束
    meterStandardName: '', //		所属标准装置名称
    model: '', //		规格型号
    manufacturer: '', // 生产厂家
    // partType: '', //		参照标准、工作标准和关键测量设备表功能该参数传1(同时approvalStatus参数传0),其余情况不用传该参数
    standardType: '', //		标准类型(字典code)
    traceCompany: '', //		溯源单位
    scrapStatus: '1', // 是否为非报废
    offset: 1,
    limit: 20,
  }
  getEquipmentList({ ...params }).then((response) => {
    list.value = response.data.rows.map((item: any) => {
      return {
        ...item,
        equipmentId: item.id, // 设备id
        measureValidDate: item.measureValidDate ? dayjs(item.measureValidDate).format('YYYY-MM-DD') : item.measureValidDate,
        supplierName: lastSupplierName.value, // 溯源机构名称使用的是上一年的溯源机构名称,不使用从设备带出来的溯源机构名称
        supplierId: lastSupplierId.value,
        traceWay: lastTraceWay.value, // 溯源方式(字典code) 使用的是上一年的溯源机构名称,不使用从设备带出来的溯源机构名称
        traceWayName: lastTraceWayName.value, // 溯源方式(字典value) 使用的是上一年的溯源机构名称,不使用从设备带出来的溯源机构名称
        planTraceTime: item.measureValidDate ? dayjs(item.measureValidDate).format('YYYY-MM') : item.measureValidDate, // 计划溯源时间
        standardName: item.meterStandardName, // 所属测量标准名称
        standardId: item.meterStandardId, // 所属测量标准名称id
        standardNo: item.meterStandardNo, // 所属测量标准编号

        standardSituation: item.standardSituation || '1', // 标准情况字典code
        standardSituationName: item.standardSituationName || '已建', // 标准情况(字典value)
        equipmentCategory: item.equipmentCategory || '1', // 所属类别(字典code)
        equipmentCategoryName: item.equipmentCategoryName || '主标准器', // 所属类别(字典value)

      }
    })
    yearPickerRef.value.handleClose() // 隐藏年选择器
    loading.close()
  }).catch(() => {
    loading.close()
  })
  // fetchSourceInfoLastyear() // 获取上一年溯源机构
}
// 年度、实验室、部门变化事件
const changeValue = (val: any, type: string) => {
  form.value[type] = val
  if (`${form.value.labCode}` && `${form.value.groupCode}` && `${form.value.planYear}`) {
    if (list.value.length) {
      ElMessageBox.confirm(
        '修改后会覆盖溯源计划列表中的所有设备!,确认覆盖吗?',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        fetchEquipmentList(form.value.labCode, form.value.groupCode, form.value.planYear)
      }).catch(() => {
        yearPickerRef.value.handleClose() // 隐藏年选择器
      })
    }
    else {
      fetchEquipmentList(form.value.labCode, form.value.groupCode, form.value.planYear)
    }
  }
  if (type === 'planYear') {
    fetchSourceInfoLastyear() // 获取上一年溯源信息
    if (props.pageType !== 'detail') {
      if (form.value.labCode === 'X') {
        form.value.applyTraceDate = `${form.value.planYear}-05`
      }
      else if (form.value.labCode === 'H') {
        form.value.applyTraceDate = `${form.value.planYear}-10`
      }
    }
  }
  else if (type === 'labCode' && `${form.value.planYear}`) {
    if (props.pageType !== 'detail') {
      if (form.value.labCode === 'X') {
        form.value.applyTraceDate = `${form.value.planYear}-05`
      }
      else if (form.value.labCode === 'H') {
        form.value.applyTraceDate = `${form.value.planYear}-10`
      }
    }
  }
}

onMounted(() => {
  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' && infoId.value) {
    fetchInfo() // 获取详情信息
  }
})

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

<template>
  <div class="source-plan">
    <detail-block v-loading="loading" title="">
      <el-form
        ref="ruleFormRef"
        :model="form"
        :label-width="120"
        label-position="right"
        :rules="rules"
      >
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="文件编号:" prop="applyNo">
              <el-input v-model="form.planNo" disabled placeholder="系统自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="12" style="display: flex;line-height: 32px;">
            <span style="color: #f56c6c;margin-right: 2px;">*</span>
            <span style="color: #606266;font-size: 14px;margin-right: 12px;">文件名称:</span>
            <!-- <el-form-item label="计划表名称:" /> -->
            <el-form-item label-width="0" prop="planYear" style="width: 90px;">
              <el-date-picker
                ref="yearPickerRef"
                v-model="form.planYear"
                type="year"
                placeholder="年度"
                format="YYYY"
                value-format="YYYY"
                :disabled="pageType === 'detail'"
                :clearable="false"
                @change="(value: number) => changeValue(value, 'planYear')"
              />
            </el-form-item>
            <span style="margin: 0 8px;font-size: 14px;color: #606266;">年</span>
            <el-form-item label-width="0" prop="planGroup" style="width: 90px;">
              <!-- <el-select v-model="form.planGroup" placeholder="选择组">
              <el-option
                v-for="item in planGroupList"
                :key="item.value"
                :value="item.value"
                :label="item.name"
              />
            </el-select> -->
              <el-input v-model="form.planGroup" :disabled="pageType === 'detail'" placeholder="输入组" />
            </el-form-item>
            <span style="margin: 0 8px;font-size: 14px;color: #606266;">组测量设备溯源计划</span>
          </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="创建时间:" prop="createTime">
              <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
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="实验室" prop="labCode">
              <el-select
                v-model="form.labCode"
                :placeholder="pageType === 'detail' ? ' ' : '请选择实验室'"
                :disabled="pageType === 'detail'"
                class="full-width-input"
                @change="(value: string) => changeValue(value, 'labCode')"
              >
                <el-option
                  v-for="item in labCodeList"
                  :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="groupCode">
              <el-select
                v-model="form.groupCode"
                :placeholder="pageType === 'detail' ? ' ' : '请选择部门'"
                :disabled="pageType === 'detail'"
                class="full-width-input"
                @change="(value: string) => changeValue(value, 'groupCode')"
              >
                <el-option
                  v-for="item in groupCodeList"
                  :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="applyTraceDate">
              <el-date-picker
                v-model="form.applyTraceDate"
                type="month"
                placeholder="请选择申请溯源时间"
                format="YYYY-MM"
                value-format="YYYY-MM"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系人:" prop="contacts">
              <el-input
                v-model.trim="form.contacts"
                placeholder="联系人"
                class="detail-input"
                disabled
              >
                <template v-if="pageType !== 'detail'" #append>
                  <el-button
                    size="small"
                    @click="handleClickSelectStaff"
                  >
                    选择
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话:" prop="phone">
              <el-input
                v-model.trim="form.phone"
                placeholder="联系电话"
                class="detail-input"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-block>
    <detail-block v-loading="loading" title="溯源计划">
      <template v-if="pageType !== 'detail'" #btns>
        <el-button type="primary" @click="multiAdd">
          批量增加
        </el-button>
        <el-button type="primary" @click="addRow">
          增加行
        </el-button>
        <el-button type="info" @click="delRow">
          删除行
        </el-button>
      </template>
      <el-table
        :data="list"
        border
        style="width: 100%;"
        max-height="600"
        @selection-change="handleSelectionChange"
      >
        <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 columns"
          :key="item.value"
          :prop="item.value"
          :label="item.text"
          :width="item.width"
          align="center"
        >
          <template #header>
            <span v-show="item.required" style="color: red;">*</span><span>{{ item.text }}</span>
          </template>
          <template
            v-if="item.value === 'equipmentName' && pageType !== 'detail'"
            #default="scope"
          >
            <el-input
              v-model="scope.row[item.value]"
              :placeholder="`${item.text}`"
              class="input"
              disabled
            >
              <template v-if="pageType !== 'detail'" #append>
                <el-button
                  size="small"
                  @click="chooseList(scope.row, scope.$index)"
                >
                  选择
                </el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="90">
          <template #default="scope">
            <el-button v-if="pageType !== 'detail'" type="text" size="small" @click="handleClickEdit(scope.row, scope.$index)">
              编辑
            </el-button>
            <el-button v-if="pageType === 'detail'" type="text" size="small" @click="handleClickEdit(scope.row, scope.$index)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </detail-block>
    <!-- 编辑设备 -->
    <detail-block v-if="isShowEquipmentInfo" v-loading="loading" title=" ">
      <template #btns>
        <el-button v-if="pageType !== 'detail'" size="small" type="primary" @click="conformEquipmentInfo">
          确认编辑
        </el-button>
        <el-button size="small" type="info" @click="isShowEquipmentInfo = false">
          关闭
        </el-button>
      </template>
      <el-form
        ref="equipmentInfoFormRef"
        :model="equipmentInfoForm"
        :label-width="130"
        label-position="right"
        :rules="rules"
      >
        <el-row :gutter="24">
          <!-- <el-col :span="6">
            <el-form-item label="统一编号:" prop="equipmentNo">
              <el-input v-model="equipmentInfoForm.equipmentNo" disabled placeholder="统一编号" />
            </el-form-item>
          </el-col> -->
          <el-col :span="6">
            <el-form-item label="设备名称:" prop="equipmentName">
              <el-input v-model="equipmentInfoForm.equipmentName" disabled placeholder="设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="规格型号" prop="model">
              <el-input
                v-model.trim="equipmentInfoForm.model"
                placeholder="规格型号"
                disabled
                class="full-width-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出厂编号:" prop="manufactureNo">
              <el-input
                v-model.trim="equipmentInfoForm.manufactureNo"
                placeholder="出厂编号"
                class="detail-input"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产厂家:" prop="manufacturer">
              <el-input
                v-model.trim="equipmentInfoForm.manufacturer"
                placeholder="生产厂家"
                class="detail-input"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属测量标准编号:" label-width="140px" prop="standardNo">
              <el-input
                v-model.trim="equipmentInfoForm.standardNo"
                placeholder="请输入所属测量标准编号"
                class="detail-input"
                type="textarea"
                autosize
                :disabled="pageType === 'detail' || haveStandardInfo"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属测量标准名称:" label-width="140px" prop="standardName">
              <el-input
                v-model.trim="equipmentInfoForm.standardName"
                placeholder="请输入所属测量标准名称"
                class="detail-input"
                type="textarea"
                autosize
                :disabled="pageType === 'detail' || haveStandardInfo"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标准情况:" prop="standardSituation">
              <el-radio-group v-model="equipmentInfoForm.standardSituation" :disabled="pageType === 'detail'">
                <el-radio label="1">
                  已建
                </el-radio>
                <el-radio label="2">
                  待建
                </el-radio>
                <el-radio label="3">
                  其他
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属类别:" prop="equipmentCategory">
              <el-radio-group v-model="equipmentInfoForm.equipmentCategory" :disabled="pageType === 'detail'">
                <el-radio label="1">
                  主标准器
                </el-radio>
                <el-radio label="2">
                  配套仪器
                </el-radio>
                <el-radio label="3">
                  其他
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="上一年度溯源情况" />
          </el-col>
          <el-col :span="6">
            <el-form-item label="检定结果:" prop="meterIdentify">
              <el-select
                v-model="equipmentInfoForm.meterIdentify"
                :placeholder="pageType === 'detail' ? ' ' : '检定结果'"
                disabled
                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-col>
          <el-col :span="6">
            <el-form-item label="测试、校准/检定日期:" label-width="150px" prop="traceDate">
              <el-date-picker
                v-model="equipmentInfoForm.traceDate"
                type="datetime"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="本年溯源计划" />
          </el-col>
          <el-col :span="6">
            <el-form-item label="溯源方式:" prop="traceWay">
              <el-radio-group v-model="equipmentInfoForm.traceWay" :disabled="pageType === 'detail'">
                <el-radio label="1">
                  自检
                </el-radio>
                <el-radio label="2">
                  送检
                </el-radio>
                <el-radio label="3">
                  比对
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="溯源机构名称:" prop="supplierName">
              <el-input
                v-model="equipmentInfoForm.supplierName"
                placeholder="请选择溯源机构名称"
                class="input"
                disabled
              >
                <template v-if="pageType !== 'detail'" #append>
                  <el-button
                    size="small"
                    @click="selectsupplier"
                  >
                    选择
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="计划溯源时间:" prop="planTraceTime">
              <el-date-picker
                v-model="equipmentInfoForm.planTraceTime"
                type="month"
                :placeholder="pageType === 'detail' ? ' ' : '计划溯源时间'"
                class="full-width-input"
                :class="{ 'detail-input': pageType === 'detail' }"
                :disabled="pageType === 'detail'"
                format="YYYY-MM"
                value-format="YYYY-MM"
                :clearable="false"
              />
            </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="equipmentInfoForm.remark"
                type="textarea"
                autosize
                :placeholder="pageType === 'detail' ? '' : '请输入备注'"
                :disabled="pageType === 'detail'"
                :class="{ 'detail-input': pageType === 'detail' }"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 溯源需求 -->
      <detail-block v-loading="loading" title="溯源需求">
        <template v-if="pageType !== 'detail'" #btns>
          <el-button type="primary" @click="addSourceNeedRow">
            增加行
          </el-button>
          <el-button type="info" @click="delSourceNeedRow">
            删除行
          </el-button>
        </template>
        <el-table
          :data="sourceNeedlist"
          border
          style="width: 100%;"
          max-height="600"
          @row-dblclick="rowDbClick"
          @selection-change="handleSelectionSourceNeedChange"
        >
          <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 sourceNeedColumns"
            :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
              v-if="pageType !== 'detail'"
              #default="scope"
            >
              <el-input
                v-if="pageType !== 'detail'"
                v-model="scope.row[item.value]"
                :placeholder="`${item.text}`"
                class="input"
              />
              <span v-if="pageType === 'detail'">{{ scope.row[item.value] }}</span>
            </template>
          </el-table-column>
        </el-table>
      </detail-block>
    </detail-block>
    <!-- 选择设备台账 -->
    <select-equipment-dialog ref="selectEquipmentDialogRef" :is-multi="isMulti" @confirm="confirmSelectedEquipment" />
    <!-- 选择溯源供方 -->
    <select-source-dialog ref="selectSourceDialogRef" @confirm="confirmSelectedSource" />
    <!-- 选择计量人员  -->
    <select-staff-dialog ref="selectStaffDialogRef" :is-multi="false" @confirm="confirmSelectStaff" />
  </div>
</template>

<style lang="scss">
.source-plan {
  .el-radio__label {
    display: block !important;
  }
}
</style>