<!-- 分包证书管理列表 -->
<script lang="ts" setup name="CertificateList">
import type { Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { DateModelType } from 'element-plus'
import type { IListQueryRecord } from '../subpackage-interface'
import type { IList, IListQuery } from './certificate-interface'
import { printJSON, printPdf } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { SCHEDULE } from '@/utils/scheduleDict'
import { getPhotoUrl } from '@/api/system/tool'
import filePreviewDialog from '@/views/business/schedule/certPrint/components/filePreviewDialog.vue'
import { delCertificate, exportcertificateList, getcertificateList } from '@/api/business/subpackage/certificate'
import { keepSearchParams, renewSearchParams } from '@/utils/keepQuery'
const $router = useRouter()
const { proxy } = getCurrentInstance() as any
// 查询条件
const listQuery: Ref<IListQuery> = ref({
  certificateCode: '', // 证书号
  certificateName: '', // 证书名称
  outsourcerId: '', // 检测单位,分包方id
  printStatus: '', // 打印状态（1已打印、0未打印，不传为查询全部）
  sampleName: '', // 样品名称
  sampleNo: '', // 样品编号
  manufacturingNo: '', // 出厂编号
  offset: 1,
  limit: 20,
})
// 页面跳转之前保存参数
onBeforeRouteLeave((to: any) => {
  keepSearchParams(to.path, 'subpackage-certificate', listQuery.value)
})
// 重新赋值
listQuery.value = renewSearchParams('subpackage-certificate') || {
  certificateCode: '', // 证书号
  certificateName: '', // 证书名称
  outsourcerId: '', // 检测单位,分包方id
  printStatus: '', // 打印状态（1已打印、0未打印，不传为查询全部）
  sampleName: '', // 样品名称
  sampleNo: '', // 样品编号
  manufacturingNo: '', // 出厂编号
  offset: 1,
  limit: 20,
}
const printFileName = ref('') // 文件名称
const printStatusList = [
  {
    name: '未打印',
    value: '0',

  },
  {
    name: '已打印',
    value: '1',
  },
]
const loadingTable = ref(false)
// 表头
const columns = ref<TableColumn[]>([
  { text: '证书编号', value: 'certificateCode', align: 'center', width: '160px' },
  { text: '证书名称', value: 'certificateName', align: 'center' },
  { text: '样品编号', value: 'sampleNo', align: 'center', width: '160px' },
  { text: '样品名称', value: 'sampleName', align: 'center' },
  { text: '型号', value: 'sampleModel', align: 'center' },
  { text: '出厂编号', value: 'manufacturingNo', align: 'center' },
  { text: '检测单位', value: 'outsourcerName', align: 'center' },
  // { text: '打印状态', value: 'printStatusName', align: 'center' },
  { text: '创建时间', value: 'createTime', align: 'center', width: '180px' },
])
const list = ref<IList[]>([]) // 表格数据
const total = ref(0) // 数据总数
const checkoutList = ref<string[]>([]) // 选中的内容

// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  // if (!isNowPage) {
  //   // 是否显示当前页，否则跳转第一页
  //   listQuery.value.offset = 1
  // }
  // 模拟数据
  getcertificateList(listQuery.value).then((response) => {
    list.value = response.data.rows.map((item: IList) => {
      return {
        ...item,
        printStatusName: item.printStatus == 0 ? '未打印' : item.printStatus == 1 ? '已打印' : '',
      }
    })
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  })
}
// 搜索
const searchList = () => {
  fetchData(true)
}

// 清除条件
const clearList = () => {
  listQuery.value = {
    certificateCode: '', // 证书号
    certificateName: '', // 证书名称
    manufacturingNo: '', // 出厂编号
    outsourcerId: '', // 检测单位,分包方id
    printStatus: '', // 打印状态（1已打印、0未打印，不传为查询全部）
    sampleName: '', // 样品名称
    sampleNo: '', // 样品编号
    offset: 1,
    limit: 20,
  }
  fetchData(true)
}

