<script lang="ts" setup name="standardListAdd">
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, UploadProps, UploadUserFile } from 'element-plus'
import dayjs from 'dayjs'
import type { ICertification } from './cert-interface'
import { getStaffList } from '@/api/measure/person'
import { getTypeSelect } from '@/api/system/price'
import { UploadFile } from '@/api/measure/file'
import useUserStore from '@/store/modules/user'
import showPhoto from '@/views/system/tool/showPhoto.vue'
import { certificatePrintDetail } from '@/api/business/lab/cert'
const loading = ref(false) // 表单加载状态
const infoId = ref('') // 证书id
const printStatus = ref('') // 可打印状态
const buttonArray = ref<string[]>([]) // 顶部按钮数组
const pageType = ref('add') // 页面类型: add,edit, detail
const buttonLoading = ref(false) // 按钮加载状态

// 从路由中获取页面类型参数
const $route = useRoute()

// 逻辑代码
const dataForm = ref<ICertification>({
  certificationId: '',
  certificationReportCode: '',
  certificationReportName: '',
  certificateReportType: '',
  certificateReportTypeName: '',
  sampleId: '',
  sampleNo: '',
  sampleName: '',
  sampleModel: '',
  manufacturingNo: '',
  orderId: '',
  orderNo: '',
  customerNo: '',
  customerName: '',
  measureCatogory: '',
  measureCatogoryName: '',
  createUser: '',
  createUserName: '',
  printNum: '',
  printStatus: '',
  createTime: '',
  calibrationMajor: '',
  issuanceDate: '',
  signId: '',
  signName: '',
  approvalSignId: '',
  approvalSignName: '',
  certificateReportFile: '',
  originalRecordId: '',
  originalRecordCode: '',
  roomNumber: '',
  temperature: '',
  humidity: '',
  manufacturer: '',
  customerPhone: '',
  customerAddress: '',
  deliverer: '',
  delivererTel: '',
  planDeliverTime: '',
  requireOverTime: '',
  mesureContent: '',
  remark: '',
})

// 下拉框数组类型
interface IOptions {
  id: string
  name: string
  value: string
  organizeName: string
  deptId: string
}
const checkTypeOptions = ref<IOptions[]>([])
const calibrationMajorList = ref<IOptions[]>([]) // 计量专业下拉框
const standardManagerStateList = ref<IOptions[]>([]) // 管理状态下拉框
const standardLevelList = ref<IOptions[]>([]) // 标准等级下拉框
const transmitRangeList = ref<IOptions[]>([]) // 传递范围下拉框
// 标准所在部门下拉框
const standardUsersDeptList = ref<IOptions[]>([])
// 获取下拉框
const getSelectList = (code: string) => {
  getTypeSelect(code).then((res) => {
    if (code === 'calibrationMajor') {
      calibrationMajorList.value = res.data
    }
    else if (code === 'standardManagerState') {
      standardManagerStateList.value = res.data
    }
    else if (code === 'standardLevel') {
      standardLevelList.value = res.data
    }
    else if (code === 'transmitRange') {
      transmitRangeList.value = res.data
    }
    else if (code === 'standardCategory') {
      checkTypeOptions.value = res.data
    }
  })
}
getSelectList('calibrationMajor') // 获取校准专业下拉框
getSelectList('standardManagerState') // 获取管理状态下拉框
getSelectList('standardLevel') // 获取标准等级下拉框
getSelectList('transmitRange') // 获取传递范围下拉框
getSelectList('standardCategory') // 获取类别下拉框
const params = ref({
  director: '',
  meterMajor: '',
  createEndTime: '',
  createstartTime: '',
  organizeName: '',
  organizeNo: '',
  organizeType: '2',
  pdeptId: null,
  offset: 1,
  limit: 999999,
})

// 添加表格弹窗开关
const dialogVisible = ref(false)
// 初始化路由
const $router = useRouter()
// 关闭
const close = () => {
  // emit('close')
  $router.back()
}
// 点击文件预览
const uploadShow = (e: any) => {
  const URL = window.URL || window.webkitURL
  window.open(URL.createObjectURL(e.raw))
}

// 获取详情信息
const getInfo = (id: string | number) => {
  // 详情页面待确认 TODO
  // dataForm.value = {
  //   approvalStatus: '2',
  //   certificateReportCategory: '1,2',
  //   certificateReportCode: 'RIM202303002',
  //   certificateReportFile: '',
  //   certificateReportName: '证书报告名称03',
  //   certificateReportType: '1',
  //   createTime: '2023-03-14T18:28:41',
  //   createUser: '1',
  //   customerAddress: 'ewfewfe ',
  //   customerEmail: '',
  //   customerName: '京东集团',
  //   customerNo: 'wtsc202302080001',
  //   customerPhone: '950618',
  //   deliverer: '张三',
  //   delivererId: '1',
  //   delivererTel: '113652204',
  //   id: '154524246245210210',
  //   isDel: false,
  //   measureContent: '项目4',
  //   measureDeptId: '',
  //   measurePersonId: '1',
  //   measureType: '2',
  //   orderId: '1623234926190817282',
  //   originalRecordId: '1625802150301368321',
  //   originalRecordName: '',
  //   planDeliverTime: '2022-11-29T21:14:50',
  //   printNum: 0,
  //   printStatus: '1',
  //   processId: '',
  //   remark: '',
  //   requireOverTime: '2023-01-29T21:14:50',
  //   sampleId: '1625742343335677953',
  //   sampleName: '测试4',
  //   sampleNo: '',
  //   signId: '',
  //   templateId: '',
  // }
  certificatePrintDetail({ id }).then((res) => {
    dataForm.value = res.data
    dataForm.value.createTime = res.data.createTime.split('T')[0]
  })
}

