<!-- 证书报告检索列表 -->
<script lang="ts" setup name="CertificateReportRetrieval">
import { getCurrentInstance, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import DetailDialog from './detailDialog.vue'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getDictByCode } from '@/api/system/dict'
import { changeCert, getCertificateRetrievalList } from '@/api/business/lab/certificateReportRetrieval'
import { getStaffList } from '@/api/measure/person'
import { getPhotoUrl } from '@/api/system/tool'
import { download } from '@/utils/download'
import { UploadFile } from '@/api/measure/file'

import { certificatePrintDetail, certificatePrintInvalid } from '@/api/business/lab/cert'
import { getUserList } from '@/api/system/user'
import { exportFile } from '@/utils/exportUtils'
const { proxy } = getCurrentInstance() as any
const $router = useRouter() // 初始化路由
// 查询条件
const listQuery = ref({
  offset: 1, // 当前页
  limit: 20, // 每页多少条
  certificateNo: '', // 证书编号
  certificateName: '', // 证书名称
  sampleNo: '', // 样品编号
  sampleName: '', // 样品名称
  sampleModel: '', // 型号
  manufacturingNo: '', // 出厂编号
  orderNo: '', // 委托方编号
  customerName: '', // 委托方名称
  measureType: '', // 校验类别
  measurePersonId: '', // 检定人员
})
// 多选选中
const list = ref<any[]>([]) // 数据列表
const total = ref(0) // 总条数
const loadingTable = ref(false) // 表格loading

// 表头
const columns = ref<TableColumn[]>([
  { text: '证书编号', value: 'certificateNo', align: 'center' },
  { text: '证书名称', value: 'certificateName', align: 'center' },
  // { text: '样品编号', value: 'sampleNo', align: 'center' },
  { text: '样品名称', value: 'sampleName', align: 'center' },
  { text: '型号', value: 'sampleModel', align: 'center' },
  { text: '出厂编号', value: 'manufacturingNo', align: 'center' },
  { text: '委托方编号', value: 'orderNo', align: 'center' },
  { text: '委托方名称', value: 'customerName', align: 'center' },
  { text: '检校类别', value: 'measureTypeName', align: 'center' },
  { text: '检定人员', value: 'measurePersonName', align: 'center' },
])

// 列表数据查询
const fetchData = (isNowPage: boolean) => {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  getCertificateRetrievalList(listQuery.value).then((res) => {
    list.value = res.data.rows
    total.value = res.data.total
    loadingTable.value = false
  })
}

// 搜索
const searchList = () => {
  fetchData(true)
}

// 重置
const clearList = () => {
  listQuery.value = {
    offset: 1, // 当前页
    limit: 20, // 每页多少条
    certificateNo: '', // 证书编号
    certificateName: '', // 证书名称
    sampleNo: '', // 样品编号
    sampleName: '', // 样品名称
    sampleModel: '', // 型号
    manufacturingNo: '', // 出厂编号
    orderNo: '', // 委托方编号
    customerName: '', // 委托方名称
    measureType: '', // 校验类别
    measurePersonId: '', // 检定人员
  }
  fetchData(true)
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    listQuery.value.limit = val.size
  }
  if (val && val.page) {
    listQuery.value.offset = val.page
  }
  fetchData(true)
}
// 获取字典值
const mesureCategoryList = ref<any>([]) // 校检类别
const userList = ref<any[]>([]) // 可使用人列表
async function getDict() {
  // 校检类别
  const response = await getDictByCode('measureCategory')
  mesureCategoryList.value = response.data

  const params = {
    staffNo: '', // 人员编号
    name: '', // 姓名
    deptId: '', // 工作部门
    major: '', // 计量专业
    verifierCertificateNo: '', // 证书号
    certificateStatus: '', // 证书状态
    limit: 100000,
    offset: 1,
  }
  // 获取人员列表
  getStaffList(params).then((res) => {
    userList.value = res.data.records
  })
}
getDict()
onMounted(async () => {
  fetchData(true) // 获取列表数据
})
// 查看详情
const detailRef = ref()
const handleDetail = (row: any) => {
  detailRef.value.initDialog(row.printFileName)
}

