Newer
Older
xc-business-system / src / views / business / taskMeasure / measureData / components / first / templateDetail.vue
<!-- 第一套:多功能校准源标准装置 -->
<!-- 检定数据管理详情模板 -->
<script lang="ts" setup name="MeasureDataTemplateDetail">
import { ref } from 'vue'
import { ElLoading, ElMessage, tagEmits } from 'element-plus'
import dayjs from 'dayjs'
import type { IForm } from '../../measureData-interface'
import changeRecord from '../changeRecord.vue'
import selectStandard from '../../dialog/selectStandardDialog.vue'
import { useMaximumError } from '../../useCaculate'
import type { IDetailMeasureList } from './first-interface'
import { getUserList } from '@/api/system/user'
import useUserStore from '@/store/modules/user'
import { getDictByCode } from '@/api/system/dict'
import type { deptType, dictType } from '@/global'
import { getDeptTreeList } from '@/api/system/dept'
import { toTreeList } from '@/utils/structure'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getEquipmentList } from '@/api/equipment/standard/book'
import { useUniqueArray } from '@/utils/useUniqueArray'
import { calculateHandle, getInfo, getLocationList } from '@/api/business/taskMeasure/measureData'
import { getInfo as getItemInfo } from '@/api/business/measure/item'
import { getClassificationList } from '@/api/business/measure/classification'
import { useCheckList } from '@/commonMethods/useCheckList'
import { mergeTableRow, useMergeTableRow } from '@/commonMethods/useMergeTableRow'
import { getDataNum, getDataUnit } from '@/utils/validate'