// 多选发生改变时
function handleSelectionChange(e: any) {
  checkoutList.value = e.map((item: { id: string }) => item.id)
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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 exportAll = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const params = {
      certificateCode: listQuery.value.certificateCode, // 证书号
      certificateName: listQuery.value.certificateName, // 证书名称
      manufacturingNo: listQuery.value.manufacturingNo, // 出厂编号
      outsourcerId: listQuery.value.outsourcerId, // 检测单位,分包方id
      printStatus: listQuery.value.printStatus, // 打印状态（1已打印、0未打印，不传为查询全部）
      sampleName: listQuery.value.sampleName, // 样品名称
      sampleNo: listQuery.value.sampleNo, // 样品编号
      offset: 1,
      limit: 20,
      ids: checkoutList.value,
    }
    exportcertificateList(params).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, '分包证书列表.xlsx')
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  loading.close()
}
// 打印
const printList = () => {
  // 打印列
  const properties = columns.value.map((item) => {
    return {
      field: item.value,
      displayName: item.text,
    }
  })
  if (checkoutList.value.length <= 0 && list.value.length > 0) {
    printJSON(list.value, properties, '分包证书列表')
  }
  else if (checkoutList.value.length > 0) {
    const printList = list.value.filter((item: IList) => checkoutList.value.includes(item.id))
    printJSON(printList, properties, '分包证书列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}

// 点击编辑或详情
const handleDetail = (row: any, type: 'edit' | 'detail') => {
  $router.push({
    path: `/subpackage/${type}/${row.id}`,
    query: {
      certificateCode: row.certificateCode, // 证书号
      certificateName: row.certificateName, // 证书名称
      expirationDate: row.expirationDate, // 证书有效期
      issuanceDate: row.issuanceDate, // 证书出具日期
      certificateFile: row.certificateFile, // 证书文件
      originalRecordFile: row.originalRecordFile, // 原始记录文件
      outsourcerName: row.outsourcerName, // 检测单位名称-分包方名称
      sampleName: row.sampleName, // 样品名称
      sampleNo: row.sampleNo, // 样品编号
      sampleModel: row.sampleModel, // 型号
      manufacturingNo: row.manufacturingNo, // 出厂编号
    },
  })
}

// 点击新建
const add = (row: IList) => {
  $router.push({
    path: '/subpackage/add',
  })
}

// 点击表格中的打印
const print = (row: IList) => {
  getPhotoUrl(row.printFileName as string).then((res) => {
    const url = res.data
    printPdf(url)
  })
}
const filePreviewDialogRef = ref() // 预览弹窗ref

// 查看证书
const checkCertificate = (row: any) => {
  filePreviewDialogRef.value.initDialog(row.certificateFile)
}

// 删除
const del = (row: any) => {
  ElMessageBox.confirm(
    '确认删除吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      delCertificate({ id: row.id }).then((res) => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        fetchData(true)
      })
    })
}

onMounted(async () => {
  fetchData()
})
</script>

<template>
  <div>
    <!-- 布局 -->
    <app-container>
      <search-area :need-clear="true" @search="searchList" @clear="clearList">
        <search-item>
          <el-input v-model.trim="listQuery.certificateCode" placeholder="证书编号" class="short-input" clearable />
        </search-item>
        <search-item>
          <el-input v-model.trim="listQuery.certificateName" placeholder="证书名称" class="short-input" clearable />
        </search-item>
        <!-- <search-item>
          <el-input v-model.trim="listQuery.sampleNo" placeholder="样品编号" class="short-input" clearable />
        </search-item> -->
        <search-item>
          <el-input v-model.trim="listQuery.manufacturingNo" placeholder="出厂编号" class="short-input" clearable />
        </search-item>
        <search-item>
          <el-input v-model.trim="listQuery.sampleName" placeholder="样品名称" class="short-input" clearable />
        </search-item>
        <search-item>
          <el-input v-model.trim="listQuery.outsourcerId" placeholder="检测单位" class="short-input" clearable />
        </search-item>
      </search-area>
      <table-container>
        <template #btns-right>
          <!-- <icon-button icon="icon-import" title="批量导入" type="primary" /> -->
          <!-- <icon-button icon="icon-template" title="模板下载" type="primary" /> -->
          <icon-button icon="icon-add" title="新建" type="primary" @click="add" />
          <icon-button icon="icon-export" title="导出" type="primary" @click="exportAll" />
          <icon-button icon="icon-print" title="打印" type="primary" @click="printList" />
        </template>
        <normal-table
          :data="list" :total="total" :columns="columns" :query="listQuery" :list-loading="loadingTable"
          is-showmulti-select @change="changePage" @multi-select="handleSelectionChange"
        >
          <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" fixed="right" width="200">
              <template #default="{ row }">
                <el-button size="small" link type="primary" @click="handleDetail(row, 'edit')">
                  编辑
                </el-button>
                <el-button size="small" link type="primary" @click="handleDetail(row, 'detail')">
                  详情
                </el-button>
                <el-button size="small" link type="primary" @click="checkCertificate(row)">
                  查看证书
                </el-button>
                <el-button size="small" link type="danger" @click="del(row)">
                  删除
                </el-button>
                <!-- <el-button size="small" link type="primary" @click="print(row)">
                  打印
                </el-button> -->
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
    <file-preview-dialog ref="filePreviewDialogRef" />
  </div>
</template>
