<!-- 标准装置台账信息 基本信息 -->
<script name="StandardBookBasic" lang="ts" setup>
import type { Ref } from 'vue'
import { onMounted, ref } from 'vue'
import dayjs from 'dayjs'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { FormRules } from 'element-plus'
import type { IForm, ITechFiles } from '../book-interface'
import selectBuildStandardDialog from '../dialog/selectBuildStandardDialog.vue'
import selectTechFiles from '@/views/equipement/standard/book/dialog/selectTechFiles.vue'
import { getDictByCode } from '@/api/system/dict'
import useUserStore from '@/store/modules/user'
import type { deptType, dictType } from '@/global'
import { getDeptTreeList } from '@/api/system/dept'
import showPhoto from '@/components/showPhoto/index.vue'
import { UploadFile } from '@/api/file'
import { toTreeList } from '@/utils/structure'
import { SCHEDULE } from '@/utils/scheduleDict'
import { useCheckList } from '@/commonMethods/useCheckList'
import { useSetAllRowReadable } from '@/commonMethods/useSetAllRowReadable'
import { getStaffList } from '@/api/resource/register'
import { addStandard, failUpdateStandard, getInfo, submit, updateStandard } from '@/api/equipment/standard/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 infoId = ref('') // id
const form: Ref<IForm> = ref({ // 基本信息表单
  approvalType: '', // 审批类型
  createUserId: '', // 创建人id
  createUserName: '', // 创建人名称
  createTime: '', // 创建时间
  standardNo: '', // 标准代码
  standardName: '', // 标准装置名称
  storageLocation: '', // 存放地点code
  storageLocationName: '', // 存放地点名称
  major: '', // 所属专业code
  majorName: '', // 所属专业名称
  buildStandardName: '', // 建标申请名称
  buildStandardId: '', // 建标申请表id
  // buildStandardName: '', // 建标名称
  // buildStandardDate: '', // 建标日期
  standardCertNo: '', // 计量标准证书号
  lastReviewDate: '', // 最近复查日期
  deptId: '', // 标准所在部门id
  deptName: '', // 标准所在部门名称
  directorId: '', // 标准负责人id
  directorName: '', // 标准负责人id
  manageStatus: '', // 使用状态code
  manageStatusName: '', // 使用状态名称
  buildStandardReportFile: '', // 建标报告
  examTableFile: '', // 考核表
  standardCertFile: '', // 标准证书

  // temperature: '', // 温度(℃)
  // humidity: '', // 相对湿度
  // voltage: '', // 电源电压
  // powerFrequency: '', // 电源频率
  // surroundEnvironment: '', // 周围环境
  // electricField: '', // 电磁场

  // measureRange: '', // 测量范围
  // uncertainty: '', // 不确定度或允许误差极限或准确度等级
  // measureItem: '', // 检定或校准项目
})
const rules = reactive<FormRules>({ // 表单验证规则
  standardName: [{ required: true, message: '标准装置名称不能为空', trigger: ['blur', 'change'] }],
  storageLocation: [{ required: true, message: '存放地点不能为空', trigger: ['blur', 'change'] }],
  major: [{ required: true, message: '所属专业不能为空', trigger: ['blur', 'change'] }],
  // buildStandardId: [{ required: true, message: '建标申请不能为空', trigger: ['blur', 'change'] }],
  standardCertNo: [{ required: true, message: '计量标准证书号不能为空', trigger: ['blur', 'change'] }],
  lastReviewDate: [{ required: true, message: '最近复查日期不能为空', trigger: ['blur', 'change'] }],
  deptId: [{ required: true, message: '标准所在部门不能为空', trigger: ['blur', 'change'] }],
  directorId: [{ required: true, message: '标准负责人不能为空', trigger: ['blur', 'change'] }],
  manageStatus: [{ required: true, message: '使用状态不能为空', trigger: ['blur', 'change'] }],
})
const getInfoForm: Ref<{ [key: string]: string }> = ref({})
// ------------------------------------------字典----------------------------------------------
const storageLocationList = ref<dictType[]>([]) // 存放地点
const approvalTypeList = ref<dictType[]>([]) // 审批类型
const majorList = ref<dictType[]>([]) // 所属专业
const useDeptList = ref<deptType[]>([]) // 所属部门列表
const userList = ref<{ [key: string]: string }[]>([]) // 用户列表
const manageStatusList = ref<dictType[]>([]) // 使用状态
const approvalTypeMap = ref({}) as any // 审批类型{1: 新建}

