<!-- 分包证书管理列表 -->
<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 { 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 { deleteCertificateList, exportCertificateList, getCertificateList } from '@/api/business/subpackage/certificate'
const $router = useRouter()
const { proxy } = getCurrentInstance() as any
// 查询条件
const listQuery: Ref<IListQuery> = ref({
  certificateNo: '', // 证书号
  certificateName: '', // 证书名称
  createTimeEnd: '', // 创建时间(结束)
  createTimeStart: '', // 创建时间(开始)
  outsourcerName: '', // 分包方名称
  sampleName: '', // 样品名称
  sampleNo: '', // 样品编号
  offset: 1,
  limit: 20,
})
const loadingTable = ref(false)
const dateRange = ref<[DateModelType, DateModelType]>(['', '']) // 筛选时间段数据
const columns = ref<TableColumn[]>([// 表头
  { text: '证书编号', value: 'certificateNo', align: 'center', width: '160' },
  { text: '证书名称', value: 'certificateName', align: 'center' },
  { text: '受检设备编号', value: 'sampleNo', align: 'center', width: '160p' },
  { text: '受检设备名称', value: 'sampleName', align: 'center' },
  { text: '型号', value: 'model', align: 'center' },
  { text: '出厂编号', value: 'manufactureNo', align: 'center' },
  { text: '检测单位', value: 'outsourcerName', align: 'center' },
  { text: '创建时间', value: 'createTime', align: 'center', width: '180' },
])
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
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  })
}
// 搜索
const searchList = () => {
  fetchData(true)
}

// 清除条件
const clearList = () => {
  listQuery.value = {
    certificateNo: '', // 证书号
    certificateName: '', // 证书名称
    createTimeEnd: '', // 创建时间(结束)
    createTimeStart: '', // 创建时间(开始)
    outsourcerName: '', // 分包方名称
    sampleName: '', // 样品名称
    sampleNo: '', // 样品编号
    offset: 1,
    limit: 20,
  }
  dateRange.value = ['', '']
  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 = {
      certificateNo: listQuery.value.certificateNo, // 证书号
      certificateName: listQuery.value.certificateName, // 证书名称
      createTimeEnd: listQuery.value.createTimeEnd, // 创建时间(结束)
      createTimeStart: listQuery.value.createTimeStart, // 创建时间(开始)
      outsourcerName: listQuery.value.outsourcerName, // 分包方名称
      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])
      loading.close()
      exportFile(blob, '分包证书管理.xlsx')
    })
  }
  else {
    loading.close()
    ElMessage.warning('无数据可导出数据')
  }
}
// 打印
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: `certificate/${type}/${row.id}`,
    query: {
      certificateNo: row.certificateNo, // 证书号
      certificateName: row.certificateName, // 证书名称
      certificateValid: row.certificateValid, // 证书有效期
      checkDate: row.checkDate, // 检定(校准)日期
      certificateReportFile: row.certificateReportFile, // 证书文件
      originalRecordFile: row.originalRecordFile, // 原始记录文件
      sampleName: row.sampleName, // 样品名称
      sampleNo: row.sampleNo, // 样品编号
      sampleModel: row.model, // 型号
      manufactureNo: row.manufactureNo, // 出厂编号
      orderNo: row.orderNo, // 任务单编号
      outsourcerNo: row.outsourcerNo, // 检测单位编号
      outsourcerName: row.outsourcerName, // 检测单位名称-分包方名称
      outsourcerId: row.outsourcerId, // 检测单位id
      sampleId: row.sampleId, // 受检设备id
      orderId: row.orderId, // 任务单id
      meterIdentify: row.meterIdentify, // 计量标识
      id: row.id,
    },
  })
}

// 点击新建
const add = () => {
  $router.push({
    path: 'certificate/add',
  })
}
// 模板下载
const downloadTemplate = () => {
  ElMessage.info('敬请期待')
}
// 导入
const importFile = () => {
  ElMessage.info('敬请期待')
}

// 删除
const del = (row: IList) => {
  ElMessageBox.confirm(
    '确认删除吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      deleteCertificateList({ id: row.id }).then((res) => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        fetchData(true)
      })
    })
}
watch(dateRange, (val) => {
  if (val) {
    listQuery.value.createTimeEnd = `${val[0]}`
    listQuery.value.createTimeStart = `${val[1]}`
  }
  else {
    listQuery.value.createTimeEnd = ''
    listQuery.value.createTimeStart = ''
  }
})
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.certificateNo" 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.sampleName" placeholder="受检设备名称" class="short-input" clearable />
        </search-item>
        <search-item>
          <el-input v-model.trim="listQuery.outsourcerName" placeholder="检测单位" class="short-input" clearable />
        </search-item>
        <search-item>
          <el-date-picker
            v-model="dateRange"
            class="short-input"
            type="datetimerange"
            range-separator="至"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            start-placeholder="创建时间(开始)"
            end-placeholder="创建时间(结束)"
          />
        </search-item>
      </search-area>
      <table-container>
        <template #btns-right>
          <icon-button icon="icon-import" title="批量导入" type="primary" @click="importFile" />
          <icon-button icon="icon-template" title="模板下载" type="primary" @click="downloadTemplate" />
          <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="120">
              <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="danger" @click="del(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
  </div>
</template>
