<!-- 更换\暂停\撤销\恢复\复查详情 -->
<script lang="ts" setup name="standardListAdd">
import { reactive, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules, UploadRequestOptions, UploadUserFile } from 'element-plus'
import dayjs from 'dayjs'
import type { IFixedAssetsList, IFromListInfo, IformInline } from '../../standard_interface'
import EquipmentDialog from '../standardList/equipmentDialog.vue'
import selectStandardAuxiliaryEquipment from '../standardList/selectStandardAuxiliaryEquipment.vue'
import StandardDialog from './standardDialog.vue'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import { getStaffList } from '@/api/measure/person'
import { getTypeSelect } from '@/api/system/price'
import {
  failUpdateStandardEquipmentApply,
  getStandardLisAdd,
  getStandardLisdetali,
  getStandardListDetail,
  getUsersDept,
  submitStandardEquipmentApply,
  updateStandardEquipmentApply,
} from '@/api/device/standard'
import { UploadFile } from '@/api/measure/file'
import useUserStore from '@/store/modules/user'
import showPhoto from '@/views/system/tool/showPhoto.vue'
import { cancelApproval, fetchApproval, submitApproval } from '@/api/approval'
const approvalDialog = ref() // 审批对话ref
const decisionItem = ref('') // 同意、驳回、拒绝按钮权限
const processId = ref('') // 流程实例id
const taskId = ref('') // 任务id，用于同意、驳回、拒绝审批
const tempEquipementList = ref([]) // 除了更换之外的申请需要保存的参数
// 选择标准装置弹窗ref
const standarDialog = ref()
const tableId = ref('') // 标准配套设备需要的id
const loading = ref(false) // 表单加载状态
const infoId = ref('') // id
const buttonArray = ref<string[]>([]) // 顶部按钮数组
const pageType = ref('add') // 页面类型: add,edit, detail
const buttonLoading = ref(false) // 按钮加载状态
const textMap: { [key: string]: string } = {
  edit: '编辑',
  add: '新建',
  detail: '详情',
} // 字典
// 从路由中获取页面类型参数
const $route = useRoute()
const formId = ref<string>('')
const user = useUserStore() // 用户信息
const addId = ref('') // 保存后的id，用于提交使用
const approvalStatusName = ref('') // 审批状态名称
// 表格选中的数组
const selectionList = ref<object[]>([])
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string
  formId.value = $route.query.formId as string
  if ($route.query.id) {
    infoId.value = $route.query.id as string
  }
}
const ruleFormRef = ref<FormInstance>()
const formInline = ref<IformInline>({
  applyNo: '', // 申请编号
  applyName: '', // 申请名称
  applyTime: '', // 申请时间
  applyUnit: '', // 申请单位
  applyUnitName: '', // 申请单位名称
  applyPerson: '', // 申请人
  applyPersonName: '', // 申请人名称
  assessDate: '', // 考核日期
  assessmentUnit: '', // 考核单位
  category: '', // 类 别
  categoryName: '', // 类 别名称
  constructionStandardProject: '', // 建标项目
  constructionStandardUnitName: '', // 建标单位名称
  contactInfo: '', // 联系方式
  createTime: null, // 创建时间
  createUser: null, // 创建人
  id: '', // 主键id
  processId: '', // 流程实例id
  laboratoryOwner: '', // 实验室
  laboratoryOwnerContact: '', // 实验室负责人
  laboratoryOwnerName: '', // 实验室名称
  managerState: '', // 管理状态
  managerStateName: '', // 管理状态名称
  measureMajor: '', // 计量专业
  fileList: [], // 文件列表
  measureMajorName: '', // 计量专业名称
  mesureRange: '', // 测量范围
  organizeNo: '', // 组织机构代码
  preparationDate: '', // 筹建日期
  projectNo: '', // 项目编号
  remark: '', // 备注
  standardHumidity: null, // 标准湿度
  standardLaboratory: '', // 标准所在实验室
  standardLaboratoryName: '', // 标准所在实验室名称
  standardLevel: '', // 标准等级
  standardLevelName: '', // 标准等级名称
  standardName: '', // 标准名称
  standardNo: '', // 标准编号
  standardOwner: '', // 标准负责人
  standardOwnerName: '', // 标准负责人名称
  standardTemperature: null, // 标准温度
  totalInvestment: null, // 投资总额
  transmitRange: '', // 传递范围
  transmitRangeName: '', // 传递范围名称
  uncertainty: '', // 不确定度
})

