<!-- 分包证书管理详情 -->
<script lang="ts" setup name="CertificateEdit">
import type { Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox, formContextKey } from 'element-plus'
import type { FormInstance, UploadUserFile } from 'element-plus'
import { ref } from 'vue'
import dayjs from 'dayjs'
import type { IForm } from './certificate-interface'
import selectSampleDialog from './dialog/selectSampleDialog.vue'
import type { dictType } from '@/global'
import { getDictByCode } from '@/api/system/dict'
import selectReceivedEquipmentDialog from '@/views/business/subpackage/review/dialog/selectReceivedEquipmentDialog.vue'
import type { IList as IOrderList } from '@/views/business/manager/order/order-interface'
import selectOrderDialog from '@/views/business/manager/interchangeReceipt/dialog/selectOrderDialog.vue'
import { getOrderDetail } from '@/api/business/manager/order'
import SelectOutsourcerNoDialog from '@/views/business/subpackage/review/dialog/selectOutsourcerNoDialog.vue'
import showPhoto from '@/components/showPhoto/index.vue'
import { UploadFile } from '@/api/file'
import { addCertificateList, updateCertificateList } from '@/api/business/subpackage/certificate'
// 初始化router
const $router = useRouter()
const $route = useRoute()
const sampleVisible = ref(false) // 控制选择样品对话框显隐
const projectVisible = ref(false) // 控制选择分包方对话框显隐
const textMap: { [key: string]: string } = {
  edit: '编辑',
  add: '新建',
  detail: '详情',
}// 字典
const pageType = ref('add') // 页面类型: add, edit, detail
const loading = ref(false) // 表单加载状态
const infoId = ref('') // id
const form: Ref<IForm> = ref({ // 表单
  id: '',
  certificateNo: '', // 证书号
  certificateName: '', // 证书名称
  outsourcerNo: '', // 检测单位编号
  outsourcerName: '', // 检测单位名称
  outsourcerId: '', // 检测单位id
  sampleId: '', // 受检设备id
  sampleName: '', // 受检设备名称
  sampleNo: '', // 受检设备编号
  model: '', // 型号
  manufactureNo: '', // 出厂编号
  orderId: '', // 任务单id
  orderNo: '', // 任务单编号
  checkDate: '', // 检定(校准)日期
  certificateValid: '', // 证书有效期
  meterIdentify: '', // 计量标识
  certificateReportFile: '', // 证书报告附件
  originalRecordFile: '', // 原始记录文件
})
const ruleFormRef = ref<FormInstance>() // 表单ref
// 校验规则
const rules = ref({
  certificateNo: [{ required: true, message: '证书编号不能为空', trigger: 'blur' }],
  certificateName: [{ required: true, message: '证书名称不能为空', trigger: 'blur' }],
  certificateValid: [{ required: true, message: '证书有效期不能为空', trigger: ['blur, change'] }],
  checkDate: [{ required: true, message: '检定(校准)日期不能为空', trigger: ['blur, change'] }],
  outsourcerName: [{ required: true, message: '检测单位编号不能为空', trigger: ['blur, change'] }],
  sampleNo: [{ required: true, message: '受检设备编号不能为空', trigger: ['blur, change'] }],
  certificateReportFile: [{ required: true, message: '证书报告不能为空', trigger: ['blur, change'] }],
}) // 表单验证规则

// 关闭
const close = () => {
  $router.back()
}

// -----------------------------------------路由参数--------------------------------
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string
  if ($route.params.id) {
    infoId.value = $route.params.id as string
  }
}

// ------------------------------------------选择受检设备---------------------------------------
const selectReceivedEquipmentRef = ref() // 已接收的全部受检设备的组件ref
const selectSampleDialogRef = ref() // 选择任务单下的受检设备的组件ref

// 点击选择样品
const handleSelectSample = () => {
  if (!form.value.orderId) { // 没有任务单编号
    selectReceivedEquipmentRef.value.initDialog(false, '')
  }
  else {
    selectSampleDialogRef.value.initDialog(false, form.value.orderId)
  }
}
// 选好设备
const clickConfirmSample = (val: any) => {
  console.log(val)

  if (val && val.length) {
    if (!form.value.orderId) {
      form.value.sampleId = val[0].id// 受检设备id
      form.value.sampleName = val[0].equipmentName// 受检设备名称
      form.value.sampleNo = val[0].equipmentNo// 受检设备编号
      form.value.model = val[0].equipmentNo// 型号
      form.value.manufactureNo = val[0].manufactureNo// 出厂编号
    }
    else {
      form.value.sampleId = val[0].sampleId// 受检设备id
      form.value.sampleName = val[0].sampleName// 受检设备名称
      form.value.sampleNo = val[0].sampleNo// 受检设备编号
      form.value.model = val[0].sampleModel// 型号
      form.value.manufactureNo = val[0].manufactureNo// 出厂编号
    }
  }
}
// -----------------------------------------选择检测单位------------------------------------------
const selectOutsourcerRef = ref() // 选择任务单组件ref
// 点击选择任务单
const selectOutsourcer = () => {
  selectOutsourcerRef.value.initDialog()
}

