<!-- 设备状态维护 基本信息 -->
<script name="FieldTestApproveBasic" lang="ts" setup>
import type { Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import dayjs from 'dayjs'
import type { IForm } from '../stateMaintenance-interface'
import SelectEquipmentDialog from '@/views/business/fieldTest/approve/dialog/selectEquipmentDialog.vue'
import type { IAccessory, Itech } from '@/views/equipement/info/book/book-interface'
import showPhoto from '@/components/showPhoto/index.vue'
import { UploadFile } from '@/api/file'
import type { deptType, dictType } from '@/global'
import type { IAddress } from '@/components/AddressSelect/address-interface'
import { getDictByCode } from '@/api/system/dict'
import { SCHEDULE } from '@/utils/scheduleDict'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import useUserStore from '@/store/modules/user'
import { getDeptTreeList } from '@/api/system/dept'
import { toTreeList } from '@/utils/structure'
import { getStaffList } from '@/api/resource/register'
import countries from '@/components/AddressSelect/country-code.json'
import { getInfo as getEquipmentDetail } from '@/api/equipment/info/book'
import { addStateMaintenance, failUpdateStateMaintenance, getInfo, submit, updateStateMaintenance } from '@/api/equipment/stateMaintenance/stateMaintenance'
const props = defineProps({
  pageType: { // 页面类型 add新建 edit编辑 detail详情
    type: String,
    requre: true,
    default: 'detail',
  },
  id: {
    type: String,
    requre: true,
  },
  approvalStatusName: { // 审批状态名称
    type: String,
    requre: true,
  },
  title: String, // 标题
  approvalType: { // 1启封、2封存、3禁用、4报废
    type: String,
    default: '1',
  },
  formId: {
    type: String,
    default: '',
  },
})
const emits = defineEmits(['addSuccess', 'submitSuccess'])
const countryList = ref(countries) // 国家列表
const user = useUserStore() // 用户信息
const form = ref<IForm>({
  approvalNo: '', // 登记表编号、申请表编号
  approvalName: '', // 登记表名称
  createTime: '',	// 申请时间
  createUserId: '',	// 申请人id
  createUserName: '',	// 申请人姓名
  equipmentId: '', // 设备id
  equipmentName: '', // 设备名称
  equipmentNo: '', // 统一编号
  model: '', // 型号规格
  deptId: '', // 使用单位id
  deptName: '', // 使用单位
  productCountry: '', // 生产国家
  manufacturer: '', // 生产厂家
  manufactureNo: '', // 出厂编号
  produceDate: '', // 生产日期
  traceCompany: '', // 溯源单位
  traceDate: '', // 溯源日期
  measureValidDate: '', // 检定有效期
  meterIdentify: '', // 计量标识
  meterStandardName: '', // 所属测量标准
  technicalFile: '', // 所依据的技术文件
  approvalAddress: '', // 封存地点/存放地点/报废地点
  approvalReason: '', // 封存原因/启封原因/禁用原因/报废原因
  approvalType: '', // 申请类型
  equipmentStatus: '', // 启封设备状态
  performStatus: '', // 设备性能状态
  approvalTime: '', // 封存时间
})
const ruleFormRef = ref() // 表单ref
const ruleFormRefInfo = ref() // 表单ref
const loading = ref(false) // loading
const infoId = ref('') // id
const rules = ref<FormRules>({ // 校验规则
  equipmentNo: [{ required: true, message: '统一编号不能为空', trigger: ['blur', 'change'] }],
  approvalReason: [{ required: true, message: `${props.title}原因不能为空`, trigger: ['blur', 'change'] }],
  approvalAddress: [{ required: true, message: `${props.title}地点不能为空`, trigger: ['blur', 'change'] }],
  equipmentStatus: [{ required: true, message: '启封设备状态不能为空', trigger: ['blur', 'change'] }],
  performStatus: [{ required: true, message: '设备性能状态不能为空', trigger: ['blur', 'change'] }],
  approvalTime: [{ required: true, message: `${props.title}时间不能为空`, trigger: ['blur', 'change'] }],
})
// -----------------------------------------字典--------------------------------------------------------------
const meterIdentifyDict = ref<dictType[]>([]) // 计量标识
const useDeptList = ref<deptType[]>([]) // 所属部门列表
const userList = ref<{ [key: string]: string }[]>([]) // 用户列表
function getDict() {
  // 计量标识
  getDictByCode('bizMeterIdentify').then((response) => {
    meterIdentifyDict.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
  })
}

// --------------------------------------表格-------------------------------------------------
const technicalTargetList = ref<Itech[]>([]) // 技术指标列表
const technicalIndexColumns = [ // 技术指标表头
  { text: '检定参数名称', value: 'measureParam', required: true },
  { text: '测量范围', value: 'measureRange', required: true },
  { text: '不确定度或允许误差极限或准确度等级', value: 'uncertainty', required: true },
  { text: '误差计算指标', value: 'errorCalculateIndicators', required: true },
]
const attachmentList = ref<IAccessory[]>([]) // 主附件信息
const accessoryColumns = [ // 主附件信息
  { text: '名称', value: 'name', required: true },
  { text: '信息', value: 'information', required: true },
  { text: '位置', value: 'location', required: true },
]

// 点击所属依据标准
const handleClickMeterStandardLink = () => {
// 跳转标准装置详情页
}
// --------------------------------------选择设备编号-------------------------------------------------
const selectEquipmentDialogRef = ref() // 选择设备编号组件ref
// 批量添加
const selectEquipment = () => {
  selectEquipmentDialogRef.value.initDialog()
}

// 确定选择设备
const confirmSelectEquipment = (val: any) => {
  if (val.length) {
    getEquipmentDetail({ id: val[0].id, type: '1' }).then((res) => {
      attachmentList.value = res.data.attachmentList // 主附件信息
      technicalTargetList.value = res.data.technicalTargetList // 技术指标
      form.value.equipmentId = val[0].id // 设备id
      form.value.equipmentName = res.data.equipmentInfoApproval.equipmentName // 设备名称
      form.value.equipmentNo = res.data.equipmentInfoApproval.equipmentNo // 统一编号
      form.value.model = res.data.equipmentInfoApproval.model // 型号规格
      form.value.deptId = res.data.equipmentInfoApproval.deptId // 使用单位id
      form.value.deptName = res.data.equipmentInfoApproval.deptName // 使用单位
      form.value.productCountry = res.data.equipmentInfoApproval.productCountry // 生产国家
      form.value.manufacturer = res.data.equipmentInfoApproval.manufacturer // 生产厂家
      form.value.manufactureNo = res.data.equipmentInfoApproval.manufactureNo // 出厂编号
      form.value.produceDate = res.data.equipmentInfoApproval.produceDate // 生产日期
      form.value.traceCompany = res.data.equipmentInfoApproval.traceCompany // 溯源单位
      form.value.traceDate = res.data.equipmentInfoApproval.traceDate // 溯源日期
      form.value.measureValidDate = res.data.equipmentInfoApproval.measureValidDate // 检定有效期
      form.value.meterIdentify = res.data.equipmentInfoApproval.meterIdentify // 计量标识
      form.value.meterStandardName = res.data.equipmentInfoApproval.meterStandardName // 所属测量标准
      form.value.technicalFile = res.data.equipmentInfoApproval.technicalFile // 所依据的技术文件
    })
  }
}
// -----------------------------------------------保存-------------------------------------------
/**
 * 点击保存
 * @param formEl 基本信息表单ref
 */
const saveForm = async () => {
  if (props.approvalType === '1') { // 启封
    if (!form.value.approvalReason) { return ElMessage.warning('启封原因不能为空') }
    if (!form.value.equipmentStatus) { return ElMessage.warning('启封设备状态不能为空') }
  }
  await ruleFormRef.value.validate((valid: boolean) => {
    if (valid) { // 基本信息表单通过校验
      ruleFormRefInfo.value.validate((validin: boolean) => {
        if (validin) {
          ElMessageBox.confirm(
            '确认保存吗？',
            '提示',
            {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning',
            },
          ).then(() => {
            const loading = ElLoading.service({
              lock: true,
              text: '加载中...',
              background: 'rgba(255, 255, 255, 0.8)',
            })
            if (props.pageType === 'add') { // 新建
              addStateMaintenance({ ...form.value, approvalType: props.approvalType }).then((res) => {
                loading.close()
                form.value.approvalNo = res.data.approvalNo // 申请编号
                infoId.value = res.data.id // id
                emits('addSuccess', infoId.value)
                ElMessage.success('已保存')
              }).catch(() => {
                loading.close()
              })
            }
            else if (props.pageType === 'edit') { // 编辑
              console.log(props.approvalStatusName)
              if (props.approvalStatusName === '草稿箱' || props.approvalStatusName === '全部') {
                updateStateMaintenance({ ...form.value, approvalType: props.approvalType }).then((res) => {
                  loading.close()
                  emits('addSuccess', infoId.value)
                  ElMessage.success('已保存')
                }).catch(() => {
                  loading.close()
                })
              }
              else { // '未通过' || '已取消'
                failUpdateStateMaintenance({ ...form.value, approvalType: props.approvalType }).then((res) => {
                  loading.close()
                  emits('submitSuccess')
                  ElMessage.success('已保存')
                }).catch(() => {
                  loading.close()
                })
              }
            }
          })
        }
      })
    }
  })
}

// ----------------------------------------------提交--------------------------------------------
// 提交
/**
 *
 * @param processId 流程实例id
 * @param id
 */
const submitForm = (processId: string, id: string) => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(255, 255, 255, 0.6)',
  })
  submit({ id, formId: props.formId, processId }).then((res) => {
    ElMessage.success('已提交')
    emits('submitSuccess')
    loading.close()
  })
}
// -----------------------------------------获取详情------------------------------------------
// 获取详情
const fetchInfo = () => {
  loading.value = true
  getInfo({ id: infoId.value }).then((res) => {
    loading.value = false
    form.value = res.data
    attachmentList.value = res.data.attachmentList
    technicalTargetList.value = res.data.technicalTargetList
  })
}
// ---------------------------------------------钩子----------------------------------------------
watch(() => props.id, (newValue) => {
  infoId.value = newValue!
  if (infoId.value) {
    fetchInfo() // 获取详情信息
  }
}, { immediate: true })