const fromListInfo = ref<IFromListInfo>({
  applyNo: '', // 申请编号
  applyName: '', // 申请名称
  applyTime: '', // 申请时间
  applyUnit: '', // 申请单位
  applyUnitName: '', // 申请单位名称
  applyPerson: '', // 申请人
  applyPersonName: '', // 申请人名称
  applyDept: '', // 申请部门
  applyType: $route.query.applyType, // 申请类型
  applyTypeName: '', // 申请类型名称
  approvalStatus: '', // 审批状态
  applyEquipmentList: [], // 申请设备列表
  fixedAssetsList: [], // 申请设备上传列表
  newFixedAssetsList: [], // 申请设备上传列表
  approvalStatusName: '', // 审批状态名称
  constructionStandardUnitName: '', // 建标单位名称
  createTime: null, // 创建时间
  createUser: null, // 创建人
  fileList: [], // 文件列表
  id: '', // 主键id
  processId: '', // 审批id
  remark: '', // 备注
  standardEquipmentId: '', // 标准装置id
  standardName: '', // 标准名称
  standardNo: '', // 标准编号
  standardOwner: '', // 标准负责人
  taskId: '', // 任务id
  minioFileName: [], // 附件
  newSupportEquipmentList: [], // 替换后的设备列表
  oldSupportEquipmentList: [], // 需要被替换的设备列表
})
// 下拉框数组类型
interface IOptions {
  id: string
  name: string
  value: string
  organizeName: string
  deptId: string
}
const checkTypeOptions = ref<IOptions[]>([])
const standardOwnerOptions = ref<IOptions[]>([]) // 标准负责人
const fileList = ref<UploadUserFile[]>([]) // 文件对象数组
const measureMajorList = ref<IOptions[]>([]) // 计量专业下拉框
const standardManagerStateList = ref<IOptions[]>([]) // 管理状态下拉框
const standardLevelList = ref<IOptions[]>([]) // 标准等级下拉框
const transmitRangeList = ref<IOptions[]>([]) // 传递范围下拉框
// 标准所在部门下拉框
const standardUsersDeptList = ref<IOptions[]>([])
// 获取下拉框
const getSelectList = (code: string) => {
  getTypeSelect(code).then((res) => {
    if (code === 'measureMajor') {
      measureMajorList.value = res.data
    }
    else if (code === 'standardManagerState') {
      standardManagerStateList.value = res.data
    }
    else if (code === 'standardLevel') {
      standardLevelList.value = res.data
    }
    else if (code === 'transmitRange') {
      transmitRangeList.value = res.data
    }
    else if (code === 'standardCategory') {
      checkTypeOptions.value = res.data
    }
  })
}
getSelectList('measureMajor') // 获取计量专业下拉框
getSelectList('standardManagerState') // 获取管理状态下拉框
getSelectList('standardLevel') // 获取标准等级下拉框
getSelectList('transmitRange') // 获取传递范围下拉框
getSelectList('standardCategory') // 获取类别下拉框
// 获取部门信息参数
const params = ref({
  director: '',
  meterMajor: '',
  createEndTime: '',
  createstartTime: '',
  organizeName: '',
  organizeNo: '',
  organizeType: '2',
  pdeptId: null,
  offset: 1,
  limit: 999999,
})
// 获取部门信息
getUsersDept(params.value).then((res) => {
  standardUsersDeptList.value = res.data.rows
})
// 获取到标准负责人数组
const getStandardOwnerOptions = () => {
  const params = {
    staffNo: '', // 人员编号
    name: '', // 姓名
    deptId: '', // 工作部门
    major: '', // 计量专业
    verifierCertificateNo: '', // 证书号
    certificateStatus: '', // 证书状态
    limit: 999999,
    offset: 1,
  }
  getStaffList(params).then((res) => {
    standardOwnerOptions.value = res.data.records
  })
}
// 数据
const list = ref<object[]>([])
// 标准配套设备更换表格总数
const total = ref(0)
// 标准配套设备表头类型
interface columnsType {
  text: string // 表头名称
  value: string // 内容
  align: string // 对齐方式
  required: Boolean // 是否必填
  choose: Boolean // 是否有按钮
  time: Boolean // 是否是时间选择框
  width?: string // 宽
}

// 标准配套设备更换表头
const columns = ref<columnsType[]>([
  {
    text: '设备名称',
    value: 'equipmentName',
    align: 'center',
    required: true,
    choose: true,
    time: false,
    width: '240',
  },
  {
    text: '设备编号',
    value: 'equipmentNo',
    align: 'center',
    width: '160',
    required: true,
    choose: false,
    time: false,
  },
  {
    text: '型号',
    value: 'modelNo',
    align: 'center',
    required: true,
    choose: false,
    time: false,
  },
  {
    text: '测量范围',
    value: 'mesureRange',
    align: 'center',
    required: true,
    choose: false,
    time: false,
  },
  {
    text: '使用部门',
    value: 'useDeptName',
    align: 'center',
    required: true,
    choose: false,
    time: false,
  },
  {
    text: '检定时间',
    value: 'mesureDate',
    align: 'center',
    width: '180',
    required: true,
    choose: false,
    time: false,
  },
  {
    text: '检定结果',
    value: 'mesureResultName',
    align: 'center',
    required: true,
    choose: false,
    time: false,
  },
  {
    text: '有效日期',
    value: 'validDate',
    align: 'center',
    width: '120',
    required: true,
    choose: false,
    time: false,
  },
])