// 确定选择分包方
const confirmSelectOutsourcerNo = (val: any) => {
  console.log(val)
  form.value.outsourcerId = val[0].id // 分包方id
  form.value.outsourcerNo = val[0].outsourcerNo // 分包方编号
  form.value.outsourcerName = val[0].outsourcerName // 分包机构名称
}
// --------------------------------------------选择任务单------------------------------------
const selectOrderRef = ref() // 选择任务单组件ref
/**
 * 有任务单的时候选择任务单下的样品、没有任务单选择所有样品
 * 点击选择任务单
 */
const selectOrder = () => {
  selectOrderRef.value.initDialog()
}
// 选好任务单
const clickConfirmOrder = (val: IOrderList[]) => {
  getOrderDetail({ id: val[0].id }).then((res) => {
    form.value.orderNo = res.data.data.orderNo!// 任务单编号
    form.value.orderId = val[0].id// 任务单id
    form.value.sampleId = '' //  受检设备id
    form.value.sampleName = ''//  受检设备名称
    form.value.sampleNo = '' //  受检设备编号
    form.value.model = ''// 型号
    form.value.manufactureNo = ''// 出厂编号
  })
}
// ---------------------------------文件上传-------------------------------------------
const fileRef = ref()
const fileRefCertificate = ref()
const onFileChangeCertificateFile = (event: any) => {
  // 原生上传
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('multipartFile', event.target.files[0])
    UploadFile(fd).then((res) => {
      if (res.code === 200) {
        form.value.certificateReportFile = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
      }
      else {
        ElMessage.error(res.message)
      }
    })
  }
}
const uploadCertificate = () => {
  fileRefCertificate.value.click()
}

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.originalRecordFile = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}
// ------------------------------------------字典----------------------------------------------
const meterIdentifyDict = ref<dictType[]>([]) // 计量标识

/**
 * 获取字典
 */
async function getDict() {
  // 计量标识
  const response = await getDictByCode('bizMeterIdentify')
  meterIdentifyDict.value = response.data
}
// -----------------------------------------------------------------------------------