/**
 * 获取字典
 */
function getDict() {
  // 存放地点
  getDictByCode('bizStorageLocation').then((response) => {
    storageLocationList.value = response.data
  })
  // 审批类型
  getDictByCode('approvalType').then((response) => {
    response.data.forEach((item: any) => {
      approvalTypeMap.value[`${item.value}`] = item.name
    })
    approvalTypeList.value = response.data
  })
  // 所属专业
  getDictByCode('bizMeasureMajor').then((response) => {
    majorList.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('bizStandardManagerState').then((response) => {
    manageStatusList.value = response.data
  })
}
// ------------------------------------------建标申请-------------------------------------------
const selectBuildStandardRef = ref() // 建标申请ref
// 点击选择建标申请
const selectBuildStandard = () => {
  selectBuildStandardRef.value.initDialog()
}
// 选择好建标申请
const confirmSelectBuildStandard = (val: any) => {
  form.value.buildStandardName = val[0].applyName // 建标申请名称
  form.value.buildStandardId = val[0].id // 建标申请id
}
// -------------------------------------------文件上传--------------------------------------
// 文件上传
const fileRefBuildStandardReport = ref() // 建标报告ref
const fileRefExamTableFile = ref() // 考核表ref
const fileRefStandardCertFile = ref() // 标准证书ref
/**
 * 建标报告上传文件，在 Input 值改变时触发
 * @param event 事件对象
 */
const onBuildStandardReportFileChange = (event: any) => {
  // 原生上传
  console.log(event.target.files)
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('multipartFile', event.target.files[0])
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    UploadFile(fd).then((res) => {
      if (res.code === 200) {
        form.value.buildStandardReportFile = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
//
const onExamTableFileChange = (event: any) => {
  // 原生上传
  console.log(event.target.files)
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('multipartFile', event.target.files[0])
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    UploadFile(fd).then((res) => {
      if (res.code === 200) {
        form.value.examTableFile = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
const onStandardCertFileChange = (event: any) => {
  // 原生上传
  console.log(event.target.files)
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('multipartFile', event.target.files[0])
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    UploadFile(fd).then((res) => {
      if (res.code === 200) {
        form.value.standardCertFile = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
const upload = (fileRef: any) => {
  fileRef.click()
}
// -----------------------------------------依据的技术文件------------------------------
const checkoutFilesList = ref<ITechFiles[]>([]) // 技术文件多选
const technologyRelationList = ref<ITechFiles[]>([]) // 所依据的技术文件
const selectFliesIndex = ref() // 技术文件表格-点击选择的index---点击第几行
const techFileRef = ref() // 所依据的技术文件组件ref
// 所依据的技术文件表头
const techFilesColumns = [
  { text: '文件编号', value: 'technologyFileNo', required: true, align: 'center', width: '240' },
  { text: '文件名称', value: 'technologyFileName', required: true, align: 'center' },
  { text: '备注', value: 'remark', align: 'center' },
]

// 点击技术文件增加行
const addFilesRow = () => {
  const index = technologyRelationList.value.findIndex((item: ITechFiles) => !item.technologyFileNo)
  if (index !== -1) {
    ElMessage.warning('请完善上一条文件信息')
    return
  }
  technologyRelationList.value.push({
    remark: '', //	备注
    standardNo: '', //	标准代码
    technologyFileId: '', //	依据的技术文件id
    technologyFileName: '', //	依据的技术文件名称
  })
}

// 技术文件表格多选
const handleSelectionChangeFiles = (e: any) => {
  checkoutFilesList.value = e
}

// 点击技术文件删除行
const delFilesRow = () => {
  if (checkoutFilesList.value.length <= 0) {
    ElMessage({
      message: '请选中要删除的行',
      type: 'warning',
    })
  }
  else {
    checkoutFilesList.value.forEach((item: ITechFiles) => {
      technologyRelationList.value.forEach((element: ITechFiles, index: number) => {
        if (element.technologyFileId === item.technologyFileId) {
          technologyRelationList.value.splice(index, 1)
        }
      })
    })
  }
}

// 点击选择文件编号
const handleClickFiles = (index: number) => {
  selectFliesIndex.value = index
  techFileRef.value.initDialog()
}

// 选好文件
const confirmSelectTechFile = (val: any) => {
  console.log(val)

  if (val && val.length) {
    const index = technologyRelationList.value.findIndex((i: ITechFiles) => val[0].fileNo === i.technologyFileNo)
    if (index !== -1) {
      ElMessage.warning('此文件已添加过')
      return
    }
    const fileParam = {
      technologyFileNo: val[0].fileNo, // 文件编号
      technologyFileName: val[0].fileName, // 文件名称
      remark: val[0].remark, // 备注
      technologyFileId: val[0].id, // id
    }
    technologyRelationList.value.splice(selectFliesIndex.value, 1, fileParam)
  }
}
// ------------------------------------------环境条件----------------------------------------
const environmentalConditionsColumns = [ // 环境条件表头
  { text: '温度(℃)', value: 'temperature', align: 'center' },
  { text: '相对湿度(%)', value: 'humidity', align: 'center' },
  { text: '电源电压(v)', value: 'voltage', align: 'center' },
  { text: '电源频率(Hz)', value: 'powerFrequency', align: 'center' },
  { text: '周围环境', value: 'surroundEnvironment', align: 'center', required: true },
  { text: '电磁场', value: 'electricField', align: 'center', required: true },
]
const environmentalConditionsList = ref([{
  temperature: '', // 温度(℃)
  humidity: '', // 相对湿度
  voltage: '', // 电源电压
  powerFrequency: '', // 电源频率
  surroundEnvironment: '', // 周围环境
  electricField: '', // 电磁场
  editable: true, // 是否可编辑
}])
// -------------------------------------------技术指标----------------------------------------
const technicalIndexColumns = [ // 环境条件表头
  { text: '测量范围', value: 'measureRange', align: 'center', required: true },
  { text: '不确定度或允许误差极限或准确度等级', value: 'uncertainty', align: 'center', required: true },
  { text: '检定或校准项目', value: 'measureItem', align: 'center', required: true },
]
const technicalIndexList = ref([{
  measureRange: '', // 测量范围
  uncertainty: '', // 不确定度或允许误差极限或准确度等级
  measureItem: '', // 检定或校准项目
  editable: true, // 是否可编辑
}])
// -------------------------------------------获取详情信息----------------------------------------
/**
 * 获取详情
 * @param isCopy 是否备份，判断基本信息是否变化
 */
function fetchInfo(isCopy = false) {
  getInfo({ id: infoId.value!, type: window.sessionStorage.getItem('infoParamType')! }).then((res) => {
    form.value = res.data.standardInfoApproval // 表单数据
    technologyRelationList.value = res.data.technologyRelationList // 技术文件
    environmentalConditionsList.value = [{ // 环境数据
      temperature: res.data.standardInfoApproval.temperature, // 温度(℃)
      humidity: res.data.standardInfoApproval.humidity, // 相对湿度
      voltage: res.data.standardInfoApproval.voltage, // 电源电压
      powerFrequency: res.data.standardInfoApproval.powerFrequency, // 电源频率
      surroundEnvironment: res.data.standardInfoApproval.surroundEnvironment, // 周围环境
      electricField: res.data.standardInfoApproval.electricField, // 电磁场
      editable: props.pageType !== 'detail', // 是否可编辑
    }]
    technicalIndexList.value = [{ // 技术指标数据
      measureRange: res.data.standardInfoApproval.measureRange, // 测量范围
      uncertainty: res.data.standardInfoApproval.uncertainty, // 不确定度或允许误差极限或准确度等级
      measureItem: res.data.standardInfoApproval.measureItem, // 检定或校准项目
      editable: props.pageType !== 'detail', // 是否可编辑
    }]
    form.value.approvalType = `${res.data.standardInfoApproval.approvalType}` // 审批类型
    const tempGetInfoForm = window.sessionStorage.getItem('standardGetInfoForm') ? JSON.parse(window.sessionStorage.getItem('standardGetInfoForm')!) : window.sessionStorage.getItem('standardGetInfoForm')
    if (isCopy && !tempGetInfoForm.standardName) {
      getInfoForm.value = {
        standardName: res.data.standardInfoApproval.standardName, // 标准装置名称
        storageLocation: res.data.standardInfoApproval.storageLocation, // 存放地点code
        storageLocationName: res.data.standardInfoApproval.storageLocationName, // 存放地点名称
        major: res.data.standardInfoApproval.major, // 所属专业code
        majorName: res.data.standardInfoApproval.majorName, // 所属专业名称
        buildStandardId: res.data.standardInfoApproval.buildStandardId, // 建标申请表id
        // buildStandardName: res.data.standardInfoApproval.buildStandardName, // 建标名称
        // buildStandardDate: res.data.standardInfoApproval.buildStandardDate, // 建标日期
        standardCertNo: res.data.standardInfoApproval.standardCertNo, // 计量标准证书号
        lastReviewDate: res.data.standardInfoApproval.lastReviewDate, // 最近复查日期
        deptId: res.data.standardInfoApproval.deptId, // 标准所在部门id
        deptName: res.data.standardInfoApproval.deptName, // 标准所在部门名称
        directorId: res.data.standardInfoApproval.directorId, // 标准负责人id
        directorName: res.data.standardInfoApproval.directorName, // 标准负责人id
        manageStatus: res.data.standardInfoApproval.manageStatus, // 使用状态code
        manageStatusName: res.data.standardInfoApproval.manageStatusName, // 使用状态名称
        buildStandardReportFile: res.data.standardInfoApproval.buildStandardReportFile, // 建标报告
        examTableFile: res.data.standardInfoApproval.examTableFile, // 考核表
        standardCertFile: res.data.standardInfoApproval.standardCertFile, // 标准证书
        temperature: res.data.standardInfoApproval.temperature, // 温度(℃)
        humidity: res.data.standardInfoApproval.humidity, // 相对湿度
        voltage: res.data.standardInfoApproval.voltage, // 电源电压
        powerFrequency: res.data.standardInfoApproval.powerFrequency, // 电源频率
        surroundEnvironment: res.data.standardInfoApproval.surroundEnvironment, // 周围环境
        electricField: res.data.standardInfoApproval.electricField, // 电磁场
        measureRange: res.data.standardInfoApproval.measureRange, // 测量范围
        uncertainty: res.data.standardInfoApproval.uncertainty, // 不确定度或允许误差极限或准确度等级
        measureItem: res.data.standardInfoApproval.measureItem, // 检定或校准项目
      } // 保存用于比较修改需要审批的字段
      window.sessionStorage.setItem('standardGetInfoForm', JSON.stringify(getInfoForm.value))
    }
  })
}
// ---------------------------------------检查基本信息变化-------------------------------------

/**
 * 检查信息是否有变化
 * @param tempObject 要检查的对象
 */
const checkBasicInfo = (tempObject: any) => {
  const tempGetInfoForm = JSON.parse(window.sessionStorage.getItem('standardGetInfoForm')!)
  // 检查基本信息有没有变化
  for (const key in tempGetInfoForm) {
    console.log(key, tempGetInfoForm[key])
    console.log(key, tempObject[key])
    console.log(tempGetInfoForm[key] == tempObject[key])

    if (tempGetInfoForm[key] != tempObject[key]) {
      return true // 有变化
    }
  }
  return false // 没变化
}
// ----------------------------------------------- 保存---------------------------------------
const ruleFormRef = ref() // 基本信息表单ref
/**
 * 点击保存
 * @param ruleFormRef 基本信息表单ref
 */
function saveForm() {
  if (!useCheckList(technologyRelationList.value, techFilesColumns, '依据的技术文件')) {
    return false
  }
  if (!technologyRelationList.value.length) {
    ElMessage.warning('依据的技术文件不能为空')
    return false
  }

  if (!useCheckList(environmentalConditionsList.value, environmentalConditionsColumns, '环境条件')) {
    return false
  }

  if (!useCheckList(technicalIndexList.value, technicalIndexColumns, '技术指标')) {
    return false
  }
  ruleFormRef.value.validate((valid: boolean) => {
    if (valid) { // 基本信息表单通过校验
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        console.log('pppppp')
        console.log(environmentalConditionsList.value)
        console.log(technicalIndexList.value)

        const params = { // 请求参数
          technologyRelationList: technologyRelationList.value.map((item) => {
            return {
              ...item,
              standardNo: form.value.standardNo, // 标准代码
            }
          }), // 依据的技术文件
          standardInfoApproval: { // 表单、环境、指标
            ...form.value,
            ...environmentalConditionsList.value[0], // 环境
            ...technicalIndexList.value[0], // 技术指标
            id: form.value.id,
          },
        }
        const loading = ElLoading.service({
          lock: true,
          text: '加载中...',
          background: 'rgba(255, 255, 255, 0.6)',
        })
        if (props.pageType === 'add') { // 新建
          addStandard(params).then((res) => {
            loading.close()
            form.value.standardNo = res.data.standardNo // 设备编号
            infoId.value = res.data.id // id
            emits('addSuccess', form.value.standardNo, infoId.value, form.value.standardName)
            ElMessage.success('已保存')
          }).catch(() => {
            loading.close()
          })
        }
        else if (props.pageType === 'edit') { // 编辑
          switch (props.approvalStatusName) {
            case '草稿箱':
              updateStandard(params).then((res) => {
                loading.close()
                ElMessage.success('已保存')
                emits('saveSuccess')
                window.sessionStorage.setItem('infoParamType', '0')
                useSetAllRowReadable(technologyRelationList.value) // 技术指标进入不可编辑状态
              }).catch(() => {
                loading.close()
              })
              break
            case '全部': // 全部的编辑-保存相当于新建一个草稿
              params.standardInfoApproval.id = '' // 新建一个草稿，所以id需要置空
              params.standardInfoApproval.approvalType = '2' // 审批类型
              addStandard(params).then((res) => {
                loading.close()
                form.value.standardNo = res.data.standardNo // 设备编号
                infoId.value = res.data.id // id
                emits('addSuccess', form.value.standardNo, infoId.value, form.value.standardName)
                window.sessionStorage.setItem('infoParamType', '0') // 全部编辑相当于新建一个草稿，所以去查草稿箱的详情传0
                ElMessage.success('已保存')
              }).catch(() => {
                loading.close()
              })
              break
            default: // '未通过' || '已取消'
              failUpdateStandard(params).then((res) => {
                loading.close()
                ElMessage.success('已保存')
                emits('submitSuccess', form.value.standardNo, infoId.value, form.value.standardName)
                window.sessionStorage.setItem('infoParamType', '0')
                fetchInfo() // 获取详情信息
                useSetAllRowReadable(technologyRelationList.value) // 技术指标进入不可编辑状态
              }).catch(() => {
                loading.close()
              })
              break
          }
        }
      })
    }
  })
}

// ----------------------------------------------提交--------------------------------------------

const submitForm = (processId = '') => {
  if (infoId.value) {
    // 未通过编辑、已取消编辑、新建正常走审批流程
    if (props.approvalStatusName === '未通过' || props.approvalStatusName === '已取消' || form.value.approvalType === '1') {
      // 未通过、已取消直接进流程，所以不需要查看基本信息有没有变化
      handleSubmit(processId, '')
    }
    if (props.approvalStatusName === '全部' || props.approvalStatusName === '草稿箱') {
      // 检查基本信息有没有变化--除了依据技术文件剩下的变化就走审批
      const tempObject = {
        ...form.value,
        ...environmentalConditionsList.value[0],
        ...technicalIndexList.value[0],
      }
      if (!checkBasicInfo(tempObject)) {
        console.log('信息没变化')
        // 信息没变化
        handleSubmit(processId, '2', '1')
        window.sessionStorage.setItem('infoParamType', '1')
      }
      else { // 信息有变化
        handleSubmit(processId, '2', '0') // 信息有变化正常走审批流程
      }
    }
  }
  else {
    ElMessage.warning('请先保存')
  }
}
// 提交
/**
 *
 * @param processId 流程实例id
 * @param approvalType // 审批类型 1新建、2编辑、3删除
 * @param changeFlag // 基本信息是否变化 1、信息没变化、0信息有变化
 */
function handleSubmit(processId: string, approvalType: string, changeFlag?: string) {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(255, 255, 255, 0.6)',
  })
  submit({ id: infoId.value!, formId: SCHEDULE.STANDARD_BOOK_APPROVAL, processId, approvalType, changeFlag }).then((res) => {
    if (props.approvalStatusName === '草稿箱' && changeFlag === '1') { // 全部且信息无变化
      infoId.value = res.data.id // id
      ElMessage.success('无基本信息变更，无需审批，更新成功')
    }
    else {
      ElMessage.success('已提交')
    }
    emits('submitSuccess', form.value.standardNo, infoId.value, form.value.standardName)
    fetchInfo(false) // 获取详细信息
    loading.close()
  })
}
// -------------------------------------------钩子------------------------------------------------
// 监听pageType处理审批类型
watch(() => props.pageType, (newValue) => {
  console.log('监听页面类型', newValue)
  form.value.approvalType = newValue === 'add' ? '1' : newValue === 'edit' ? '2' : ''
  console.log(form.value.approvalType, ';;')
}, { immediate: true })

// 监听pageType处理审批类型
watch(() => props.approvalStatusName, (newValue) => {
  console.log('approvalStatusName', newValue)
  if (newValue) {
    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) {
    console.log('watchID', props.approvalStatusName)

    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') {
    if (window.sessionStorage.getItem('standardGetInfoForm')) {
      fetchInfo(false) // 获取详情信息
    }
    else {
      fetchInfo(true) // 获取详情信息
    }
  }
})

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

<template>
  <detail-block title="">
    <el-form
      ref="ruleFormRef"
      :model="form"
      :label-width="130"
      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="form.approvalType"
              filterable
              :placeholder="pageType === 'detail' ? ' ' : '请选择审批类型'"
              disabled
              class="full-width-input"
            >
              <el-option v-for="item of approvalTypeList" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="创建人:">
            <el-input v-model="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="standardNo">
            <el-input
              v-model="form.standardNo"
              :disabled="pageType === 'detail'"
              :placeholder="pageType === 'detail' ? '' : '请输入标准代码'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标准装置名称:" prop="standardName">
            <el-input
              v-model.trim="form.standardName"
              :placeholder="pageType === 'detail' ? '' : '请输入标准装置名称'"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="存放地点:" prop="storageLocation">
            <el-select
              v-model="form.storageLocation"
              filterable
              :placeholder="pageType === 'detail' ? ' ' : '请选择存放地点'"
              :disabled="pageType === 'detail'"
              class="full-width-input"
            >
              <el-option v-for="item of storageLocationList" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属专业:" prop="major">
            <el-select
              v-model="form.major"
              filterable
              :placeholder="pageType === 'detail' ? ' ' : '请选择所属专业'"
              :disabled="pageType === 'detail'"
              class="full-width-input"
            >
              <el-option v-for="item of majorList" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="建标申请:" prop="buildStandardName">
            <el-input
              v-model.trim="form.buildStandardName"
              :placeholder="pageType === 'detail' ? ' ' : '请选择建标申请'"
              disabled
              class="full-width-input"
              clearable
            >
              <template v-if="pageType !== 'detail'" #append>
                <el-button
                  size="small"
                  @click="selectBuildStandard"
                >
                  选择
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="6">
          <el-form-item label="建标名称:" prop="buildStandardName">
            <el-input v-model="form.buildStandardName" disabled :placeholder="pageType === 'detail' ? ' ' : '建标申请'" />
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="6">
          <el-form-item label="建标日期:" prop="buildStandardDate">
            <el-date-picker
              v-model="form.buildStandardDate"
              :placeholder="pageType === 'detail' ? ' ' : '建标日期'"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              class="full-width-input"
              disabled
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="6">
          <el-form-item label="计量标准证书号:" prop="standardCertNo">
            <el-input
              v-model.trim="form.standardCertNo"
              :placeholder="pageType === 'detail' ? '' : '请输入计量标准证书号'"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="最近复查日期:" prop="lastReviewDate">
            <el-date-picker
              v-model="form.lastReviewDate"
              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="deptId">
            <dept-select v-model="form.deptId" :disabled="pageType === 'detail'" :data="useDeptList" :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="manageStatus">
            <el-select
              v-model.trim="form.manageStatus"
              clearable
              :placeholder="pageType === 'detail' ? '' : '请选择使用状态'"
              size="default"
              :disabled="pageType === 'detail'"
              class="full-width-input"
            >
              <el-option
                v-for="item in manageStatusList"
                :key="item.id"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" class="marg">
        <el-col :span="24">
          <el-form-item label="建标报告:">
            <show-photo v-if="form.buildStandardReportFile" :minio-file-name="form.buildStandardReportFile" />
            <span v-else-if="pageType === 'detail'">无</span>
            <input v-show="pageType === ''" ref="fileRefBuildStandardReport" type="file" @change="onBuildStandardReportFileChange">
            <el-button v-if="pageType !== 'detail'" id="file" type="primary" :disabled="pageType === 'detail'" :style="{ 'margin-left': form.buildStandardReportFile === '' ? '0px' : '20px' }" @click="upload(fileRefBuildStandardReport)">
              {{ form.buildStandardReportFile === '' ? '上传' : '更换附件' }}
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" class="marg">
        <el-col :span="24">
          <el-form-item label="考核表:">
            <show-photo v-if="form.examTableFile" :minio-file-name="form.examTableFile" />
            <span v-else-if="pageType === 'detail'">无</span>
            <input v-show="pageType === ''" ref="fileRefExamTableFile" type="file" @change="onExamTableFileChange">
            <el-button v-if="pageType !== 'detail'" id="file" type="primary" :disabled="pageType === 'detail'" :style="{ 'margin-left': form.examTableFile === '' ? '0px' : '20px' }" @click="upload(fileRefExamTableFile)">
              {{ form.examTableFile === '' ? '上传' : '更换附件' }}
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" class="marg">
        <el-col :span="24">
          <el-form-item label="标准证书:">
            <show-photo v-if="form.standardCertFile" :minio-file-name="form.standardCertFile" />
            <span v-else-if="pageType === 'detail'">无</span>
            <input v-show="pageType === ''" ref="fileRefStandardCertFile" type="file" @change="onStandardCertFileChange">
            <el-button v-if="pageType !== 'detail'" id="file" type="primary" :disabled="pageType === 'detail'" :style="{ 'margin-left': form.standardCertFile === '' ? '0px' : '20px' }" @click="upload(fileRefStandardCertFile)">
              {{ form.standardCertFile === '' ? '上传' : '更换附件' }}
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </detail-block>

  <detail-block title="依据的技术文件">
    <template v-if="pageType !== 'detail'" #btns>
      <el-button type="primary" @click="addFilesRow">
        增加行
      </el-button>
      <el-button type="info" @click="delFilesRow">
        删除行
      </el-button>
    </template>
    <el-table
      :data="technologyRelationList"
      border
      style="width: 100%;"
      @selection-change="handleSelectionChangeFiles"
    >
      <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 techFilesColumns"
        :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.text === '文件编号' && pageType !== 'detail'"
          #default="scope"
        >
          <el-input
            v-model="scope.row[item.value]"
            :placeholder="`${item.text}`"
            class="input"
            disabled
          >
            <template #append>
              <el-button
                v-if="pageType !== 'detail'"
                size="small"
                @click="handleClickFiles(scope.$index)"
              >
                选择
              </el-button>
            </template>
          </el-input>
        </template>
      </el-table-column>
    </el-table>
  </detail-block>

  <detail-block title="环境条件">
    <el-table
      :data="environmentalConditionsList"
      border
      style="width: 100%;"
    >
      <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 environmentalConditionsColumns"
        :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">
          <el-input
            v-if="scope.row.editable && (item.value === 'surroundEnvironment' || item.value === 'electricField')"
            v-model="scope.row[item.value]"
            :placeholder="`${item.text}`"
            class="input"
          />
          <el-input-number v-else-if="scope.row.editable" v-model="scope.row[item.value]" :step="0.1" />
          <span v-if="!scope.row.editable">{{ scope.row[item.value] }}</span>
        </template>
      </el-table-column>
    </el-table>
  </detail-block>

  <detail-block title="技术指标">
    <el-table
      :data="technicalIndexList"
      border
      style="width: 100%;"
    >
      <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">
          <el-input
            v-if="scope.row.editable"
            v-model="scope.row[item.value]"
            :placeholder="`${item.text}`"
            class="input"
          />
          <span v-else>{{ scope.row[item.value] }}</span>
        </template>
      </el-table-column>
    </el-table>
  </detail-block>
  <!-- 选择所依据的技术文件 -->
  <select-tech-files ref="techFileRef" @confirm="confirmSelectTechFile" />
  <!-- 选择建标申请 -->
  <select-build-standard-dialog ref="selectBuildStandardRef" @confirm="confirmSelectBuildStandard" />
</template>