// 初始化路由
const $router = useRouter()
// 关闭
const close = () => {
  $router.back()
}
// 表单验证规则
const rules = reactive<FormRules>({
  standardName: [{ required: true, message: '标准名称必填', trigger: ['blur', 'change'] }],
  projectNo: [{ required: true, message: '项目编号必填', trigger: ['blur', 'change'] }],
  constructionStandardProject: [{ required: true, message: '建标项目必填', trigger: ['blur', 'change'] }],
  organizeNo: [{ required: true, message: '组织机构代码必填', trigger: ['blur', 'change'] }],
  constructionStandardUnitName: [{ required: true, message: '建标单位名称必填', trigger: ['blur', 'change'] }],
  standardOwner: [{ required: true, message: '标准负责人必填', trigger: ['blur', 'change'] }],
  contactInfo: [{ required: true, message: '联系方式必填', trigger: ['blur', 'change'] }],
  category: [{ required: true, message: '类别必填', trigger: ['blur', 'change'] }],
  standardLevel: [{ required: true, message: '标准等级必填', trigger: ['blur', 'change'] }],
  transmitRange: [{ required: true, message: '传递范围必填', trigger: ['blur', 'change'] }],
  preparationDate: [{ type: 'date', required: true, message: '筹建日期必填', trigger: 'change' }],
  applyTime: [{ required: true, message: '申请时间必填', trigger: ['blur', 'change'] }],
  managerState: [{ required: true, message: '管理状态必填', trigger: ['blur', 'change'] }],
  measureMajor: [{ required: true, message: '计量专业必填', trigger: ['blur', 'change'] }],
  assessmentUnit: [{ required: true, message: '考核单位必填', trigger: ['blur', 'change'] }],
  assessDate: [{ type: 'date', required: true, message: '考核日期必填', trigger: 'change' }],
  uncertainty: [{ required: true, message: '不确定度必填', trigger: ['blur', 'change'] }],
  mesureRange: [{ required: true, message: '测量范围必填', trigger: ['blur', 'change'] }],
  standardTemperature: [{ required: true, message: '标准温度必填', trigger: ['blur', 'change'] },
    { pattern: /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/, message: '标准温度只能为数字', trigger: ['blur', 'change'] }],
  standardHumidity: [
    { required: true, message: '标准湿度必填', trigger: ['blur', 'change'] },
    { pattern: /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/, message: '标准湿度只能为数字', trigger: ['blur', 'change'] }],
})
// 第几条数据选择
const listIndex = ref(0)

