<!-- 分包证书管理详情 -->
<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 selectSample from './components/selectSample.vue'
import showPhoto from '@/views/system/tool/showPhoto.vue'
import TemplateTable from '@/views/customer/customerInfo/templateTable.vue'
import { UploadFile } from '@/api/measure/file'
import selectProjectApprove from '@/views/business/subpackage/apply/components/selectProjectApprove.vue'
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 dataForm: Ref<IForm> = ref({
  id: '', // 主键--编辑使用
  certificateCode: '', // 证书号
  certificateName: '', // 证书名称
  // expirationDate: '', // 证书有效期
  // issuanceDate: '', // 证书出具日期
  certificateFile: '', // 证书文件
  originalRecordFile: '', // 原始记录文件
  orderId: '', // 委托书id
  outsourcerId: '', // 分包方id
  outsourcerName: '', // 检测单位名称-分包方名称
  outsourcerNo: '', // 分包方编号
  sampleId: '', // 样品id
  sampleName: '', // 样品名称
  sampleNo: '', // 样品编号
  sampleModel: '', // 型号
  manufacturingNo: '', // 出厂编号
})// 表单
const ruleFormRef = ref<FormInstance>() // 表单ref
// 校验规则
const rules = ref({
  // sampleModel: [{ required: true, message: '样品型号必填', trigger: 'blur' }],
  // manufacturingNo: [{ required: true, message: '出厂编号必填', trigger: 'blur' }],
  certificateCode: [{ required: true, message: '证书编号必填', trigger: 'blur' }],
  certificateName: [{ required: true, message: '证书名称必填', trigger: 'blur' }],
  // expirationDate: [{ required: true, message: '证书有效期必填', trigger: 'blur, change' }],
  // issuanceDate: [{ required: true, message: '证书出具日期必填', trigger: 'blur, change' }],
  outsourcerName: [{ required: true, message: '样检测单位名称必填', trigger: 'blur, change' }],
  sampleNo: [{ required: true, message: '样品编号必填', trigger: 'blur, change' }],
  // originalRecordFile: [{ required: true, message: '原始记录必填', trigger: 'blur, change' }],
  certificateFile: [{ 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 handleSelectSample = () => {
  if (!dataForm.value.outsourcerName) {
    ElMessage.warning('请先选择检测单位')
    return
  }
  sampleVisible.value = true // 选择样品对话框显隐
}
// 修改委托方对话框显隐
const changeSampleVisible = (val: boolean) => {
  sampleVisible.value = val
}
// 选好样品
const clickConfirmSample = (val: any) => {
  dataForm.value.sampleId = val[0].sampleId || val[0].id // 样品id
  dataForm.value.sampleName = val[0].sampleName // 样品名称
  dataForm.value.sampleNo = val[0].sampleNo // 样品编号
  dataForm.value.sampleModel = val[0].sampleModel // 型号
  dataForm.value.manufacturingNo = val[0].manufacturingNo // 出厂编号
  dataForm.value.orderId = val[0].orderId // 委托书id
}
// -----------------------------------------选择分包方------------------------------------------
// 修改项目选择对话框显隐
const changeProjectVisible = (val: boolean) => {
  projectVisible.value = val
}
// 点击选择分包方
const handleSelectOutsourcer = () => {
  projectVisible.value = true // 选择分包方对话框显隐
}
// 选择分好包方
const clickConfirmProject = (val: any) => {
  dataForm.value.outsourcerId = val[0].id // 分包方id
  dataForm.value.outsourcerNo = val[0].outsourcerNo // 分包方编号
  dataForm.value.outsourcerName = val[0].outsourcerName // 公司名称
  console.log(dataForm.value.outsourcerNo)
  // 清空样品信息
  dataForm.value.sampleId = '' // 样品id
  dataForm.value.sampleName = '' // 样品名称
  dataForm.value.sampleNo = '' // 样品编号
  dataForm.value.sampleModel = '' // 型号
  dataForm.value.manufacturingNo = '' // 出厂编号
  dataForm.value.orderId = '' // 委托书id
}
// ---------------------------------------------------------------------------------------
// ---------------------------------文件上传-------------------------------------------
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) {
        dataForm.value.certificateFile = 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) {
        dataForm.value.originalRecordFile = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}
// -----------------------------------------------------------------------------------

// 点击保存
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(dataForm.value).then((res) => {
          ElMessage.success('保存成功')
          close()
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }
      else if (pageType.value === 'edit') {
        dataForm.value.id = infoId.value
        updateCertificateList(dataForm.value).then((res) => {
          ElMessage.success('保存成功')
          close()
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }
    }
  })
}
onMounted(() => {
  if (pageType.value !== 'add') {
    dataForm.value.certificateCode = $route.query.certificateCode as string// 证书号
    dataForm.value.certificateName = $route.query.certificateName as string// 证书名称
    dataForm.value.certificateFile = $route.query.certificateFile as string// 证书文件
    dataForm.value.originalRecordFile = $route.query.originalRecordFile as string// 原始记录文件
    dataForm.value.outsourcerName = $route.query.outsourcerName as string// 检测单位名称-分包方名称
    dataForm.value.sampleName = $route.query.sampleName as string// 样品名称
    dataForm.value.sampleNo = $route.query.sampleNo as string// 样品编号
    dataForm.value.sampleModel = $route.query.sampleModel as string// 型号
    dataForm.value.manufacturingNo = $route.query.manufacturingNo as string// 出厂编号
  }
})
</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="dataForm"
            :label-width="120"
            label-position="right"
            :rules="rules"
          >
            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item label="证书编号:" prop="certificateCode">
                  <el-input
                    v-model="dataForm.certificateCode"
                    :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="dataForm.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="expirationDate">
                  <el-date-picker
                    v-model="dataForm.expirationDate"
                    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="issuanceDate">
                  <el-date-picker
                    v-model="dataForm.issuanceDate"
                    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="outsourcerName">
                  <el-input
                    v-model="dataForm.outsourcerName"
                    :placeholder="pageType === 'detail' ? '' : '请选择检测单位'"
                    :class="{ 'detail-input': pageType === 'detail' }"
                    disabled
                  >
                    <template v-if="pageType !== 'detail'" #append>
                      <el-button size="small" @click="handleSelectOutsourcer">
                        选择
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="样品编号:" prop="sampleNo">
                  <el-input
                    v-model="dataForm.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="dataForm.sampleName"
                    placeholder="样品名称"
                    :class="{ 'detail-input': pageType === 'detail' }"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="样品型号:" prop="sampleModel">
                  <el-input
                    v-model="dataForm.sampleModel"
                    placeholder="样品型号"
                    :class="{ 'detail-input': pageType === 'detail' }"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="出厂编号:" prop="manufacturingNo">
                  <el-input
                    v-model="dataForm.manufacturingNo"
                    placeholder="出厂编号"
                    :class="{ 'detail-input': pageType === 'detail' }"
                    disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" class="marg">
              <el-col :span="14">
                <el-form-item label="原始记录附件:" prop="originalRecordFile">
                  <show-photo v-if="dataForm.originalRecordFile" :minio-file-name="dataForm.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': dataForm.originalRecordFile === '' ? '0px' : '20px' }" @click="upload">
                    {{ dataForm.originalRecordFile === '' ? '上传' : '更换附件' }}
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" class="marg">
              <el-col :span="14">
                <el-form-item label="证书报告附件:" prop="certificateFile">
                  <show-photo v-if="dataForm.certificateFile" :minio-file-name="dataForm.certificateFile" />
                  <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': dataForm.certificateFile === '' ? '0px' : '20px' }" @click="uploadCertificate">
                    {{ dataForm.certificateFile === '' ? '上传' : '更换附件' }}
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </detail-page>
      <!-- 项目选择 -->
      <select-project-approve
        v-model:visible="projectVisible" @clickConfirmProject="clickConfirmProject"
        @change-visible="changeProjectVisible(false)"
      />
      <!-- 样品增加弹窗 -->
      <select-sample v-model:visible="sampleVisible" :outsourcer-id="dataForm.outsourcerId" :customer-no="dataForm.outsourcerNo" :is-multi="false" @click-confirm-sample="clickConfirmSample" @change-visible="changeSampleVisible" />
    </app-container>
  </div>
</template>