// 打印证书
const printCert = () => {

}

const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  // 原生上传
  console.log(event.target.files)
  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.certificateReportFile = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
      }
      else {
        ElMessage.error(res.message)
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}

onMounted(() => {
  if ($route.params && $route.params.id) {
    infoId.value = $route.query.id as string
  }
  if ($route.query && $route.query.printStatus) {
    printStatus.value = $route.query.printStatus as string
  }

  if ($route.query && $route.query.pageType) {
    pageType.value = $route.query.pageType as string
  }
  getInfo(infoId.value)
})
</script>

<template>
  <app-container>
    <detail-page title="证书打印">
      <template #btns>
        <el-button v-if="printStatus === '1'" type="primary" @click="printCert">
          打印
        </el-button>
        <el-button type="primary" @click="printCert">
          预览
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <el-form ref="ruleFormRef" :model="dataForm" label-position="right" label-width="auto">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="检校专业:">
              <el-select
                v-model="dataForm.measureType" clearable size="default" class="full-width-input"
                placeholder="" disabled
              >
                <el-option v-for="item in calibrationMajorList" :key="item.name" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出具日期:">
              <el-input v-model="dataForm.createTime" class="full-width-input" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="证书编号:">
              <el-input
                v-model.trim="dataForm.certificateReportCode"
                :placeholder="pageType === 'detail' ? '' : '请输入证书编号'" class="full-width-input" clearable disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="证书报告名称:">
              <el-input
                v-model.trim="dataForm.certificateReportName"
                :placeholder="pageType === 'detail' ? '' : '请输入证书报告名称'" class="full-width-input" clearable disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <!-- 无字段返回 -->
            <el-form-item label="电子签章:">
              <el-input v-model.trim="dataForm.signName" class="full-width-input" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="认可标志专用章:">
              <el-input v-model.trim="dataForm.approvalSignName" class="full-width-input" disabled />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="10">
            <el-form-item label="证书报告附件:" prop="contactInfo">
              <show-photo v-if="dataForm.certificateReportFile" :minio-file-name="dataForm.certificateReportFile" />
              <span v-else>无附件</span>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="原始记录编号:" prop="category">
              <el-input v-model.trim="dataForm.originalRecordCode" class="full-width-input" disabled>
                <template v-if="pageType !== 'detail'" #append>
                  <el-button size="small">
                    查看
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检校地点:" prop="standardLevel">
              <el-input v-model.trim="dataForm.roomNumber" class="full-width-input" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="温度(℃):" prop="transmitRange">
              <el-input v-model.trim="dataForm.temperature" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="相对湿度(%):">
              <el-input v-model.trim="dataForm.humidity" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="样品编号:" prop="preparationDate">
              <el-input v-model.trim="dataForm.sampleNo" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="样品名称:" prop="standardLaboratory">
              <el-input v-model.trim="dataForm.sampleName" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出厂编号:" prop="laboratoryOwner">
              <el-input v-model.trim="dataForm.manufacturingNo" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="型号:" prop="laboratoryOwnerContact">
              <el-input v-model.trim="dataForm.sampleModel" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="生产厂家:" prop="managerState">
              <el-input v-model.trim="dataForm.manufacturer" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="委托方代码:" prop="measureMajor">
              <el-input v-model.trim="dataForm.customerNo" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="委托方名称:" prop="assessmentUnit">
              <el-input v-model.trim="dataForm.customerName" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="委托方电话:" prop="assessDate">
              <el-input v-model.trim="dataForm.customerPhone" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="委托方地址:" prop="uncertainty">
              <el-input v-model.trim="dataForm.customerAddress" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="送检人:" prop="mesureRange">
              <el-input v-model.trim="dataForm.deliverer" class="full-width-input" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式:" prop="mesureRange">
              <el-input v-model.trim="dataForm.delivererTel" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="预计送达时间:" prop="planDeliverTime">
              <el-date-picker
                v-model="dataForm.planDeliverTime" type="datetime" class="full-width-input" clearable
                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="requireOverTime">
              <el-date-picker
                v-model="dataForm.requireOverTime" type="datetime" class="full-width-input"
                format="YYYY-MM-DD hh:mm:ss" clearable value-format="YYYY-MM-DD HH:mm:ss" disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="检定项目:" prop="standardTemperature">
              <el-input v-model.trim="dataForm.mesureContent" class="full-width-input" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="备注:">
              <el-input v-model.trim="dataForm.remark" class="full-width-input" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="证书报告附件:">
              <show-photo v-if="dataForm.certificateReportFile" :minio-file-name="dataForm.certificateReportFile" />
              <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.certificateReportFile === '' ? '0px' : '20px' }" @click="upload"
              >
                {{ dataForm.certificateReportFile === '' ? '上传' : '更换附件' }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
  </app-container>
</template>

<style lang="scss">
.el-upload-list {
  display: none !important;
}
</style>