// ---------------------------------------文件上传-------------------------------------
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  // 原生上传
  console.log(event.target.files)
  const files = event.target.files
  if (files.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    for (var i = 0; i < files.length; i++) {
      fd.append('multipartFile', files[i])
    }
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    UploadFile(fd).then((res) => {
      if (res.code === 200) {
        res.data.forEach((item: string) => {
          formInline.value.fileList.push({
            minioFileName: item,
          })
        })
        fromListInfo.value.fileList = formInline.value.fileList
        ElMessage.success('文件上传成功')
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}

// 删除附件
const del = (index: any) => {
  formInline.value.fileList.splice(index, 1)
}
// -----------------------------------------------------------------------------------
// 选择标准配套设备
const equipmentDialog = ref()
const listNewIndex = ref()
const tableType = ref('old') // 是需要更换的表格还是更换为的表格
const standardAuxiliaryEquipment = ref()
// 点击标准配套设备选择按钮
const chooseList = (row: object, index: number, type: string) => {
  tableType.value = type
  if (type === 'old') {
    if (!tableId.value) {
      ElMessage.warning('请先选择标准名称')
    }
    else {
      listIndex.value = index
      standardAuxiliaryEquipment.value.initDialog()
    }
  }
  if (type === 'new') {
    listNewIndex.value = index
    equipmentDialog.value.initDialog()
  }
}
// 证书测试数据
const simulateObject = {
  data: dayjs(`${new Date()}`).format('YYYY.MM.DD'), // 有效日期
  certificateNo: '199926465422', // 证书编号
  authorityOfIssue: 'xxx公司', // 发证单位
  authorityOfDate: dayjs(`${new Date()}`).format('YYYY.MM.DD'), // 发证日期
}

// ---------------------------------------操作表格-需要更换------------------------------------
// 点击增加行
const addRow = (type: string) => {
  console.log(type)

  if (type === 'old') { // 需要更换
    // 判断applyEquipmentList上一条数据是否填写
    console.log(fromListInfo.value.newFixedAssetsList)

    if (fromListInfo.value.fixedAssetsList.length >= 1 && fromListInfo.value.fixedAssetsList[fromListInfo.value.fixedAssetsList.length - 1].equipmentId === '') {
      ElMessage.warning('请完善上一条设备信息')
    }
    else {
      fromListInfo.value.fixedAssetsList.push({
        equipmentId: '',
        standardApplyId: '',
      })
    }
  }
  else { // 更换为
    // 判断applyEquipmentList上一条数据是否填写
    if (fromListInfo.value.newFixedAssetsList.length >= 1 && fromListInfo.value.newFixedAssetsList[fromListInfo.value.newFixedAssetsList.length - 1].equipmentId === '') {
      ElMessage.warning('请完善上一条设备信息')
    }
    else {
      fromListInfo.value.newFixedAssetsList.push({
        equipmentId: '',
        standardApplyId: '',
      })
    }
  }
}
// 删除行
const removeRow = (type: string) => {
  if (type === 'old') { // 需要更换
    if (selectionList.value.length > 0) {
      fromListInfo.value.fixedAssetsList = fromListInfo.value.fixedAssetsList.filter((item) => {
        return !selectionList.value.includes(item)
      })
    }
    else {
      ElMessage.warning('请选中')
    }
  }
  else { // 更换为
    if (selectionList.value.length > 0) {
      fromListInfo.value.newFixedAssetsList = fromListInfo.value.newFixedAssetsList.filter((item) => {
        return !selectionList.value.includes(item)
      })
    }
    else {
      ElMessage.warning('请选中')
    }
  }
}
// 选择好标准配套设备
const equipmentAddRow = (data: IFixedAssetsList) => {
  data.validDate = data.validDate ? dayjs(data.validDate).format('YYYY-MM-DD') : data.validDate

  if (tableType.value === 'old') { // 需要被更换
    const index = fromListInfo.value.fixedAssetsList.findIndex(item => item.equipmentId === data.id)
    if (index === -1) {
      fromListInfo.value.fixedAssetsList[listIndex.value] = data
      fromListInfo.value.fixedAssetsList[listIndex.value].supportEquipmentId = data.id
      // fromListInfo.value.fixedAssetsList[listIndex.value].equipmentId = data.id
      fromListInfo.value.fixedAssetsList[listIndex.value].id = ''
    }
    else {
      ElMessage.warning('该设备已存在')
    }
  }

  if (tableType.value === 'new') { // 更换为
    const index = fromListInfo.value.newFixedAssetsList.findIndex(item => item.equipmentId === data.id)
    if (index === -1) {
      fromListInfo.value.newFixedAssetsList[listNewIndex.value] = data
      fromListInfo.value.newFixedAssetsList[listNewIndex.value].equipmentId = data.id
      fromListInfo.value.newFixedAssetsList[listNewIndex.value].id = ''
    }
    else {
      ElMessage.warning('该设备已存在')
    }
  }
}
// -------------------------------------------------------------------------------------

// 获取详情信息
const getInfo = (id: string | number) => {
  const loading = ElLoading.service({
    lock: true,
    background: 'rgba(255, 255, 255, 0.8)',
  })
  getStandardLisdetali({ id }).then((res) => {
    // 判断下拉框返回的数据是否是number类型，如果是就得转成string类型
    Object.keys(res.data).map((item) => {
      if (typeof res.data[item] === 'number') {
        res.data[item] = res.data[item].toString()
      }
    })
    // 给数据对象赋值
    formInline.value = res.data.meterStandardEquipment
    // 拿到当前的标准设备id
    // fromListInfo.value.standardEquipmentId = res.data.id
    fromListInfo.value.standardEquipmentId = res.data.standardEquipmentId
    tableId.value = res.data.standardEquipmentId
    // 拿到当前的设备信息
    // fromListInfo.value.fixedAssetsList = res.data.fixedAssetsList
    // 需要更换的表格
    if (res.data.oldSupportEquipmentList && res.data.oldSupportEquipmentList.length) {
      fromListInfo.value.fixedAssetsList = res.data.oldSupportEquipmentList.map((item: any) => {
        return {
          ...item,
          id: '',
          supportEquipmentId: item.id,
          validDate: item.validDate ? dayjs(item.validDate).format('YYYY-MM-DD') : '',
        }
      })
    }
    // 更换为的表格
    if (res.data.newSupportEquipmentList && res.data.newSupportEquipmentList.length) {
      fromListInfo.value.newFixedAssetsList = res.data.newSupportEquipmentList.map((item: any) => {
        return {
          ...item,
          id: '',
          equipmentId: item.id,
          validDate: item.validDate ? dayjs(item.validDate).format('YYYY-MM-DD') : '',
        }
      })
    }
    formInline.value.applyNo = res.data.applyNo // 申请编号
    formInline.value.applyName = res.data.applyName // 申请名称
    formInline.value.applyTime = res.data.applyTime // 申请时间
    formInline.value.applyUnit = res.data.applyUnit // 申请单位
    formInline.value.applyUnitName = res.data.applyUnitName // 申请单位名称
    formInline.value.applyPerson = res.data.applyPerson // 申请人
    formInline.value.applyPersonName = res.data.applyPersonName // 申请人名称
    formInline.value.fileList = res.data.fileList // 文件列表
    formInline.value.applyName = `标准装置${$route.query.routeMetaTitle}` // 申请名称固定
    loading.close()
  })
}

// 提交
const submit = () => {
  if (addId.value === '') {
    ElMessage.warning('请先保存')
  }
  else {
    submitStandardEquipmentApply({
      id: addId.value,
      formId: formId.value,
    }).then((res) => {
      if (res.code === 200) {
        ElMessage.success('已提交')
        close()
      }
    })
  }
}

// 点击保存
const save = async (formEl: FormInstance | undefined) => {
  // 添加校验条件
  if ($route.query.routeMetaTitle === '更换申请' && fromListInfo.value.fixedAssetsList) {
    if (!fromListInfo.value.fixedAssetsList[0]?.supportEquipmentId) {
      ElMessage.warning('需要更换的标准配套设备不能为空')
      return false
    }
  }
  if ($route.query.routeMetaTitle === '更换申请' && fromListInfo.value.newFixedAssetsList) {
    if (!fromListInfo.value.newFixedAssetsList[0]?.equipmentId) {
      ElMessage.warning('更换成的标准配套设备不能为空')
      return false
    }
  }
  if (!formEl) {
    return
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 保存之前清除空行、避免传给后端无用空对象
      if (fromListInfo.value.fixedAssetsList && fromListInfo.value.fixedAssetsList.length) {
        const index = fromListInfo.value.fixedAssetsList.findIndex((item: any) => !item.supportEquipmentId)
        if (index !== -1) {
          fromListInfo.value.fixedAssetsList.splice(index, 1)
        }
      }
      // 保存之前清除空行、避免传给后端无用空对象
      if (fromListInfo.value.newFixedAssetsList && fromListInfo.value.newFixedAssetsList.length) {
        const index = fromListInfo.value.newFixedAssetsList.findIndex((item: any) => !item.equipmentId)
        if (index !== -1) {
          fromListInfo.value.newFixedAssetsList.splice(index, 1)
        }
      }
      if (fromListInfo.value.fixedAssetsList.length !== fromListInfo.value.newFixedAssetsList.length) {
        ElMessage.warning('两个表格数据条数应相等')
        return false
      }
      ElMessageBox.confirm('确认保存吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const loading = ElLoading.service({
          lock: true,
          background: 'rgba(255, 255, 255, 0.8)',
        })
        if ($route.query.routeMetaTitle === '更换申请') {
          fromListInfo.value.applyEquipmentList = fromListInfo.value.newFixedAssetsList.map((item, index) => {
            return {
            // ...item,
              equipmentId: item.equipmentId,
              // id: item.equipmentId,
              standardApplyId: infoId.value,
              supportEquipmentId: fromListInfo.value.fixedAssetsList[index].supportEquipmentId,
            }
          })
        }
        else {
          fromListInfo.value.applyEquipmentList = tempEquipementList.value.map((item: any, index: number) => {
            return {
            // ...item,
              equipmentId: item.equipmentId,
              // id: item.equipmentId,
              standardApplyId: infoId.value,
            }
          })
        }

        fromListInfo.value.newSupportEquipmentList = fromListInfo.value.newFixedAssetsList
        fromListInfo.value.oldSupportEquipmentList = fromListInfo.value.fixedAssetsList
        fromListInfo.value.applyName = formInline.value.applyName // 申请名称固定
        fromListInfo.value.applyUnit = formInline.value.applyUnit // 申请单位
        fromListInfo.value.applyUnitName = formInline.value.applyUnitName // 申请单位名称
        fromListInfo.value.applyPerson = formInline.value.applyPerson // 申请人
        fromListInfo.value.applyPersonName = formInline.value.applyPersonName // 申请人名称
        fromListInfo.value.applyTime = formInline.value.applyTime // 申请时间
        fromListInfo.value.fileList = formInline.value.fileList.map((item) => {
          return {
            minioFileName: item.minioFileName,
          }
        }) // 文件列表
        if (pageType.value === 'add') { // 新建
          getStandardLisAdd(fromListInfo.value).then((res) => {
            if (res.code === 200) {
              ElMessage.success('保存成功')
              addId.value = res.data
              loading.close()
            }
          })
        }
        else if (pageType.value === 'edit') { // 编辑
          if (approvalStatusName.value === '未通过-驳回') { // 未通过-驳回
            failUpdateStandardEquipmentApply(fromListInfo.value).then((res) => {
              if (res.code === 200) {
                ElMessage.success('保存成功')
                loading.close()
                close()
              }
            })
          }
          else { // 草稿箱、已取消
            updateStandardEquipmentApply(fromListInfo.value).then((res) => {
              if (res.code === 200) {
                ElMessage.success('保存成功')
                loading.close()
                close()
              }
            })
          }
        }
      })
    }
  })
}

