<!-- 溯源证书管理详情 -->
<script lang="ts" setup name="EquipmentSourceCertDetail">
import { ref } from 'vue'
import dayjs from 'dayjs'
import { ElLoading, ElMessage } from 'element-plus'
import type { IForm } from '../cert/cert-interface'
import selectApproveList from './dialog/selectFieldTestApprove.vue'
import selectSourceDialog from '@/views/equipement/source/plan/dialog/selectSourceDialog.vue'
import { getStaffList } from '@/api/resource/register'
import useUserStore from '@/store/modules/user'
import { getDictByCode } from '@/api/system/dict'
import type { dictType } from '@/global'
import { useCheckList } from '@/commonMethods/useCheckList'
import { getInfo } from '@/api/business/fieldTest/approve'
import { UploadFile } from '@/api/file'
import SelectEquipmentDialog from '@/views/business/fieldTest/approve/dialog/selectEquipmentDialog.vue'
import { getInfo as getEquipmentDetail } from '@/api/equipment/info/book'
import { addSourceCertList, updateSourceCert } from '@/api/equipment/source/cert'
// import type { IOptions } from '@/views/device/standardEquipment/standard_interface'
const user = useUserStore() // 用户信息
const textMap: { [key: string]: string } = {
  edit: '编辑',
  add: '新建',
  detail: '详情',
}// 字典
const $router = useRouter() // 关闭页面使用
const $route = useRoute() // 路由参数
const pageType = ref('add') // 页面类型: add, edit, detail
const infoId = ref('') // 列表id
const ruleFormRef = ref() // 表单ref
const form = ref<IForm>({
  certificateName: '', // 证书名称
  certificateNo: '', // 证书编号
  equipmentId: '', // 设备id
  equipmentName: '', // 设备名称
  equipmentNo: '', // 设备编号
  traceCompany: '', // 溯源单位名
  traceDate: '', // 检定日期
  validDate: '', // 证书有效期
  meterIdentify: '', 	// 计量标识(字典code)
  meterIdentifyName: '',	// 计量标识(字典value)
  remark: '', // 备注
  certificateFile: '', // 证书报告附件
})
const list = ref([]) // 记录结果表
// 校验规则
const formRules = ref({
  certificateNo: [{ required: true, message: '证书编号不能为空', trigger: ['blur', 'change'] }],
  certificateName: [{ required: true, message: '证书名称不能为空', trigger: ['blur', 'change'] }],
  equipmentNo: [{ required: true, message: '统一编号不能为空', trigger: ['blur', 'change'] }],
  equipmentName: [{ required: true, message: '设备名称不能为空', trigger: ['blur', 'change'] }],
  traceCompany: [{ required: true, message: '溯源单位不能为空', trigger: ['blur', 'change'] }],
  traceDate: [{ required: true, message: '检定日期不能为空', trigger: ['blur', 'change'] }],
  validDate: [{ required: true, message: '证书有效期不能为空', trigger: ['blur', 'change'] }],
  meterIdentify: [{ required: true, message: '计量标识不能为空', trigger: ['blur', 'change'] }],
})

// -------------------------------------------字典------------------------------------------
const meterIdentifyDict = ref<dictType[]>([]) // 计量标识

// 获取字典值
async function getDict() {
  // 计量标识
  getDictByCode('bizMeterIdentify').then((response) => {
    meterIdentifyDict.value = response.data
  })
}
// ----------------------------------路由参数--------------------------------------------
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string
  console.log(pageType.value)

  if ($route.params.id) {
    infoId.value = $route.params.id as string
  }
}
// --------------------------------------选择设备编号-------------------------------------------------
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) => {
      form.value.equipmentId = val[0].id // 设备id
      form.value.equipmentName = res.data.equipmentInfoApproval.equipmentName // 设备名称
      form.value.equipmentNo = res.data.equipmentInfoApproval.equipmentNo // 统一编号
    })
  }
}
// --------------------------------------------选择溯源机构---------------------------------------
const selectSourceDialogRef = ref() // 选择溯源机构组件ref
// 点击选择溯源机构
const selectsupplier = () => {
  selectSourceDialogRef.value.initDialog()
}

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

// -------------------------------------------文件上传--------------------------------------
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  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.certificateFile = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}
// -------------------------------------------------------------------------------------
// 关闭新增页面的回调
const close = () => {
  $router.back()
}