// 点击保存
const saveForm = () => {
  ruleFormRef.value!.validate((valid: boolean) => {
    if (valid) {
      const loading = ElLoading.service({
        lock: true,
        background: 'rgba(255, 255, 255, 0.8)',
      })
      if (pageType.value === 'add') {
        addCertificateList(form.value).then((res) => {
          ElMessage.success('保存成功')
          pageType.value = 'detail'
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }
      else if (pageType.value === 'edit') {
        // form.value.id = infoId.value
        updateCertificateList(form.value).then((res) => {
          ElMessage.success('保存成功')
          pageType.value = 'detail'
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }
    }
  })
}
onMounted(() => {
  getDict().then(() => {
    if (pageType.value !== 'add') {
      form.value.certificateNo = $route.query.certificateNo as string// 证书号
      form.value.certificateName = $route.query.certificateName as string// 证书名称
      form.value.certificateReportFile = $route.query.certificateReportFile as string// 证书文件
      form.value.originalRecordFile = $route.query.originalRecordFile as string// 原始记录文件
      form.value.outsourcerName = $route.query.outsourcerName as string// 检测单位名称-分包方名称
      form.value.sampleName = $route.query.sampleName as string// 样品名称
      form.value.sampleNo = $route.query.sampleNo as string// 样品编号
      form.value.model = $route.query.sampleModel as string// 型号
      form.value.manufactureNo = $route.query.manufactureNo as string// 出厂编号
      form.value.orderNo = $route.query.orderNo as string// 任务单编号
      form.value.checkDate = $route.query.checkDate as string//  检定(校准)日期
      form.value.certificateValid = $route.query.certificateValid as string// 证书有效期
      form.value.outsourcerNo = $route.query.outsourcerNo as string// 检测单位编号
      form.value.outsourcerId = $route.query.outsourcerId as string// 检测单位id
      form.value.sampleId = $route.query.sampleId as string// 受检设备id
      form.value.orderId = $route.query.orderId as string// 任务单id
      form.value.meterIdentify = $route.query.meterIdentify as string// 计量标识
      form.value.id = $route.query.id as string// id
    }
  })
})
</script>

<template>
  <div>
    <!-- 布局 -->
    <app-container>
      <detail-page v-loading="loading" :title="`分包证书管理-${textMap[pageType]}`">
        <template #btns>
          <el-button v-if="pageType !== 'detail'" type="primary" @click="saveForm">
            保存
          </el-button>
          <el-button type="info" @click="close">
            关闭
          </el-button>
        </template>
        <div id="form">
          <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="证书编号:" prop="certificateNo">
                  <el-input
                    v-model="form.certificateNo"
                    :placeholder="pageType === 'detail' ? '' : '请输入证书编号'"
                    :class="{ 'detail-input': pageType === 'detail' }"
                    :disabled="pageType === 'detail'"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="证书名称:" prop="certificateName">
                  <el-input
                    v-model.trim="form.certificateName"
                    :placeholder="pageType === 'detail' ? '' : '请输入证书名称'"
                    :class="{ 'detail-input': pageType === 'detail' }"
                    :disabled="pageType === 'detail'"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="检测单位编号:" prop="outsourcerName">
                  <el-input
                    v-model="form.outsourcerName"
                    :placeholder="pageType === 'detail' ? '' : '请选择检测单位编号'"
                    :class="{ 'detail-input': pageType === 'detail' }"
                    disabled
                  >
                    <template v-if="pageType !== 'detail'" #append>
                      <el-button size="small" @click="selectOutsourcer">
                        选择
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="检测单位名称:" prop="outsourcerName">
                  <el-input
                    v-model.trim="form.outsourcerName"
                    :placeholder="pageType === 'detail' ? '' : '请输入检测单位名称'"
                    :class="{ 'detail-input': pageType === 'detail' }"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="任务单编号:" prop="orderNo">
                  <el-input
                    v-model.trim="form.orderNo"
                    :placeholder="pageType === 'detail' ? ' ' : '请选择任务单编号'"
                    disabled
                    class="full-width-input"
                    clearable
                  >
                    <template v-if="pageType !== 'detail'" #append>
                      <el-button
                        size="small"
                        @click="selectOrder"
                      >
                        选择
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="受检设备编号:" prop="sampleNo">
                  <el-input
                    v-model="form.sampleNo"
                    :placeholder="pageType === 'detail' ? ' ' : '请选择受检设备'"
                    :class="{ 'detail-input': pageType === 'detail' }"
                    disabled
                  >
                    <template v-if="pageType !== 'detail'" #append>
                      <el-button size="small" @click="handleSelectSample">
                        选择
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="受检设备名称:" prop="sampleName">
                  <el-input
                    v-model="form.sampleName"
                    :placeholder="pageType === 'detail' ? ' ' : '受检设备名称'"
                    :class="{ 'detail-input': pageType === 'detail' }"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="型号:" prop="model">
                  <el-input
                    v-model="form.model"
                    :placeholder="pageType === 'detail' ? ' ' : '型号'"
                    :class="{ 'detail-input': pageType === 'detail' }"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="出厂编号:" prop="manufactureNo">
                  <el-input
                    v-model="form.manufactureNo"
                    :placeholder="pageType === 'detail' ? ' ' : '出厂编号'"
                    :class="{ 'detail-input': pageType === 'detail' }"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="检定(校准)日期:" prop="checkDate">
                  <el-date-picker
                    v-model="form.checkDate"
                    type="date"
                    style="width: 100%;"
                    :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="certificateValid">
                  <el-date-picker
                    v-model="form.certificateValid"
                    type="date"
                    style="width: 100%;"
                    :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" class="marg">
              <el-col :span="24">
                <el-form-item label="原始记录附件:" prop="originalRecordFile">
                  <show-photo v-if="form.originalRecordFile" :minio-file-name="form.originalRecordFile" />
                  <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.originalRecordFile === '' ? '0px' : '20px' }" @click="upload">
                    {{ form.originalRecordFile === '' ? '上传' : '更换附件' }}
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" class="marg">
              <el-col :span="24">
                <el-form-item label="证书报告附件:" prop="certificateReportFile">
                  <show-photo v-if="form.certificateReportFile" :minio-file-name="form.certificateReportFile" />
                  <span v-else-if="pageType === 'detail'">无</span>
                  <input v-show="pageType === ''" ref="fileRefCertificate" type="file" @change="onFileChangeCertificateFile">
                  <el-button v-if="pageType !== 'detail'" id="file" type="primary" :disabled="pageType === 'detail'" :style="{ 'margin-left': form.certificateReportFile === '' ? '0px' : '20px' }" @click="uploadCertificate">
                    {{ form.certificateReportFile === '' ? '上传' : '更换附件' }}
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </detail-page>
      <!-- 选择所有已接收的受检设备组件 -->
      <select-received-equipment-dialog ref="selectReceivedEquipmentRef" :is-multi="false" @confirm="clickConfirmSample" />
      <!-- 选择任务单下的设备  -->
      <select-sample-dialog ref="selectSampleDialogRef" @confirm="clickConfirmSample" />
      <!-- 选择任务单 -->
      <select-order-dialog ref="selectOrderRef" @confirm="clickConfirmOrder" />
      <!-- 选择分包方编号 -->
      <select-outsourcer-no-dialog ref="selectOutsourcerRef" @confirm="confirmSelectOutsourcerNo" />
    </app-container>
  </div>
</template>