// 点击标准名称选择
const standardChange = () => {
  standarDialog.value.initDialog()
}

// 表格多选框
const handleSelectionChange = (e: any) => {
  selectionList.value = e
}
watch(
  () => formInline.value,
  (newVal) => {
    // 变化后存储
  },
  { deep: true, immediate: true },
)

// 标准装置发生改变data类型
interface dataReturn {
  id: string
}
// 获取详情信息
const getStandarInfo = (id: string | number) => {
  getStandardListDetail({ id }).then((res) => {
    Object.keys(res.data).map((item) => {
      if (typeof res.data[item] === 'number') {
        res.data[item] = res.data[item].toString()
      }
    })
    formInline.value = { ...formInline.value, ...res.data }
    fromListInfo.value.standardEquipmentId = res.data.id
    if ($route.query.routeMetaTitle === '更换申请') {
      fromListInfo.value.newFixedAssetsList = [] // 更换申请新表格（更换成什么设备）
      fromListInfo.value.fixedAssetsList = []// 更换申请旧表格（需要被更换的）
    }
    else {
      tempEquipementList.value = res.data.equipmentList
    }
  })
}
// 选择标准装置完成之后
const StandarAddRow = (data: dataReturn) => {
  getStandarInfo(data.id)
  tableId.value = data.id
  nextTick(() => {
    ruleFormRef.value?.clearValidate() // 清除校验
  })
}