onMounted(async () => {
  await getDict()
  form.value.approvalName = (props.title === '启封' || props.title === '封存') ? `设备${props.title}登记表` : `设备${props.title}申请表` // 登记表名、申请表名称
  form.value.createUserId = user.id// 申请人id
  form.value.createUserName = user.name // 申请人名字
  form.value.createTime = dayjs().format('YYYY-MM-DD HH-mm:ss')// 申请时间
  if (props.pageType !== 'add' && infoId.value) {
    fetchInfo() // 获取详情信息
  }
})

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

<template>
  <detail-block v-loading="loading" title="">
    <el-form
      ref="ruleFormRef"
      :model="form"
      :label-width="120"
      label-position="right"
      :rules="rules"
    >
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item :label="(props.title === '启封' || props.title === '封存') ? '登记表编号' : `申请表编号`">
            <el-input v-model="form.approvalNo" disabled placeholder="系统自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="(props.title === '启封' || props.title === '封存') ? '登记表名称' : '申请表名称'">
            <el-input
              v-model="form.approvalName"
              :placeholder="pageType === 'detail' ? '' : '请输入登记表名称'"
              disabled
            />
          </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="申请时间:" prop="applyTime">
            <el-date-picker
              v-model="form.createTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="统一编号:" prop="equipmentNo">
            <el-input
              v-model="form.equipmentNo"
              :placeholder="pageType === 'detail' ? '' : '请选择统一编号'"
              :class="{ 'detail-input': pageType === 'detail' }"
              disabled
            >
              <template v-if="pageType !== 'detail'" #append>
                <el-button size="small" @click="selectEquipment">
                  选择
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="设备名称:" prop="equipmentName">
            <el-input
              v-model.trim="form.equipmentName"
              :placeholder="pageType === 'detail' ? '' : '请输入设备名称'"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="型号规格" prop="model">
            <el-input
              v-model.trim="form.model"
              :placeholder="pageType === 'detail' ? '' : '请输入型号规格'"
              disabled
              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" :data="useDeptList" disabled :placeholder="pageType === 'detail' ? ' ' : '所属部门'" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="生产国家:" prop="productCountry">
            <el-select
              v-model="form.productCountry"
              filterable
              :placeholder="pageType === 'detail' ? ' ' : '请选择生产国家'"
              disabled
              class="full-width-input"
            >
              <el-option v-for="country of countryList" :key="country.code" :label="country.CNName" :value="country.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="生产厂家:" prop="manufacturer">
            <el-input
              v-model.trim="form.manufacturer"
              :placeholder="pageType === 'detail' ? '' : '请输入生产厂家'"
              :class="{ 'detail-input': pageType === 'detail' }"
              disabled
              class="full-width-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="出厂编号:" prop="manufactureNo">
            <el-input
              v-model.trim="form.manufactureNo"
              :placeholder="pageType === 'detail' ? '' : '请输入出厂编号'"
              :class="{ 'detail-input': pageType === 'detail' }"
              disabled
              class="full-width-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="生产日期:" prop="produceDate">
            <el-date-picker
              v-model="form.produceDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :placeholder="pageType === 'detail' ? ' ' : '请选择生产日期'"
              disabled
              class="full-width-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="溯源单位:" prop="traceCompany" style="flex: 1;">
            <el-input
              v-model="form.traceCompany"
              disabled
              :placeholder="pageType === 'detail' ? ' ' : '请输入溯源单位'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="溯源日期:" prop="traceDate" style="flex: 1;">
            <el-date-picker
              v-model="form.traceDate"
              type="date"
              :placeholder="pageType === 'detail' ? ' ' : '请选择日期'"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              disabled
              class="full-width-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="检定有效期:" prop="measureValidDate" style="flex: 1;">
            <el-date-picker
              v-model="form.measureValidDate"
              type="date"
              :placeholder="pageType === 'detail' ? ' ' : '请选择日期'"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              disabled
              class="full-width-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="计量标识:" prop="meterIdentify" style="flex: 1;">
            <el-select
              v-model="form.meterIdentify"
              :placeholder="pageType === 'detail' ? ' ' : '请选择计量标识'"
              disabled
              class="full-width-input"
            >
              <el-option v-for="item of meterIdentifyDict" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </detail-block>
  <!-- 技术指标 -->
  <detail-block title="技术指标">
    <div v-if="!(pageType === 'detail' && !form.meterStandardName && !form.technicalFile)" class="file-area">
      <span v-if="form.meterStandardName">所属测量标准：<span class="link" @click="handleClickMeterStandardLink">{{ form.meterStandardName }}</span></span>
      <div class="tech-file">
        <span v-if="form.technicalFile" class="file-text">依据的技术文件: </span>
        <show-photo :minio-file-name="form.technicalFile!" width="100%" height="125px" />
      </div>
    </div>
    <el-table
      ref="techRef"
      :data="technicalTargetList"
      border
      style="width: 100%;"
    >
      <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"
      />
    </el-table>
  </detail-block>
  <!-- 主附件信息 -->
  <detail-block title="主附件信息">
    <el-table
      ref="accessoryRef"
      :data="attachmentList"
      border
      style="width: 100%;"
    >
      <el-table-column align="center" label="序号" width="80" type="index" />
      <el-table-column
        v-for="item in accessoryColumns"
        :key="item.value"
        :prop="item.value"
        :label="item.text"
        align="center"
      />
    </el-table>
  </detail-block>
  <detail-block title="">
    <el-form
      ref="ruleFormRefInfo"
      :model="form"
      :label-width="120"
      label-position="right"
      :rules="rules"
    >
      <el-row v-if="props.title === '封存' || props.title === '禁用'">
        <el-col :span="12">
          <el-form-item label="设备性能状态" prop="performStatus">
            <el-input
              v-model="form.performStatus"
              type="textarea"
              autosize
              :placeholder="pageType === 'detail' ? '' : '请输入设备性能状态'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="approvalReason" :label="`${props.title}原因`">
            <el-input
              v-model="form.approvalReason"
              type="textarea"
              autosize
              :placeholder="pageType === 'detail' ? '' : `请输入${props.title}原因`"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item v-if="props.title === '封存' || props.title === '禁用' || props.title === '报废'" prop="approvalAddress" :label="`${props.title}地点`">
            <el-input
              v-model="form.approvalAddress"
              type="textarea"
              autosize
              :placeholder="pageType === 'detail' ? '' : `请输入${props.title}地点`"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item v-if="props.title === '启封'" prop="equipmentStatus" label="启封设备状态">
            <el-input
              v-model="form.equipmentStatus"
              type="textarea"
              autosize
              :placeholder="pageType === 'detail' ? '' : '请输入启封设备状态'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item v-if="props.title === '封存' || props.title === '禁用' || props.title === '报废'" prop="approvalTime" :label="`${props.title}时间`">
            <el-date-picker
              v-model="form.approvalTime"
              type="datetime"
              :placeholder="pageType === 'detail' ? '' : `请选择${props.title}时间`"
              class="full-width-input"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </detail-block>

  <!-- 选择设备台账 -->
  <select-equipment-dialog ref="selectEquipmentDialogRef" @confirm="confirmSelectEquipment" />
</template>

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

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

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

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