// 点击下载
const downloadFile = (row: any) => {
  if (row.printFileName) {
    const loading = ElLoading.service({
      lock: true,
      text: '下载中，请稍后...',
      background: 'rgba(255, 255, 255, 0.6)',
    })
    getPhotoUrl(row.printFileName).then((res) => {
      const fileType = res.data.split('.')[res.data.split('.').length - 1]
      download(res.data, `${row.certificateName}.${fileType}` as string)
      loading.close()
    }).catch(() => {
      ElMessage.error('下载失败')
      loading.close()
    })
  }
  else {
    ElMessage('无可下载内容')
  }
}
// 重检按钮
const recheck = (row: any) => {
  ElMessageBox.confirm(
    '确认需要重检吗?',
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then((res) => {
    certificatePrintDetail({ id: row.id }).then((res) => {
      certificatePrintInvalid({
        orderId: res.data.orderId,
        sampleId: res.data.sampleId,
        // certificateReportCode: res.data.certificateReportCode,
      }).then((res) => {
        ElMessage.success('操作成功')
        fetchData(true)
      })
    })
  })
}

// -----------------------------------------更换证书-------------------------------------------
const fileRef = ref() // 文件上传input
const changeCertificateReportId = ref('')
const onFileChange = (event: any) => {
  // 原生上传
  console.log(event.target.files)
  const files = event.target.files
  if (files.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    for (var i = 0; i < files.length; i++) {
      fd.append('multipartFile', files[i])
    }
    const loading = ElLoading.service({
      lock: true,
      text: '加载中...',
      background: 'rgba(255, 255, 255, 0.6)',
    })
    UploadFile(fd).then((res) => {
      if (res.code === 200) {
        // ElMessage.success('文件上传成功')
        event.target.value = ''
        const params = {
          minioFileName: res.data[0],
          certificatePrintId: changeCertificateReportId.value,
        }
        changeCert(params).then(() => {
          ElMessage.success('更换证书成功')
          loading.close()
        }).catch(() => {
          ElMessage.warning('文件上传失败')
          loading.close()
        })
      }
      else {
        ElMessage.error(res.message)
      }
    }).catch(() => {
      ElMessage.warning('文件上传失败')
      loading.close()
    })
  }
}
const upload = () => {
  fileRef.value.click()
}
// 点击更换证书
const clickChangeCert = (row: any) => {
  changeCertificateReportId.value = row.id
  upload()
}
// -------------------------------------------------------------------------------------------------
</script>

<template>
  <app-container>
    <!-- 证书预览 -->
    <detail-dialog ref="detailRef" />
    <search-area :need-clear="true" @search="searchList" @clear="clearList">
      <search-item>
        <el-input
          v-model.trim="listQuery.certificateNo"
          placeholder="证书号"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.certificateName"
          placeholder="证书名称"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.sampleName"
          placeholder="样品名称"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.sampleModel"
          placeholder="型号"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.manufacturingNo"
          placeholder="出厂编号"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.orderNo"
          placeholder="委托单编号"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.customerName"
          placeholder="委托方名称"
          clearable
        />
      </search-item>
      <search-item>
        <el-select
          v-model="listQuery.measureType"
          placeholder="请选择检校类别"
          style="width: 195px;"
          clearable
        >
          <el-option
            v-for="item in mesureCategoryList"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </search-item>
      <search-item>
        <!-- <el-input
          v-model.trim="listQuery.measurePersonId"
          placeholder="检定人员"
          clearable
        /> -->
        <el-select
          v-model="listQuery.measurePersonId" filterable clearable placeholder="检定人员"
        >
          <el-option v-for="(item) in userList" :key="item.id" :label="item.name" :value="item.id">
            <span style="float: left;">{{ item.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px;">{{ item.deptName }}</span>
          </el-option>
        </el-select>
      </search-item>
    </search-area>
    <table-container>
      <normal-table
        :data="list"
        :total="total"
        :columns="columns"
        :query="listQuery"
        :list-loading="loadingTable"
        :is-showmulti-select="false"
        @change="changePage"
      >
        <template #preColumns>
          <el-table-column label="序号" width="55" align="center">
            <template #default="scope">
              {{ (listQuery.offset - 1) * listQuery.limit + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
        <template #columns>
          <el-table-column label="证书状态" align="center">
            <template #default="{ row }">
              <el-tag v-if="row.printStatusName === '作废'" type="danger">
                {{ row.printStatusName }}
              </el-tag>
              <el-tag v-else type="primary">
                {{ row.printStatusName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180" fixed="right">
            <template #default="{ row }">
              <!-- <el-button
                size="small"
                link
                type="primary"
                @click="handleDetail(row)"
              >
                查看
              </el-button> -->
              <el-button
                size="small"
                link
                type="primary"
                @click="downloadFile(row)"
              >
                下载
              </el-button>

              <el-button
                v-if="proxy.hasPerm('/schedule/certPrint/changeCert')"
                size="small"
                link
                type="primary"
                @click="clickChangeCert(row)"
              >
                更换证书
              </el-button>

              <el-button v-if="proxy.hasPerm('/schedule/certPrint/recheck')" size="small" :disabled="row.printStatusName === '作废'" link type="primary" @click="recheck(row)">
                重检
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
    <input v-show="false" ref="fileRef" type="file" name="upload" multiple @change="onFileChange">
  </app-container>
</template>