// ----------------------------------------审批-------------------------------------
const approvalRecordData = ref([]) // 审批流程数据
// 查询审批记录
function getApprovalRecord(processId: string) {
  if (pageType.value !== 'add') {
    if (processId) {
      fetchApproval(processId).then((res) => {
        approvalRecordData.value = res.data
      })
    }
    else {
      ElMessage.warning('流程实例id为空')
    }
  }
}
// 审批结束回调
const approvalSuccess = () => {
  close() // 返回上一页
}
// 审批
const handleApprove = (val: string, title = '') => {
  if (val === '取消') {
    const params = {
      processInstanceId: fromListInfo.value.processId!,
      comments: '',
    }
    ElMessageBox.confirm(
      '确认取消该审批吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(() => {
        cancelApproval(params).then((res) => {
          ElMessage({
            type: 'success',
            message: '取消成功',
          })
          close()
        })
      })
  }
  else if (val === '同意') {
    approvalDialog.value.initDialog('agree', taskId.value)
  }
  else if (val === '驳回') {
    approvalDialog.value.initDialog('reject', taskId.value)
  }
  else if (val === '拒绝') {
    approvalDialog.value.initDialog('refuse', taskId.value)
  }
}
// ---------------------------------------------------------------------------------
onMounted(async () => {
  await getStandardOwnerOptions()
  fromListInfo.value.processId = $route.query.processId as string // 流程实例id
  processId.value = $route.query.processId as string // 流程实例id
  decisionItem.value = $route.query.decisionItem as string // 同意、驳回、拒绝按钮权限
  taskId.value = $route.query.taskId as string // 任务id
  approvalStatusName.value = $route.query.approvalStatusName as string // 审批名称
  formInline.value.id = $route.query.id as string // id
  fromListInfo.value.id = $route.query.id as string // id
  formInline.value.applyName = `标准装置${$route.query.routeMetaTitle}` // 申请名称固定
  formInline.value.applyUnit = user.deptId // 申请单位
  formInline.value.applyUnitName = user.deptName // 申请单位名称
  formInline.value.applyPerson = user.id // 申请人
  formInline.value.applyPersonName = user.name // 申请人名称
  formInline.value.applyTime = dayjs().format('YYYY-MM-DD HH:mm:ss') // 申请时间
  // 编辑、详情获取详情信息
  if (pageType.value !== 'add') {
    getInfo(infoId.value)
  }
  if (approvalStatusName.value !== '草稿箱') {
    getApprovalRecord(processId.value) // 查询审批记录
  }
})
</script>