const props = defineProps({
  infoId: String, // id
  dataNo: String, // 检定数据编号
})
const emits = defineEmits(['giveInfoId'])
const user = useUserStore() // 用户信息
const $router = useRouter() // 关闭页面使用
const $route = useRoute() // 路由参数
const ruleFormRef = ref() // 表单ref
const form = ref<IForm>({
  dataNo: '', // 检定数据编号
  measureCategory: '', // 检校类别
  measureCategoryName: '', // 检校类别名称
  customerName: '', // 委托单位
  traceDate: '', // 测试、校准或检定日期
  measureValidDate: '', // 检定有效期
  measureAddress: '', // 测试、校准或检定地点
  temperature: '', // 温度
  humidity: '', // 相对湿度
  orderId: '',
  orderNo: '', // 任务单编号
  technologyFile: '', // 依据的技术文件(编号、名称)
  createUserId: '', // 检定员id
  createUserName: '', // 检定员
  dataSource: '', // 数据来源
  conclusion: '', // 结论
  restrictionInstruction: '', // 限用说明
  appearanceFunctionCheck: '', // 外观及功能性检查
  itemId: '', // 检定项id
  itemCategoryName: '', // 设备检定项分类名称
  itemCategoryId: '', // 设备检定项分类名称id
  belongStandardEquipment: '', // 标准装置code
  belongStandardEquipmentName: '', // 标准装置名称
  ipri: '', // 电流转换系数
  ipriUnit: 'A', // 电流转换系数单位
  isec: '', // 电流转换系数
  isecUnit: 'A', // 电流转换系数单位
  vpri: '', // 电压转换系数
  vpriUnit: 'V', // 电压转换系数单位
  vsec: '', // 电压转换系数
  vsecUnit: 'V', // 电压转换系数单位
})
// 校验规则
const rules = ref({
  measureCategory: [{ required: true, message: '检校类别不能为空', trigger: ['blur', 'change'] }],
  // customerName: [{ required: true, message: '委托单位不能为空', trigger: ['blur', 'change'] }],
  traceDate: [{ required: true, message: '测试、校准或检定日期不能为空', trigger: ['blur', 'change'] }],
  measureValidDate: [{ required: true, message: '检定有效期不能为空', trigger: ['blur', 'change'] }],
  measureAddress: [{ 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'] }],
  // orderNo: [{ required: true, message: '任务单编号不能为空', trigger: ['blur', 'change'] }],
  // technologyFile: [{ required: true, message: '依据的技术文件不能为空', trigger: ['blur', 'change'] }],
  createUserName: [{ required: true, message: '检定员不能为空', trigger: ['blur', 'change'] }],
  conclusion: [{ required: true, message: '结论不能为空', trigger: ['blur', 'change'] }],
  restrictionInstruction: [{ required: true, message: '限用说明不能为空', trigger: ['blur', 'change'] }],
  appearanceFunctionCheck: [{ required: true, message: '外观及功能性检查不能为空', trigger: ['blur', 'change'] }],
})

const itemCategoryName = ref('') // 设备检定项分类名称
const measureItemConfigCalibrator = ref({}) as any // 后五种设备表单配置
// -------------------------------------------路由参数------------------------------------------
const pageType = ref('add') // 页面类型: add, edit, detail
const infoId = ref('') // 列表id
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string

  if ($route.params.id) {
    infoId.value = $route.params.id as string
  }
}
// -------------------------------------------字典---------------------------------------------+
const conclusionList = ref<dictType[]>([]) // 结论
const measureCategoryList = ref<dictType[]>([]) // 检校类别
const IUnitList = ref<dictType[]>([]) // 电流转换系数单位
const UUnitList = ref<dictType[]>([]) // 电压转换系数
const positionList = ref([]) as any // 测试、校准或检定地点
const userList = ref<{ [key: string]: string }[]>([]) // 用户列表
const useDeptList = ref<deptType[]>([]) // 所属部门列表
const deptList = ref<deptType[]>([]) // 所属部门列表
const lineModeList = ref<dictType[]>([]) // 两线/四线模式

// 获取字典值
async function getDict() {
  // 结论
  getDictByCode('bizConclusion').then((response) => {
    conclusionList.value = response.data
  })
  // 检校类别
  getDictByCode('measureCategory').then((response) => {
    measureCategoryList.value = response.data
  })
  // I单位(电流转换系数单位)
  getDictByCode('bizFirstStandardUnitI').then((response) => {
    IUnitList.value = response.data
  })
  // U单位(电压转换系数单位)
  getDictByCode('bizFirstStandardUnitU').then((response) => {
    UUnitList.value = response.data
  })

  // 两线/四线模式
  getDictByCode('bizFirstStandardLineMode').then((response) => {
    lineModeList.value = response.data
  })
  // 测试、校准或检定地点
  getLocationList({
    locationName: '', // 地点名称
    locationNo: '', // 地点编号
    limit: 999999,
    offset: 1,
  }).then((res) => {
    positionList.value = res.data.rows.map((item: { id: string; locationName: string; temperature: string; humidity: string }) => {
      return {
        id: item.id,
        name: item.locationName, // 地点名称
        temperature: `${item.temperature}` || '', // 温度
        humidity: `${item.humidity}` || '', // 湿度
      }
    })
  })

  // 获取用户列表
  getUserList({ offset: 1, limit: 999999 }).then((res: any) => {
    userList.value = res.data.rows
  })
  // 获取部门列表
  getDeptTreeList().then((res) => {
    deptList.value = res.data
    // 转成树结构
    useDeptList.value = toTreeList(res.data, '0', true)
  })
  // 获取用户列表
  // getStaffList({ offset: 1, limit: 999999 }).then((res: any) => {
  //   userList.value = res.data.rows
  // })
}

// --------------------------------------被检件信息--------------------------------------------------------
const sampleList = ref([]) as any // 被检件
const columns = ref<TableColumn[]>([ // 表头
  { text: '设备名称', value: 'sampleName', align: 'center' },
  { text: '规格型号', value: 'sampleModel', align: 'center' },
  { text: '出厂编号', value: 'manufactureNo', align: 'center' },
  { text: '制造厂家', value: 'manufacturer', align: 'center' },
  { text: '设备检定项分类', value: 'categoryName', align: 'center' },
])
// --------------------------------------所使用的标准,主要测量设备--------------------------------------------------------
const measureDataCalibratorList = ref([]) as any // 列表
const selectStandardRef = ref() // 所使用的标准,主要测量设备组件ref
const checkoutMeasureDataCalibratorList = ref([]) as any // 选中列表
const tableLoading = ref(false) // 表格loading
const measureDataCalibratorColumns = ref<TableColumn[]>([ // 表头
  { text: '设备名称', value: 'equipmentName', align: 'center' },
  { text: '规格型号', value: 'model', align: 'center' },
  { text: '出厂编号', value: 'manufactureNo', align: 'center' },
  { text: '不确定度或允许误差极限或准确度等级', value: 'uncertainty', align: 'center' },
  { text: '证书有效期', value: 'measureValidDate', align: 'center' },
])

// 用标准装置id获取标准配套设备查询条件
const listQuery = ref({
  standardId: '',
  offset: 1,
  limit: 999999,
})

// 批量增加
const multiFilesAdd = () => {
  selectStandardRef.value.initDialog()
}

// 选好标准装置
const confirmSelectStandard = (val: any) => {
  if (val.length) {
    const allRequest = [] as any // 所有的请求
    let tempEquipmentList = [] as any // 临时变量-选择的标准装置所对应的配套设备
    val.forEach((item: { id: string }) => {
      tableLoading.value = true // 表格loading
      listQuery.value.standardId = item.id // 标准装置id
      const request = getEquipmentList(listQuery.value).then((res) => { // 请求
        const tempArr = [] as any
        res.data.rows.forEach((item: any) => {
          if (!item.technicalTargetList.length) {
            tempArr.push(item)
          }
          else {
            let tempUncertainty = ''
            item.technicalTargetList.forEach((i: any) => {
              tempUncertainty = `${tempUncertainty}${i.uncertainty}; `
            })
            tempArr.push({
              ...item,
              uncertainty: tempUncertainty,
            })
          }
        })
        tempEquipmentList = tempEquipmentList.concat(tempArr)
      })
      allRequest.push(request) // 集合所有请求
    })
    Promise.all(allRequest).then(() => { // 等待所有请求完成
      let tempList = [] as any // 临时数组
      tempList = tempList.concat(tempEquipmentList)
      measureDataCalibratorList.value = useUniqueArray(tempList) // 数组去重
      tableLoading.value = false
    })
  }
}

// 表格多选
const handleSelectionChange = (e: any) => {
  checkoutMeasureDataCalibratorList.value = e
}

// 删除行
const delRow = () => {
  if (checkoutMeasureDataCalibratorList.value.length <= 0) {
    ElMessage({
      message: '请选中要删除的行',
      type: 'warning',
    })
  }
  else {
    checkoutMeasureDataCalibratorList.value.forEach((item: any) => {
      measureDataCalibratorList.value.forEach((element: any, index: number) => {
        if (element.equipmentNo === item.equipmentNo) {
          measureDataCalibratorList.value.splice(index, 1)
        }
      })
    })
  }
}
// ------------------------------------------标签----------------------------------------------------------
const radioMenus = ref([ // 标签内容
  { name: '检定数据', value: 'measure-data' },
  { name: '历史修改记录', value: 'change-record' },
])
const current = ref('measure-data') // 选择的tab 默认基本信息

// ---------------------------------------检定项数据表格----------------------------------------------------
const list = ref<IDetailMeasureList[]>([]) // 表格数据
const appearanceFunctionCheck = ref('') // 外观及功能性检查
const measureColumns = ref([]) as any // 表头数据
const columns_digitalMultimeterHandheld = ref([ // 数字多用表(手持)、钳形电流表、指针式万用表
  { text: '参数', value: 'params', align: 'center', required: true, width: '80' },
  { text: '量', value: 'capacity', align: 'center', width: '80', required: true },
  { text: '单位', value: 'unit', align: 'center', width: '80', required: true },
  { text: '频率', value: 'frequency', align: 'center' },
  { text: '单位', value: 'frequencyUnit', align: 'center', width: '80' },
  { text: '量程', value: 'rangeRange', align: 'center', required: true },
  { text: '标准值', value: 'standardValue', align: 'center', required: true },
  { text: '示值', value: 'indicatingValue', align: 'center', required: true },
  { text: '绝对误差', value: 'absoluteError', align: 'center' },
  { text: '最大允许误差', value: 'maximumError', align: 'center' },
  { text: '分辨力', value: 'resolution', align: 'center', required: true },
])
const columns_digitalMultimeterTable = ref([ // 数字多用表(台式)
  { text: '参数', value: 'params', align: 'center', required: true },
  { text: '量', value: 'capacity', align: 'center', width: '120', required: true },
  { text: '单位', value: 'unit', align: 'center', width: '120', required: true },
  { text: '频率', value: 'frequency', align: 'center' },
  { text: '单位', value: 'frequencyUnit', align: 'center', width: '120' },
  { text: '量程', value: 'rangeRange', align: 'center', required: true },
  { text: '标准值', value: 'standardValue', align: 'center', required: true },
  { text: '两线/四线模式', value: 'lineMode', align: 'center', required: false, width: '120' },
  { text: '示值', value: 'indicatingValue', align: 'center', required: true },
  { text: '绝对误差', value: 'absoluteError', align: 'center' },
  { text: '最大允许误差', value: 'maximumError', align: 'center' },
  { text: '分辨力', value: 'resolution', align: 'center', required: true },
  { text: '输出备注', value: 'remark', align: 'center' },
])

const columns_multifunctionalPowerParameterMeasuringInstrument = ref([ // 多功能电力参数测量仪
  { text: '参数', value: 'params', align: 'center', required: true, width: '120' },
  { text: '量', value: 'capacity', align: 'center', width: '120', required: true },
  { text: '单位', value: 'unit', align: 'center', width: '120', required: true },
  { text: '频率', value: 'frequency', align: 'center' },
  { text: '单位', value: 'frequencyUnit', align: 'center', width: '120' },
  { text: '标准值', value: 'standardValue', align: 'center', required: true },
  { text: 'AN', value: 'an', align: 'center', required: true, width: '180' },
  { text: 'BN', value: 'bn', align: 'center', required: true, width: '180' },
  { text: 'CN', value: 'cn', align: 'center', required: true, width: '180' },
  { text: '最大允许误差', value: 'maximumError', align: 'center' },
  { text: '△AN', value: 'deltaAn', align: 'center', width: '180' },
  { text: '△BN', value: 'deltaBn', align: 'center', width: '180' },
  { text: '△CN', value: 'deltaCn', align: 'center', width: '180' },
  { text: '分辨力', value: 'resolution', align: 'center', required: true },
])

const columns_lastFive = ref([ // 交流电压表、交流电流表、直流电压表、直流电流表、75mV电流表
  { text: '参数', value: 'params', align: 'center', required: true, width: '120' },
  { text: '量', value: 'capacity', align: 'center', width: '120', required: true },
  { text: '单位', value: 'unit', align: 'center', width: '120', required: true },
  { text: '被检表示值', value: 'measureIndicationValue', align: 'center', width: '120', required: true },
  { text: '标准值', value: 'standardValue', align: 'center', width: '120', required: true },
  { text: '最大允许误差', value: 'maximumError', align: 'center' },
  { text: '绝对误差', value: 'absoluteError', align: 'center' },
  { text: '分辨力', value: 'resolution', align: 'center', required: true },
])

// -------------------------------------------获取详情信息--------------------------------------------------
// 获取页面详情信息
const fetchInfo = () => {
  const loading = ElLoading.service({
    lock: true,
    background: 'rgba(255, 255, 255, 0.8)',
  })
  getInfo({
    id: infoId.value,
    belongStandardEquipment: form.value.belongStandardEquipment,
    // 我的任务跳转过来如果已经配置过检定项了,到编辑页面,且用一下三个字段替代传id请求详情
    itemId: $route.query.itemId, // 检定项id
    orderId: $route.query.orderId, // 任务单id
    sampleId: $route.query.sampleId, // 被检设备id
  }).then((res) => {
    form.value = res.data
    form.value.itemCategoryName = $route.query.itemCategoryName as string // 设备检定项分类名称
    form.value.itemCategoryId = $route.query.itemCategoryId as string// 设备检定项分类名称id
    form.value.belongStandardEquipment = $route.query.belongStandardEquipment as string// 标准装置code
    form.value.belongStandardEquipmentName = $route.query.belongStandardEquipmentName as string// 标准装置名称
    infoId.value = res.data.id
    emits('giveInfoId', infoId.value)
    itemCategoryName.value = res.data.itemCategoryName // 检定项分类名称
    measureDataCalibratorList.value = res.data.equipmentList.map((item: any) => {
      return {
        ...item,
        id: item.equipmentId,
      }
    }) // 所使用的标准,主要测量设备
    // // 获取依据的技术文件
    fetchClassificationData(false, res.data.itemCategoryName! as string, res.data.belongStandardEquipment as string)
    sampleList.value = [{ // 被检设备
      sampleId: res.data.sampleId, // 设备id
      sampleName: res.data.sampleName, // 设备名称
      sampleModel: res.data.model, // 规格型号
      manufactureNo: res.data.manufactureNo, // 出厂编号
      manufacturer: res.data.manufacturer, // 制造厂家(生产厂家)
      categoryName: res.data.itemCategoryName, // 设备检定项分类
    }]
    list.value = res.data.measureDataCalibratorList.map((item: IDetailMeasureList) => {
      return {
        ...item,
        resolution: Number(item.resolution),
        redStar: Math.abs(Number(item.absoluteError)) <= Math.abs(Number(getDataNum(item.maximumError))) ? 'normal' : 'error',
      }
    }) // 检定数据
    loading.close()
  })
}

function solveColumn(res: any) {
  columns_lastFive.value = [ // 交流电压表、交流电流表、直流电压表、直流电流表、75mV电流表
    { text: '参数', value: 'params', align: 'center', required: true, width: '120' },
    { text: '量', value: 'capacity', align: 'center', width: '120', required: true },
    { text: '单位', value: 'unit', align: 'center', width: '120', required: true },
    { text: `被检表示值(${getDataUnit(res.data.measureItemDataCalibratorList[0].measureIndicationValue)})`, value: 'measureIndicationValue', align: 'center', width: '120', required: true },
    { text: `标准值(${getDataUnit(measureItemConfigCalibrator.value.standardValueUpperUnit)})`, value: 'standardValue', align: 'center', width: '120', required: true },
    { text: `最大允许误差(${getDataUnit(res.data.measureItemDataCalibratorList[0].maximumError)})`, value: 'maximumError', align: 'center' },
    { text: '绝对误差', value: 'absoluteError', align: 'center' },
    { text: '分辨力', value: 'resolution', align: 'center', required: true },
  ]
  measureColumns.value = columns_lastFive.value
}
const inputList = ref<IDetailMeasureList[]>([]) // 记录输入数据
/**
 * 新增的时候获取检定项输入数据(获取检定项分类详情)
 * @param itemId  检定项id
 * @param itemCategoryName 检定项分类名字
 * @param belongStandardEquipment 检校标准装置字典
 */
const fetchItemInfo = async (itemId: string, itemCategoryName: string, belongStandardEquipment = '', solveList = '') => {
  const params = {
    id: itemId,
    itemCategoryName, // 检定项分类名字
    belongStandardEquipment, // 检校标准装置字典code
  }
  const res = await getItemInfo(params)
  appearanceFunctionCheck.value = res.data.appearanceFunctionCheck // 外观及功能检查 1有外观,2没有外观
  if (res.data.appearanceFunctionCheck) { // 勾选外观
    form.value.appearanceFunctionCheck = '外观完好,工作正常'
  }
  else {
    form.value.appearanceFunctionCheck = ''
  }
  measureItemConfigCalibrator.value = res.data.measureItemConfigCalibrator // 后五种设备表单配置
  if (itemCategoryName === '交流电压表' || itemCategoryName === '交流电流表' || itemCategoryName === '直流电压表' || itemCategoryName === '直流电流表' || itemCategoryName === '75mV电流表') {
    solveColumn(res)
    if (solveList !== 'notNeedList') {
      inputList.value = res.data.measureItemDataCalibratorList.map((item: IDetailMeasureList) => {
        return {
          itemDataId: item.id,
          params: item.params, // 参数
          capacity: item.capacity, // 量
          unit: item.unit, // 单位
          frequency: item.frequency, // 频率
          frequencyUnit: item.frequencyUnit, // 频率单位
          rangeRange: item.rangeRange, // 量程
          standardValue: item.standardValue, // 标准值
          resolution: item.resolution, // 分辨力
          indicatingValue: item.indicatingValue, /// 示值
          lineMode: item.lineMode || '/',
          maximumError: getDataNum(item.maximumError), // 最大允许误差
          absoluteError: '', // 绝对误差
          remark: '', // 输出备注
          an: '', // AN
          bn: '', // BN
          cn: '', // CN
          deltaAn: '', // △AN
          deltaBn: '', // △BN
          deltaCn: '', // △CN
          measureIndicationValue: getDataNum(item.measureIndicationValue), // 被检表示值
          maximumErrorFormula: '', // 最大允许误差(把公式给后台传过去)
          errorParamA: item.errorParamA, // 误差参数a
          errorParamB: item.errorParamB, // 误差参数b
          standardValueUpperLimit: measureItemConfigCalibrator.value.standardValueUpper, // 标准值上限
          accuracyLevel: measureItemConfigCalibrator.value.accuracyLevel, // 准确度等级
        }
      }) // 检定项表格
      list.value = inputList.value
    }
  }
  else {
    inputList.value = res.data.measureItemDataCalibratorList.map((item: IDetailMeasureList) => {
      return {
        itemDataId: item.id,
        params: item.params, // 参数
        capacity: item.capacity, // 量
        unit: item.unit, // 单位
        frequency: item.frequency, // 频率
        frequencyUnit: item.frequencyUnit, // 频率单位
        rangeRange: item.rangeRange, // 量程
        standardValue: item.standardValue, // 标准值
        resolution: item.resolution, // 分辨力
        indicatingValue: item.indicatingValue, /// 示值
        lineMode: item.lineMode || '/',
        maximumError: itemCategoryName === '指针式万用表' ? useMaximumError(item.accuracyA!, item.fullScaleValue!) + item.fullScaleValueUnit! : item.maximumError, // 最大允许误差
        absoluteError: '', // 绝对误差
        remark: '', // 输出备注
        an: '', // AN
        bn: '', // BN
        cn: '', // CN
        deltaAn: '', // △AN
        deltaBn: '', // △BN
        deltaCn: '', // △CN
        measureIndicationValue: item.measureIndicationValue, // 被检表示值
        maximumErrorFormula: '', // 最大允许误差(把公式给后台传过去)
        errorParamA: item.errorParamA, // 误差参数a
        errorParamB: item.errorParamB, // 误差参数b
        accuracyA: item.accuracyA, // 准确度a ---用于指针式万用表最大允许误差计算
        fullScaleValue: item.fullScaleValue, // 指针式仪表满量程值---用于指针式万用表最大允许误差计算
        fullScaleValueUnit: item.fullScaleValueUnit, // 指针式仪表满量程值单位---用于指针式万用表最大允许误差计算
      }
    }) // 检定项表格
    list.value = inputList.value
  }
}

// 获取检定项分类的技术文件
// 查询条件
const fetchClassificationListQuery = ref({
  belongStandardEquipment: '', // 检校标准装置
  categoryName: '', // 检定项分类名称
  categoryNo: '', // 检定项分类编号
  deviceType: '', // 设备分类
  measureCategory: '', // 检校类别
  limit: 20,
  offset: 1,
})

// 数据查询
function fetchClassificationData(isNowPage = false, categoryName = '', belongStandardEquipment = '') {
  if (!isNowPage) {
    // 是否显示当前页,否则跳转第一页
    listQuery.value.offset = 1
  }
  fetchClassificationListQuery.value.categoryName = categoryName // 设备分类型名称
  fetchClassificationListQuery.value.belongStandardEquipment = belongStandardEquipment // 检校标准装置名称
  getClassificationList(fetchClassificationListQuery.value).then((response) => {
    if (response.data.rows.length) {
      form.value.technologyFile = response.data.rows[0].technologyFile.split(';')
    }
  })
}

// ----------------------------------------点击保存时校验---------------------------------------
// 校验
const checkout = (isSave = true) => {
  if (itemCategoryName.value === '多功能电力参数测量仪') {
    if (!form.value.ipri) {
      ElMessage.warning('请输入电流转换系数Ipri')
      return false
    }
    if (!form.value.ipriUnit) {
      ElMessage.warning('请输入电流转换系数Ipri单位')
      return false
    }
    if (!form.value.isec) {
      ElMessage.warning('请输入电流转换系数Isec')
      return false
    }
    if (!form.value.isecUnit) {
      ElMessage.warning('请输入电流转换系数Isec单位')
      return false
    }
    if (!form.value.vpri) {
      ElMessage.warning('请输入电压转换系数Vpri')
      return false
    }
    if (!form.value.vpriUnit) {
      ElMessage.warning('请输入电压转换系数Vpri单位')
      return false
    }
    if (!form.value.vsec) {
      ElMessage.warning('请输入电压转换系数Vsec')
      return false
    }
    if (!form.value.vsecUnit) {
      ElMessage.warning('请输入电压转换系数Vsec单位')
      return false
    }
  }
  if (isSave) {
    if (!measureDataCalibratorList.value.length) {
      ElMessage.warning('所使用的标准,主要测量设备不能为空')
      return false
    }
    if (appearanceFunctionCheck.value && !form.value.appearanceFunctionCheck) {
      ElMessage.warning('外观及功能性检查 不能为空')
      return false
    }
  }

  if (!useCheckList(list.value, measureColumns.value, '检定数据')) {
    return false
  }
  return true
}
// -----------------------------------------生成结果处理----------------------------------------
const measureTableLoading = ref(false) // 表格loading
// 点击生成结果处理
const createResult = () => {
  if (!list.value.length) {
    ElMessage.warning('没有检定项数据,无法生成结果')
    return false
  }
  if (!checkout(false)) { return false }
  let tempList = []
  if (form.value.itemCategoryName === '多功能电力参数测量仪') {
    tempList = list.value.map((item) => {
      return {
        ...item,
        ipri: form.value.ipri, // 电流转换系数
        ipriUnit: form.value.ipriUnit, // 电流转换系数单位
        isec: form.value.isec, // 电流转换系数
        isecUnit: form.value.isecUnit, // 电流转换系数单位
        vpri: form.value.vpri, // 电压转换系数
        vpriUnit: form.value.vpriUnit, // 电压转换系数单位
        vsec: form.value.vsec, // 电压转换系数
        vsecUnit: form.value.vsecUnit, // 电压转换系数单位
      }
    })
  }
  else {
    tempList = list.value
  }
  const params = {
    belongStandardEquipment: form.value.belongStandardEquipment, // 检校标准装置
    itemCategoryName: form.value.itemCategoryName, // 检定项分类名称
    measureDataCalibratorList: tempList,
    measureItemConfigCalibrator: measureItemConfigCalibrator.value,
  }
  measureTableLoading.value = true
  calculateHandle(params).then((res) => {
    if (res.data && res.data.length) {
      list.value = res.data.map((item: IDetailMeasureList, index: number) => {
        return {
          ...item,
          resolution: Number(item.resolution),
          maximumError: itemCategoryName.value === '指针式万用表' ? useMaximumError(inputList.value[index].accuracyA!, inputList.value[index].fullScaleValue!) + inputList.value[index].fullScaleValueUnit! : Number(item.maximumError).toFixed(item.resolutionDigit),
        }
      }) // 检定数据
    }
    else {
      list.value = res.data
    }
    measureTableLoading.value = false
  }).catch(() => {
    measureTableLoading.value = false
  })
}

// -------------------------------------示值focus事件------------------------------------------
// 第一次点击示值,把标准值默认赋值给示值
const indicatingValueFocus = (row: IDetailMeasureList) => {
  if (itemCategoryName.value === '数字多用表(手持)' || itemCategoryName.value === '钳形电流表' || itemCategoryName.value === '数字多用表(台式)') {
    if (!row.indicatingValue) {
      row.indicatingValue = row.standardValue
    }
  }
}

// -------------------------------------地点变化事件--------------------------------------------
const handleChangeAddress = (id: string) => {
  if (id) {
    const index = positionList.value.findIndex((item: { id: string }) => item.id === id)
    if (index !== -1) {
      form.value.temperature = positionList.value[index].temperature
      form.value.humidity = positionList.value[index].humidity
    }
  }
}

// ------------------------------------------钩子----------------------------------------------
watch(() => itemCategoryName.value, (newValue) => {
  if (newValue) {
    switch (newValue) {
      case '数字多用表(手持)':
        measureColumns.value = columns_digitalMultimeterHandheld.value
        break
      case '数字多用表(台式)':
        measureColumns.value = columns_digitalMultimeterTable.value
        break
      case '多功能电力参数测量仪':
        measureColumns.value = columns_multifunctionalPowerParameterMeasuringInstrument.value
        break
      case '钳形电流表':
        measureColumns.value = columns_digitalMultimeterHandheld.value
        break
      case '指针式万用表':
        measureColumns.value = columns_digitalMultimeterHandheld.value
        break
      default: // 交流电压表、交流电流表、直流电压表、直流电流表、75mV电流表
        measureColumns.value = columns_lastFive.value
        break
    }
  }
}, { immediate: true })
watch(() => props.infoId, (newValue) => {
  if (newValue) {
    infoId.value = newValue
    if (pageType.value === 'detail' && form.value.belongStandardEquipment) {
      fetchInfo()
    }
  }
}, { immediate: true })
watch(() => props.dataNo, (newValue) => {
  if (newValue) {
    form.value.dataNo = newValue
  }
}, { immediate: true })

// 监听列表合并列
// watch(() => list.value, (newValue) => {
// if (Array.isArray(newValue)) {
//   list.value = list.value.map((item) => {
//     return {
//       ...item,
//       resolution: Number(item.resolution),
//       // redStar: Math.abs(Number(item.absoluteError)) <= Math.abs(Number(getDataNum(item.maximumError))) ? 'normal' : 'error',
//     }
//   })
// }

// if (pageType.value === 'detail') {
//   if (itemCategoryName.value === '数字多用表(手持)' || itemCategoryName.value === '钳形电流表' || itemCategoryName.value === '指针式万用表') {
//     useMergeTableRow(list.value, ['params', 'capacity', 'unit', 'frequency', 'frequencyUnit', 'rangeRange', 'standardValue', 'resolution'])
//   }
// }
// }, { deep: true })

onMounted(async () => {
  console.log(pageType.value, 'pageType')
  console.log(infoId.value, 'infoId.value')
  getDict().then(() => {
    if (pageType.value === 'add') { // 从我的任务跳转过来(新增)
      form.value.orderId = $route.query.orderId as string // 任务单id
      form.value.orderNo = $route.query.orderNo as string // 任务单编号
      form.value.customerName = $route.query.customerName as string // 委托单位
      form.value.traceDate = dayjs().format('YYYY-MM-DD') // 测试校准检定日期默认今天
      form.value.measureValidDate = `${dayjs().add(Number($route.query.checkCycle), 'month').subtract(1, 'day')}` // 检定有效期--今天 + 检定周期 - 1天
      form.value.measureValidDate = dayjs(form.value.measureValidDate).format('YYYY-MM-DD')
      form.value.createUserName = user.name // 检定员
      form.value.itemId = $route.query.itemId as string// 检定项id
      form.value.itemCategoryName = $route.query.itemCategoryName as string// 设备检定项分类名称
      form.value.itemCategoryId = $route.query.itemCategoryId as string// 设备检定项分类名称id
      form.value.belongStandardEquipment = $route.query.belongStandardEquipment as string// 标准装置code
      form.value.belongStandardEquipmentName = $route.query.belongStandardEquipmentName as string// 标准装置名称
      sampleList.value = [{ // 被检设备
        sampleId: $route.query.sampleId, // 设备id
        sampleName: $route.query.sampleName, // 设备名称
        sampleModel: $route.query.sampleModel, // 规格型号
        manufactureNo: $route.query.manufactureNo, // 出厂编号
        manufacturer: $route.query.manufacturer, // 制造厂家(生产厂家)
        categoryName: $route.query.itemCategoryName, // 设备检定项分类
      }]
      itemCategoryName.value = $route.query.itemCategoryName as string // 设备检定项分类名称
      // 查依据的技术文件(编号、名称)
      fetchClassificationData(false, $route.query.itemCategoryName! as string, $route.query.belongStandardEquipment as string)
      // 查输入值(查检定项管理的详情)
      fetchItemInfo($route.query.itemId! as string, $route.query.itemCategoryName! as string, $route.query.belongStandardEquipment as string)
    }
    else {
      form.value.itemCategoryName = $route.query.itemCategoryName as string // 设备检定项分类名称
      form.value.itemCategoryId = $route.query.itemCategoryId as string// 设备检定项分类名称id
      form.value.belongStandardEquipment = $route.query.belongStandardEquipment as string// 标准装置code
      form.value.belongStandardEquipmentName = $route.query.belongStandardEquipmentName as string// 标准装置名称
      // 查输入值(查检定项管理的详情)
      // fetchItemInfo($route.query.itemId! as string, $route.query.itemCategoryName! as string, $route.query.belongStandardEquipment as string, 'notNeedList').then((res) => {
      //   // fetchInfo()
      // })
      fetchItemInfo($route.query.itemId! as string, $route.query.itemCategoryName! as string, $route.query.belongStandardEquipment as string, 'notNeedList').then(() => {
        fetchInfo()
      })
    }
  })
})

defineExpose({ checkout, form, list, measureDataCalibratorList, ruleFormRef, sampleList, pageType })
</script>

<template>
  <!-- 表单  -->
  <detail-block title="">
    <el-form
      ref="ruleFormRef"
      :model="form"
      label-width="180"
      label-position="right"
      :rules="rules"
    >
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="检定数据编号:" prop="dataNo">
            <el-input v-model="form.dataNo" disabled placeholder="系统自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检校类别:" prop="measureCategory">
            <el-select
              v-model="form.measureCategory"
              placeholder="检校类别"
              filterable
              :disabled="pageType === 'detail'"
              class="full-width-input"
            >
              <el-option v-for="item in measureCategoryList" :key="item.id" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="委托单位:" prop="customerName">
            <el-input v-model="form.customerName" disabled :placeholder="pageType === 'detail' ? ' ' : '系统自动生成'" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="测试、校准或检定日期:" prop="traceDate">
            <el-date-picker
              v-model="form.traceDate"
              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="8">
          <el-form-item label="检定有效期:" prop="measureValidDate">
            <el-date-picker
              v-model="form.measureValidDate"
              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="8">
          <el-form-item label="测试、校准或检定地点:" prop="measureAddress">
            <el-select
              v-model="form.measureAddress"
              placeholder="测试、校准或检定地点"
              filterable
              :disabled="pageType === 'detail'"
              class="full-width-input"
              @change="handleChangeAddress"
            >
              <el-option v-for="item in positionList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="温度(℃):" prop="temperature">
            <el-input v-model="form.temperature" :disabled="pageType === 'detail'" :placeholder="pageType === 'detail' ? ' ' : '请输入温度'" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="相对湿度(%):" prop="humidity">
            <el-input v-model="form.humidity" :disabled="pageType === 'detail'" :placeholder="pageType === 'detail' ? ' ' : '请输入相对湿度'" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="任务单编号:" prop="orderNo">
            <el-input v-model="form.orderNo" disabled placeholder="任务单编号" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="检定员:" prop="dacreateUserNametaNo">
            <el-input v-model="form.createUserName" disabled placeholder="检定员" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="数据来源:" prop="dataSource">
            <el-input v-model="form.dataSource" disabled placeholder="数据来源" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="结论:" prop="conclusion">
            <el-select
              v-model="form.conclusion"
              placeholder="请选择结论"
              filterable
              :disabled="pageType === 'detail'"
              class="full-width-input"
            >
              <el-option v-for="item in conclusionList" :key="item.id" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="form.conclusion === '除*外其余所检项目合格'" :span="16">
          <el-form-item label="限用说明:" prop="restrictionInstruction">
            <el-input v-model="form.restrictionInstruction" type="textarea" autosize :disabled="pageType === 'detail'" placeholder="请输入限用说明" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" class="marg">
        <el-col :span="24">
          <el-form-item label="依据的技术文件:" prop="technologyFile">
            <div v-for="(item, index) in form.technologyFile" :key="index" style="display: flex;">
              <show-photo :minio-file-name="item" />
            </div>
            <span v-if="pageType === 'detail' && !form.technologyFile">无</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </detail-block>
  <!-- 被检件信息 -->
  <detail-block title="被检件信息">
    <el-table
      :data="sampleList"
      border
      style="width: 100%;"
    >
      <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"
        align="center"
      />
    </el-table>
  </detail-block>

  <detail-block title="所使用的标准,主要测量设备">
    <template v-if="pageType !== 'detail'" #btns>
      <el-button type="primary" @click="multiFilesAdd">
        批量添加
      </el-button>
      <el-button type="info" @click="delRow">
        删除行
      </el-button>
    </template>
    <el-table
      v-loading="tableLoading"
      :data="measureDataCalibratorList"
      border
      style="width: 100%;"
      @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 measureDataCalibratorColumns"
        :key="item.value"
        :prop="item.value"
        :label="item.text"
        :width="item.width"
        align="center"
      />
    </el-table>
  </detail-block>
  <!-- 标签 -->
  <detail-block :title="pageType !== 'detail' ? '检定数据' : ''" :class="pageType === 'detail' ? 'setBottom' : ''">
    <el-radio-group v-if="pageType === 'detail'" v-model="current">
      <el-radio-button v-for="item in radioMenus" :key="item.value" :label="item.value">
        {{ item.name }}
      </el-radio-button>
    </el-radio-group>

    <el-form
      v-if="current === 'measure-data'"
      ref="formRef"
      :model="form"
      label-width="150"
      label-position="right"
      :rules="rules"
      style="margin-top: 20px;"
    >
      <el-row v-if="`${appearanceFunctionCheck}` !== '0'">
        <el-col :span="12">
          <el-form-item label="外观及功能性检查:" prop="appearanceFunctionCheck">
            <el-input
              v-model="form.appearanceFunctionCheck"
              class="full-width-input"
              autosize
              type="textarea"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 多功能电力参数测量仪  -->
      <el-row v-if="itemCategoryName === '多功能电力参数测量仪'" :gutter="24">
        <el-col :span="12" style="display: flex;justify-content: flex-start;">
          <el-form-item label="电流转换系数:" prop="ipri">
            <el-input
              v-model="form.ipri"
              placeholder="Ipri"
              :disabled="pageType === 'detail'"
              style="flex: 1;"
            />
          </el-form-item>
          <el-form-item label-width="10" prop="ipriUnit">
            <!-- 单位 -->
            <el-select
              v-model="form.ipriUnit"
              placeholder="单位"
              :disabled="pageType === 'detail'"
              filterable
              style="width: 100px;"
            >
              <el-option v-for="item in IUnitList" :key="item.id" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
          <span style="margin-left: 10px;">/</span>
          <el-form-item label="" label-width="10" prop="isec">
            <el-input
              v-model="form.isec"
              placeholder="Isec"
              :disabled="pageType === 'detail'"
              style="flex: 1;"
            />
          </el-form-item>
          <el-form-item label-width="10" prop="isecUnit">
            <!-- 单位 -->
            <el-select
              v-model="form.isecUnit"
              placeholder="单位"
              :disabled="pageType === 'detail'"
              filterable
              style="width: 100px;"
            >
              <el-option v-for="item in IUnitList" :key="item.id" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" style="display: flex;justify-content: flex-start;">
          <el-form-item label="电压转换系数:" prop="vpri">
            <el-input
              v-model="form.vpri"
              placeholder="Vpri"
              :disabled="pageType === 'detail'"
              style="flex: 1;"
            />
          </el-form-item>
          <el-form-item label-width="10" prop="vpriUnit">
            <!-- 单位 -->
            <el-select
              v-model="form.vpriUnit"
              placeholder="单位"
              :disabled="pageType === 'detail'"
              filterable
              style="width: 100px;"
            >
              <el-option v-for="item in UUnitList" :key="item.id" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
          <span style="margin-left: 10px;">/</span>
          <el-form-item label="" label-width="10" prop="vsec">
            <el-input
              v-model="form.vsec"
              placeholder="Vsec"
              :disabled="pageType === 'detail'"
              style="flex: 1;"
            />
          </el-form-item>
          <el-form-item label-width="10" prop="vsecUnit">
            <!-- 单位 -->
            <el-select
              v-model="form.vsecUnit"
              placeholder="单位"
              :disabled="pageType === 'detail'"
              filterable
              style="width: 100px;"
            >
              <el-option v-for="item in UUnitList" :key="item.id" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <div style="display: flex;justify-content: space-between;">
        <div style="font-size: 14px;color: #606266;padding: 0 20px 20px;">
          示值误差:
        </div>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="createResult">
          生成结果处理
        </el-button>
      </div>

      <!-- 交流电压表、交流电流表、直流电压表、直流电流表、75mV电流表 -->
      <div v-if="itemCategoryName === '交流电压表' || itemCategoryName === '交流电流表' || itemCategoryName === '直流电压表' || itemCategoryName === '直流电流表' || itemCategoryName === '75mV电流表'" style="font-size: 14px;color: #606266;padding: 0 80px 20px;">
        <span>转换系数:<span style="font-weight: 600;">{{ measureItemConfigCalibrator.fullScaleValue }}({{ measureItemConfigCalibrator.fullScaleValueUnit }}) / {{ measureItemConfigCalibrator.standardValueUpper }}({{ measureItemConfigCalibrator.standardValueUpperUnit }})</span></span>
        <span style="display: inline-block; margin-left: 20px;">准确度等级:<span style="display: inline-block; font-weight: 600;margin-left: 10px;">{{ measureItemConfigCalibrator.accuracyLevel }}</span> </span>
      </div>
    </el-form>
    <!-- 检定数据表格 -->
    <el-table
      v-show="current === 'measure-data'"
      ref="tableRef"
      v-loading="measureTableLoading"
      :data="list"
      border
      style="width: 100%;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" label="序号" width="80" type="index" />
      <el-table-column
        v-for="item in measureColumns"
        :key="item.value"
        :prop="item.value"
        :label="item.text"
        :width="item.width"
        align="center"
      >
        <template #header>
          <span v-show="item.required" style="color: red;">*</span><span>{{ item.text }}</span>
        </template>
        <template #default="scope">
          <!-- 频率,频率单位 -->
          <span
            v-if="(item.value === 'frequency' && (scope.row.params !== 'ACV' && scope.row.params !== 'ACI'))
              || (item.value === 'frequencyUnit' && (scope.row.params !== 'ACV' && scope.row.params !== 'ACI'))
            "
          >/</span>
          <!-- 两线/四线模式 -->
          <!-- <el-select
            v-if="pageType !== 'detail' && item.value === 'lineMode' && scope.row.params === 'R'"
            v-model="scope.row[item.value]"
            placeholder="请选择"
            filterable
          >
            <el-option v-for="item in lineModeList" :key="item.id" :label="item.name" :value="item.value" />
          </el-select> -->
          <!-- 示值  -->
          <el-input v-if="(itemCategoryName !== '指针式万用表' && itemCategoryName !== '交流电压表' && itemCategoryName !== '交流电流表' && itemCategoryName !== '直流电压表' && itemCategoryName !== '直流电流表' && itemCategoryName !== '75mV电流表') && pageType !== 'detail' && item.value === 'indicatingValue'" v-model="scope.row[item.value]" :placeholder="`${item.text}`" class="input" @focus="indicatingValueFocus(scope.row)" />
          <!-- 标准值  -->
          <el-input v-if="(itemCategoryName === '指针式万用表' || itemCategoryName === '交流电压表' || itemCategoryName === '交流电流表' || itemCategoryName === '直流电压表' || itemCategoryName === '直流电流表' || itemCategoryName === '75mV电流表') && pageType !== 'detail' && item.value === 'standardValue'" v-model="scope.row[item.value]" :placeholder="`${item.text}`" class="input" />
          <!-- 输出备注 -->
          <el-input v-if="pageType !== 'detail' && item.value === 'remark'" v-model="scope.row[item.value]" type="textarea" autosize :placeholder="`${item.text}`" class="input" />
          <!-- AN、BN、CN -->
          <el-input-number
            v-if="pageType !== 'detail' && (item.value === 'an' || item.value === 'bn' || item.value === 'cn')"
            v-model="scope.row[item.value]"
            :placeholder="pageType === 'detail' ? '' : '请输入'"
            :disabled="pageType === 'detail'"
          />

          <!-- 绝对误差 -->
          <div v-if="item.value === 'absoluteError'">
            <span>{{ scope.row.absoluteError }}</span>
            <span v-if="scope.row.redStar === 'error' && `${scope.row.absoluteError}` !== ''" style="color: red;">*</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 历史修改记录 -->
    <change-record v-show="pageType === 'detail' && current === 'change-record'" :info-id="infoId" />
  </detail-block>

  <!-- 选择标准装置组件 -->
  <select-standard ref="selectStandardRef" :is-multi="true" @confirm="confirmSelectStandard" />
</template>

<style lang="scss" scoped>
.setBottom {
  padding-bottom: 20px;
}
</style>