// 保存
const save = () => {
  ruleFormRef.value!.validate((valid: boolean) => {
    if (valid) {
      const loading = ElLoading.service({
        lock: true,
        background: 'rgba(255, 255, 255, 0.8)',
      })
      // 新建
      if (pageType.value === 'add') { // 新建
        addSourceCertList(form.value).then((res) => {
          ElMessage.success('保存成功')
          pageType.value = 'detail'
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }
      // 保存
      else if (pageType.value === 'edit') { // 编辑
        updateSourceCert({ ...form.value, id: infoId.value }).then((res) => {
          ElMessage.success('保存成功')
          pageType.value = 'detail'
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }
    }
    else {
      console.log('表单校验不通过')
    }
  })
}

onMounted(async () => {
  getDict().then(() => {
    if (pageType.value !== 'add') {
      form.value = $route.query as any
      form.value.certificateName = $route.query.certificateName as string // 证书名称
      form.value.certificateNo = $route.query.certificateNo as string // 证书编号
      form.value.equipmentId = $route.query.equipmentId as string // 设备id
      form.value.equipmentName = $route.query.equipmentName as string // 设备名称
      form.value.equipmentNo = $route.query.equipmentNo as string // 设备编号
      form.value.traceCompany = $route.query.traceCompany as string // 溯源单位名
      form.value.traceDate = $route.query.traceDate as string // 检定日期
      form.value.validDate = $route.query.validDate as string // 证书有效期
      form.value.meterIdentify = $route.query.meterIdentify as string	// 计量标识(字典code)
      form.value.meterIdentifyName = $route.query.meterIdentifyName	 as string// 计量标识(字典value)
      form.value.remark = $route.query.remark as string // 备注
      form.value.certificateFile = $route.query.certificateFile as string // 证书报告附件
      infoId.value = $route.query.id as string// id
    }
  })
})
</script>

<template>
  <app-container class="fieldtest-record-detail">
    <detail-page :title="`溯源证书管理-${textMap[pageType]}`">
      <template #btns>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="save">
          保存
        </el-button>
        <!-- <el-button v-if="pageType === 'detail'" type="primary" @click="print">
          打印
        </el-button> -->
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <el-form
        ref="ruleFormRef"
        :model="form"
        label-width="120"
        label-position="right"
        :rules="formRules"
      >
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="证书编号:" prop="certificateNo">
              <el-input v-model="form.certificateNo" class="full-width-input" :disabled="pageType === 'detail'" :placeholder="pageType === 'detail' ? '' : '请输入证书编号'" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="证书名称:" prop="certificateName">
              <el-input v-model="form.certificateName" class="full-width-input" :disabled="pageType === 'detail'" placeholder="请输入证书名称" />
            </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="traceCompany">
              <el-input
                v-model="form.traceCompany"
                placeholder="请选择溯源单位"
                class="input"
                disabled
              >
                <template v-if="pageType !== 'detail'" #append>
                  <el-button
                    size="small"
                    @click="selectsupplier"
                  >
                    选择
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检定日期:" prop="traceDate">
              <el-date-picker
                v-model="form.traceDate"
                type="date"
                :placeholder="pageType === 'detail' ? ' ' : '请输入检定日期'"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="证书有效期:" prop="validDate">
              <el-date-picker
                v-model="form.validDate"
                type="date"
                :placeholder="pageType === 'detail' ? ' ' : '请输入证书有效期'"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="计量标识:" prop="meterIdentify">
              <el-select
                v-model="form.meterIdentify"
                :placeholder="pageType === 'detail' ? ' ' : '请选择计量标识'"
                :disabled="pageType === 'detail'"
                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-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="备注:" prop="remark">
              <el-input
                v-model="form.remark"
                class="full-width-input"
                :placeholder="pageType === 'detail' ? ' ' : '请输入备注'"
                autosize
                type="textarea"
                :disabled="pageType === 'detail'"
              />
            </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.certificateFile" :minio-file-name="form.certificateFile" />
              <span v-else-if="pageType === 'detail'">无</span>
              <input v-show="pageType === ''" ref="fileRef" type="file" @change="onFileChange">
              <el-button v-if="pageType !== 'detail'" id="file" type="primary" :disabled="pageType === 'detail'" :style="{ 'margin-left': form.certificateFile === '' ? '0px' : '20px' }" @click="upload">
                {{ form.certificateFile === '' ? '上传' : '更换附件' }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
    <!-- 选择溯源供方 -->
    <select-source-dialog ref="selectSourceDialogRef" @confirm="confirmSelectedSource" />
    <!-- 选择设备台账 -->
    <select-equipment-dialog ref="selectEquipmentDialogRef" @confirm="confirmSelectEquipment" />
  </app-container>
</template>

<style lang="scss">
.fieldtest-record-detail {
  .el-table thead.is-group th.el-table__cell {
    background: #f2f6ff;
  }
}
</style>