<template>
  <app-container>
    <detail-page :title="`${$route.query.routeMetaTitle} -- ${textMap[pageType]}`">
      <template #btns>
        <el-button v-if="pageType === 'detail' && approvalStatusName === '待审批'" type="primary" @click="handleApprove('同意')">
          同意
        </el-button>
        <el-button v-if="pageType === 'detail' && approvalStatusName === '待审批' && decisionItem !== '3'" type="primary" @click="handleApprove('驳回')">
          驳回
        </el-button>
        <el-button v-if="pageType === 'detail' && approvalStatusName === '待审批' && decisionItem !== '2'" type="danger" @click="handleApprove('拒绝')">
          拒绝
        </el-button>
        <el-button v-if="pageType === 'detail' && approvalStatusName === '审批中'" type="info" @click="handleApprove('取消')">
          取消
        </el-button>
        <el-button v-if="pageType === 'add'" type="primary" @click="submit">
          提交
        </el-button>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="save(ruleFormRef)">
          保存
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <el-form
        ref="ruleFormRef"
        :model="formInline"
        label-position="right"
        label-width="auto"
        :rules="rules"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="申请编号:">
              <el-input
                v-model="formInline.applyNo"
                :placeholder="pageType === 'detail' ? '' : '系统自动生成'"
                :class="{ 'detail-input': pageType === 'detail' }"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请名称:">
              <el-input
                v-model="formInline.applyName"
                :class="{ 'detail-input': pageType === 'detail' }"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请人:">
              <el-input
                v-model="formInline.applyPersonName"
                :class="{ 'detail-input': pageType === 'detail' }"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请单位:">
              <el-input
                v-model="formInline.applyUnitName"
                :class="{ 'detail-input': pageType === 'detail' }"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请时间:" prop="applyTime">
              <el-date-picker
                v-model="formInline.applyTime"
                type="datetime"
                :placeholder="pageType === 'detail' ? '' : '请选择申请时间'"
                style="width: 100%;"
                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="standardName">
              <el-input
                v-model="formInline.standardName"
                :placeholder="pageType === 'detail' ? '' : '请选择标准装置名称'"
                class="input"
                disabled
              >
                <template v-if="pageType !== 'detail'" #append>
                  <el-button
                    size="small"
                    :disabled="pageType === 'detail'"
                    @click="standardChange"
                  >
                    选择
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标准代码:">
              <el-input
                v-model.trim="formInline.standardNo"
                class="full-width-input"
                placeholder="系统自动生成"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目编号:" prop="projectNo">
              <el-input
                v-model.trim="formInline.projectNo"
                :placeholder="pageType === 'detail' ? '' : '项目编号'"
                class="full-width-input"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="建标项目:" prop="constructionStandardProject">
              <el-input
                v-model.trim="formInline.constructionStandardProject"
                :placeholder="pageType === 'detail' ? '' : '建标项目'"
                class="full-width-input"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="组织机构代码:" prop="organizeNo">
              <el-input
                v-model.trim="formInline.organizeNo"
                :placeholder="pageType === 'detail' ? '' : '组织机构代码'"
                class="full-width-input"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="建标单位名称:"
              prop="constructionStandardUnitName"
            >
              <el-input
                v-model.trim="formInline.constructionStandardUnitName"
                :placeholder="pageType === 'detail' ? '' : '建标单位名称'"
                class="full-width-input"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标准负责人:" prop="standardOwnerName">
              <el-input
                v-model.trim="formInline.standardOwnerName"
                :placeholder="pageType === 'detail' ? '' : '标准负责人'"
                class="full-width-input"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式:" prop="contactInfo">
              <el-input
                v-model.trim="formInline.contactInfo"
                :placeholder="pageType === 'detail' ? '' : '联系方式'"
                class="full-width-input"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="类 别:" prop="category">
              <el-select
                v-model="formInline.category"
                clearable
                :placeholder="pageType === 'detail' ? '' : '类别'"
                style="width: 100%;"
                size="default"
                disabled
              >
                <el-option
                  v-for="item in checkTypeOptions"
                  :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="standardLevel">
              <el-select
                v-model.trim="formInline.standardLevel"
                clearable
                :placeholder="pageType === 'detail' ? '' : '标准等级'"
                style="width: 100%;"
                size="default"
                disabled
              >
                <el-option
                  v-for="item in standardLevelList"
                  :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="transmitRange">
              <el-select
                v-model.trim="formInline.transmitRange"
                clearable
                :placeholder="pageType === 'detail' ? '' : '传递范围'"
                style="width: 100%;"
                size="default"
                disabled
              >
                <el-option
                  v-for="item in transmitRangeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="投资总额(元):">
              <el-input
                v-model.trim="formInline.totalInvestment"
                :placeholder="pageType === 'detail' ? '' : '投资总额'"
                class="full-width-input"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="筹建日期:" prop="preparationDate">
              <el-date-picker
                v-model="formInline.preparationDate"
                type="date"
                :placeholder="pageType === 'detail' ? '' : '筹建日期'"
                style="width: 100%;"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标准所在实验室:">
              <el-select
                v-model="formInline.standardLaboratoryName"
                clearable
                :placeholder="pageType === 'detail' ? ' ' : '标准所在实验室'"
                style="width: 100%;"
                size="default"
                disabled
              >
                <el-option
                  v-for="item in standardUsersDeptList"
                  :key="item.id"
                  :label="item.organizeName"
                  :value="item.deptId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="实验室负责人:">
              <el-input
                v-model.trim="formInline.laboratoryOwner"
                :placeholder="pageType === 'detail' ? '' : '实验室负责人'"
                class="full-width-input"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式:">
              <el-input
                v-model.trim="formInline.laboratoryOwnerContact"
                :placeholder="pageType === 'detail' ? '' : '联系方式'"
                class="full-width-input"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="管理状态:" prop="managerState">
              <el-select
                v-model="formInline.managerState"
                clearable
                :placeholder="pageType === 'detail' ? '' : '管理状态'"
                style="width: 100%;"
                size="default"
                disabled
              >
                <el-option
                  v-for="item in standardManagerStateList"
                  :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="measureMajor">
              <el-select
                v-model="formInline.measureMajor"
                clearable
                :placeholder="pageType === 'detail' ? '' : '计量专业'"
                style="width: 100%;"
                size="default"
                disabled
              >
                <el-option
                  v-for="item in measureMajorList"
                  :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="assessmentUnit">
              <el-input
                v-model.trim="formInline.assessmentUnit"
                :placeholder="pageType === 'detail' ? '' : '考核单位'"
                class="full-width-input"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="考核日期:" prop="assessDate">
              <el-date-picker
                v-model="formInline.assessDate"
                type="date"
                style="width: 100%;"
                :placeholder="pageType === 'detail' ? '' : '考核日期'"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="不确定度:" prop="uncertainty">
              <el-input
                v-model.trim="formInline.uncertainty"
                :placeholder="pageType === 'detail' ? '' : '不确定度'"
                class="full-width-input"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="测量范围:" prop="mesureRange">
              <el-input
                v-model.trim="formInline.mesureRange"
                :placeholder="pageType === 'detail' ? '' : '测量范围'"
                class="full-width-input"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="2">
            <el-form-item label="环境条件" />
          </el-col>
          <el-col :span="6">
            <el-form-item label="标准温度(℃):" prop="standardTemperature">
              <el-input
                v-model.trim="formInline.standardTemperature"
                :placeholder="pageType === 'detail' ? '' : '标准温度'"
                class="full-width-input"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标准湿度(%):" prop="standardHumidity">
              <el-input
                v-model.trim="formInline.standardHumidity"
                :placeholder="pageType === 'detail' ? '' : '标准湿度'"
                class="full-width-input"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="有效日期:">
              <el-date-picker
                v-model="simulateObject.data"
                type="date"
                style="width: 100%;"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="证书编号:">
              <el-input v-model.trim="simulateObject.certificateNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发证单位:">
              <el-input
                v-model.trim="simulateObject.authorityOfIssue"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发证日期:">
              <el-date-picker
                v-model="simulateObject.authorityOfDate"
                type="date"
                style="width: 100%;"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="备注:">
              <el-input
                v-model.trim="formInline.remark"
                :placeholder="pageType === 'detail' ? '' : '备注'"
                class="full-width-input"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="24">
            <el-form-item label="文件:">
              <!-- <el-button v-if="pageType === 'add'" id="file" type="primary" :style="{ 'margin-right': '20px' }" @click="upload">
                {{ !formInline.fileList.length ? '上传' : '上传' }}
              </el-button> -->
              <div v-for="(item, index) in formInline.fileList" :key="index" style="display: flex;">
                <show-photo :minio-file-name="item.minioFileName">
                  <!-- <span v-if="pageType === 'add'" class="photo-close" @click="del(index)">×</span> -->
                </show-photo>
              </div>
              <span v-if="!formInline.fileList.length">无</span>
              <!-- <span v-if="pageType !== 'add' && !formInline.fileList.length">无</span> -->
              <!-- <input v-show="pageType === ''" ref="fileRef" type="file" name="upload" multiple @change="onFileChange"> -->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
    <detail-block v-if="$route.query.routeMetaTitle === '更换申请'" title="需要更换的标准配套设备">
      <template v-if="pageType !== 'detail'" #btns>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="addRow('old')">
          增加行
        </el-button>
        <el-button v-if="pageType !== 'detail'" type="info" @click="removeRow('old')">
          删除行
        </el-button>
      </template>
      <el-table
        :data="fromListInfo.fixedAssetsList"
        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 columns"
          :key="item.value"
          :prop="item.value"
          :label="item.text"
          align="center"
          :width="item.width"
        >
          <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 v-if="item.choose" #append>
                <el-button
                  v-if="pageType !== 'detail'"
                  size="small"
                  @click="chooseList(scope.row, scope.$index, 'old')"
                >
                  选择
                </el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
      </el-table>
    </detail-block>

    <!-- 新 -->
    <detail-block v-if="$route.query.routeMetaTitle === '更换申请'" title="更换成的标准配套设备">
      <template v-if="pageType !== 'detail'" #btns>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="addRow('new')">
          增加行
        </el-button>
        <el-button v-if="pageType !== 'detail'" type="info" @click="removeRow('new')">
          删除行
        </el-button>
      </template>
      <el-table
        :data="fromListInfo.newFixedAssetsList"
        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 columns"
          :key="item.value"
          :prop="item.value"
          :label="item.text"
          align="center"
          :width="item.width"
        >
          <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 v-if="item.choose" #append>
                <el-button
                  v-if="pageType !== 'detail'"
                  size="small"
                  @click="chooseList(scope.row, scope.$index, 'new')"
                >
                  选择
                </el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
      </el-table>
    </detail-block>
    <detail-block v-if="approvalStatusName !== '草稿箱' && pageType !== 'add'" title="审批流程">
      <!-- 审批流程 -->
      <approval-record ref="approvalRecord" :approval-record-data="approvalRecordData" />
    </detail-block>
  </app-container>
  <!-- 选择标准装置弹窗 -->
  <standard-dialog ref="standarDialog" :title-type="$route.query.routeMetaTitle" @add="StandarAddRow" />
  <!-- 选择标准配套设备 -->
  <select-standard-auxiliary-equipment :id="tableId" ref="standardAuxiliaryEquipment" @add="equipmentAddRow" />
  <!-- 选择设备弹窗 -->
  <equipment-dialog ref="equipmentDialog" @add="equipmentAddRow" />
  <!-- 审批弹窗 -->
  <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
</template>

<style lang="scss">
.el-upload-list {
  display: none !important;
}
</style>
