<!-- 分包方证书-编辑 -->
<script lang="ts" setup name="SubpackageCertificiateEdit">
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { uploadApi } from '@/api/system/notice'
import showPhoto from '@/views/tested/device/info/components/showPhotoSinge.vue'
import { getDictByCode } from '@/api/system/dict'
import useUserStore from '@/store/modules/user'
import { getUserDept } from '@/api/system/user'
import { editCertificate } from '@/api/eqpt/subpackage/certificate'
import subpackageDialog from '@/views/tested/subpackage/review/components/subpackageDialog.vue'
import deviceDialog from '@/views/tested/device/group/components/selectDevice.vue'
const $route = useRoute()
const $router = useRouter()
const userStore = useUserStore()
const ruleFormRef = ref<FormInstance>() // from组件
// 显示标题
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
  detail: '详情',
}
// 对话框类型：create,update
const dialogStatus = ref('create')
const ruleForm = ref<{ [key: string]: string }>({
  certificateName: '',
  certificateNo: '',
  certificateReport: '',
  certificateValid: '',
  checkDate: '',
  createDeptId: '',
  createTime: '',
  createUserId: '',
  createUserName: '',
  equipmentId: '',
  equipmentManufactureNo: '',
  equipmentModel: '',
  equipmentName: '',
  equipmentNo: '',
  id: '',
  meterIdentify: '',
  originalRecord: '',
  subcontractorId: '',
  subcontractorName: '',
  subcontractorNo: '',
  updateTime: '',
}) // 表单
const rules = ref<FormRules>({
  certificateNo: [{ required: true, message: '证书编号必填', trigger: ['blur', 'change'] }],
  certificateName: [{ required: true, message: '证书名称必填', trigger: ['blur', 'change'] }],
  subcontractorNo: [{ required: true, message: '检测单位编号必填', trigger: ['blur', 'change'] }],
  equipmentNo: [{ required: true, message: '受检设备编号必填', trigger: ['blur', 'change'] }],
  checkDate: [{ required: true, message: '检定(校准)日期必填', trigger: ['blur', 'change'] }],
  // meterIdentify: [{ required: true, message: '计量标识必选', trigger: ['blur', 'change'] }],
  // originalRecord: [{ required: true, message: '原始记录附件需上传', trigger: ['blur', 'change'] }],
  certificateReport: [{ required: true, message: '证书报告附件需上传', trigger: ['blur', 'change'] }],
  certificateValid: [{ required: true, message: '证书有效期必选', trigger: ['blur', 'change'] }],

}) // 表单验证规则
// 弹窗初始化
const initDialog = () => {
  dialogStatus.value = $route.params.type as string
  ruleFormRef.value?.resetFields()
  if ($route.params.type !== 'create') {
    const data = JSON.parse($route.query.row as string)
    ruleForm.value = data
  }
  if ($route.params.type === 'create' || $route.params.type === 'update') {
    ruleForm.value.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss') // 创建时间
    ruleForm.value.createUserId = userStore.id
    ruleForm.value.createUserName = userStore.name
    ruleForm.value.createDeptId = userStore.deptId
    ruleForm.value.createDeptName = userStore.deptName
    // 获取当前用户所在单位
    // getUserDept().then((res) => {
    //   ruleForm.value.createDeptId = res.data.id
    //   ruleForm.value.createDeptName = res.data.fullName
    // })
  }
}
onMounted(() => {
  initDialog()
})
// 获取计量标识列表
const meterIdentifyList = ref<{ id: string; value: string; name: string }[]>()
const fetchListData = () => {
  getDictByCode('eqptMeterIdentify').then((res) => {
    meterIdentifyList.value = res.data
  })
}
fetchListData()
// 关闭弹窗
const close = () => {
  $router.back()
}
// 新增
const add = () => {
  editCertificate(ruleForm.value).then((res) => {
    ElMessage.success('新增成功')
    close()
  })
}
// 编辑
const update = () => {
  editCertificate(ruleForm.value).then((res) => {
    ElMessage.success('修改成功')
    close()
  })
}
// 保存
const saveForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then((res) => {
        if (dialogStatus.value === 'create') {
          add()
        }
        else {
          update()
        }
      })
    }
  })
}
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  formEl?.resetFields()
  close()
}
const fileRef = ref() // 文件上传input
const uploadFlag = ref('')
const onFileChange = (event: any) => {
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    fd.append('multipartFile', event.target.files[0])
    uploadApi(fd).then((res) => {
      if (res.code === 200) {
        //  certificateReport  originalRecord
        ruleForm.value[uploadFlag.value] = res.data[0]
        // 重置当前验证
        if (uploadFlag.value === 'certificateReport') {
          ruleFormRef.value?.clearValidate('certificateReport')
        }

        ElMessage.success('文件上传成功')
        fileRef.value.value = ''
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
const upload = (type: string) => {
  uploadFlag.value = type
  fileRef.value.click()
}
// 选择设备
const deviceRef = ref()
const selectDevice = () => {
  deviceRef.value.initDialog()
}
// 确认设备
const confirmDevice = (device: any) => {
  console.log(device, '设备')
  ruleForm.value.equipmentId = device.id
  ruleForm.value.equipmentManufactureNo = device.manufactureNo
  ruleForm.value.equipmentName = device.equipmentName
  ruleForm.value.equipmentNo = device.equipmentNo
  ruleForm.value.meterIdentify = device.meterIdentify
  ruleForm.value.checkDate = device.checkDate
}
// 选择分包方
const subcontractorsRef = ref()
const selectSubcontractors = () => {
  subcontractorsRef.value.initDialog()
}
// 确认分包方
const confirmSubcontractors = (subcontractors: any) => {
  ruleForm.value.subcontractorNo = subcontractors.subcontractorNo
  ruleForm.value.subcontractorName = subcontractors.companyName
  ruleForm.value.subcontractorId = subcontractors.id
}
</script>

<template>
  <app-container style="overflow: hidden;">
    <!-- 分包方弹窗 -->
    <subpackage-dialog ref="subcontractorsRef" @add="confirmSubcontractors" />
    <!-- 设备弹窗 -->
    <device-dialog ref="deviceRef" @add="confirmDevice" />
    <detail-page :title="`分包证书管理-${textMap[dialogStatus]}`">
      <template #btns>
        <el-button v-if="!$route.path.includes('detail')" type="primary" @click="saveForm(ruleFormRef)">
          保存
        </el-button>
        <el-button type="info" @click="resetForm(ruleFormRef)">
          关闭
        </el-button>
      </template>
    </detail-page>
    <detail-block-com>
      <el-form ref="ruleFormRef" :model="ruleForm" :class="$route.path.includes('detail') ? 'isDetail' : ''" :rules="rules" label-position="right" label-width="120px" class="form" :disabled="$route.path.includes('detail')">
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="证书编号" prop="certificateNo">
              <el-input v-model.trim="ruleForm.certificateNo" placeholder="证书编号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="证书名称" prop="certificateName">
              <el-input v-model.trim="ruleForm.certificateName" placeholder="证书名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检测单位编号" prop="subcontractorNo">
              <el-input v-model.trim="ruleForm.subcontractorNo" placeholder="检测单位编号" @focus="selectSubcontractors">
                <template v-if="!$route.path.includes('detail')" #append>
                  <span @click="selectSubcontractors">选择</span>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检测单位名称">
              <el-input v-model.trim="ruleForm.subcontractorName" disabled placeholder="检测单位名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="受检设备编号" prop="equipmentNo">
              <el-input v-model.trim="ruleForm.equipmentNo" placeholder="受检设备编号" @focus="selectDevice">
                <template v-if="!$route.path.includes('detail')" #append>
                  <span @click="selectDevice">选择</span>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="受检设备名称" prop="equipmentName">
              <el-input v-model.trim="ruleForm.equipmentName" disabled placeholder="受检设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出厂编号">
              <el-input v-model.trim="ruleForm.equipmentManufactureNo" disabled placeholder="出厂编号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="型号">
              <el-input v-model.trim="ruleForm.equipmentModel" disabled placeholder="型号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="检定(校准)日期" prop="checkDate">
              <el-date-picker
                v-model="ruleForm.checkDate" type="date" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" placeholder="请选择检定日期" class="normal-date" style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="证书有效期" prop="certificateValid">
              <el-date-picker
                v-model="ruleForm.certificateValid" type="date" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" placeholder="请选择证书有效期" class="normal-date" style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="计量标识" prop="meterIdentify">
              <el-select v-model="ruleForm.meterIdentify" placeholder="选择计量标识" style="width: 100%;">
                <el-option v-for="item in meterIdentifyList" :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="原始记录附件" prop="originalRecord">
              <!-- 上传组件 -->
              <input ref="fileRef" style="display: none;" type="file" @change="onFileChange">
              <show-photo :minio-file-name="ruleForm.originalRecord" />
              <el-button v-if="!$route.path.includes('detail')" type="primary" @click="upload('originalRecord')">
                {{ '上传' }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="24">
            <el-form-item label="证书报告附件" prop="certificateReport">
              <!-- 上传组件 -->
              <input ref="fileRef" style="display: none;" type="file" accept="application/msword,application/pdf" @change="onFileChange">
              <show-photo :minio-file-name="ruleForm.certificateReport" />
              <el-button v-if="!$route.path.includes('detail')" type="primary" @click="upload('certificateReport')">
                {{ '上传' }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-block-com>
  </app-container>
</template>

<style lang="scss" scoped>
// 详情页面隐藏小红点
.isDetail {
  ::v-deep {
    .el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap > .el-form-item__label::before,
    .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label::before {
      content: "";
      display: none;
    }
  }
}
</style>
