<!-- 证书管理列表 -->
<script name="BusinessCertManageList" lang="ts" setup>
import { getCurrentInstance, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
// import { Row } from 'element-plus/es/components/table-v2/src/components'
// import VuePdfEmbed from 'vue-pdf-embed'
// import * as pdfjsLib from 'pdfjs-dist'
// import print from 'vue3-print-nb'
import type { DateModelType } from 'element-plus'
import type { ICerPrintList, ICertPrintSearch } from './cert-interface'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { printJSON, printPdf } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'
import { getDictByCode } from '@/api/system/dict'
// import { exportCert, getCertList, submitApproval } from '@/api/business/lab/cert'
import { SCHEDULE } from '@/utils/scheduleDict'
import type { dictType } from '@/global'
import ButtonBox from '@/components/buttonBox/buttonBox.vue'
import type { IMenu } from '@/components/buttonBox/buttonBox'
import { changePrintStatus, getPdfStream, getPhotoUrl } from '@/api/system/tool'
import { download } from '@/utils/download'
const { proxy } = getCurrentInstance() as any
const $router = useRouter()
const pdfUrl = ref('')
const buttonBoxActive = 'CertPrint' // 存储在sessionstorage里面的字段名，用于记录右上角buttonbox点击状态
// 右上角按钮
const menu = ref<IMenu[]>([]) // 右上角审批状态按钮组合
const active = ref('') // 选中的按钮
const activeTitle = ref('') // active对应的审批状态名字
const dateRange = ref<[DateModelType, DateModelType]>(['', ''])// 筛选时间段数据
// 查询条件
const listQuery = ref<ICertPrintSearch>({
  certificateNo: '', // 证书编号
  createUserId: 0,
  printStatus: '', // 可打印(证书可打印传0,全部传null)
  orderNo: '', // 委托书编号
  customerName: '', // 委托方名称
  sampleNo: '', // 样品编号
  sampleName: '', // 样品名称
  certificateClass: '', // 证书类型
  printNum: '', // 打印次数 -未打印和全部用
  approvalStatus: active.value, // 审批状态-审批查询用
  orderId: '', // 委托书id
  reason: '', // 操作原因
  sampleId: '', // 样品id
  status: '', // 状态变更(无需检测状态7,收入状态2,归还6，回退状态2.5.1,终止5)
  formId: SCHEDULE.CERTIFICATE_PRINT_APPROVAL,
  startTime: '', // 开始时间
  endTime: '', // 结束时间
  ids: null, // 设置默认值
  offset: 1,
  limit: 20,
})

// 表头
const columns = ref<TableColumn[]>([
  { text: '证书编号', value: 'certificateNo', width: '140', align: 'center' },
  { text: '证书名称', value: 'certificateName', align: 'center' },
  { text: '样品编号', value: 'sampleNo', width: '160', align: 'center' },
  { text: '样品名称', value: 'sampleName', align: 'center' },
  { text: '型号', value: 'sampleModel', align: 'center' },
  { text: '出厂编号', value: 'manufacturingNo', align: 'center' },
  { text: '委托书编号', value: 'orderNo', width: '160', align: 'center' },
  { text: '检校类别', value: 'measureTypeName', width: '120', align: 'center' },
  { text: '检定人员', value: 'measurePersonName', align: 'center' },
  { text: '证书类型', value: 'certificateTypeName', align: 'center' },
  // { text: '打印状态', value: 'printNum', align: 'center', width: '85px', filter: (row: ICerPrintList) => { var cnum = ['未打印', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']; return row.printNum == 0 ? '未打印' : `${cnum[parseInt(row.printNum as string)]}次打印` } },
  { text: '打印状态', value: 'printStatusName', align: 'center', width: '85' },
  { text: '生成时间', value: 'createTime', align: 'center', width: '180' },
])
// 表格数据
const list = ref<ICerPrintList[]>([])
// 总数
const total = ref(0)
// 表格加载状态
const loadingTable = ref(false)
// 选中的内容
const checkoutList = ref<string[]>([])

// --------------------------------------字典---------------------------------------------
function getDict() {
  loadingTable.value = true
  // 制作右上角的菜单
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve, reject) => {
    const data1 = await getDictByCode('printStatus').then((response) => {
      return response.data
    })
    const data2 = await getDictByCode('approvalStatus').then((response) => {
      return response.data.filter((item: dictType) => item.name != '可打印')
    })
    const _data = [...data1, ...data2]
    _data.forEach((item: dictType) => {
      if (item.name === '可打印' || item.name === '全部' || item.name === '待审批' || item.name === '已通过' || item.name === '未通过') {
        if (item.name === '可打印') {
          active.value = item.value
          activeTitle.value = item.name
          menu.value.unshift({
            name: item.name,
            id: `${item.value}`,
          })
        }
        else {
          menu.value.push({
            name: item.name,
            id: `${item.value}`,
          })
        }
      }
    })
    if (window.sessionStorage.getItem(buttonBoxActive)) {
      active.value = window.sessionStorage.getItem(buttonBoxActive) as string
    }
    else {
      active.value = menu.value.find(item => item.name === '可打印')!.id as string// 可打印
    }
  })
}
// -----------------------------------------列表数据---------------------------------------------

// 根据过滤查询条件
function filterQuery() {
  const StatusFlag = activeTitle.value == '可打印'
  const value = menu.value.find(item => item.name === activeTitle.value)!.id as string
  if (StatusFlag) {
    listQuery.value.printStatus = value as string
    listQuery.value.approvalStatus = null
  }
  // else {
  //   listQuery.value.printStatus = ''
  //   listQuery.value.approvalStatus = value as string == '0' ? null : value as string
  // }
}

// 数据查询
function fetchData(isNowPage = false) {
  filterQuery()
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  // 模拟数据
  loadingTable.value = false
  // getCertList(listQuery.value).then((response) => {
  //   list.value = response.data.rows
  //   total.value = parseInt(response.data.total)
  //   loadingTable.value = false
  // })
  list.value = [
    {
      certificationId: 'test', // 证书id
      certificationReportCode: 'test', // 证书编号
      certificationReportName: 'test', // 证书名称
      certificateReportType: 'test', // 证书类型
      certificateReportTypeName: 'test', // 证书类型
      sampleNo: 'test', // 样品编号
      sampleName: 'test', // 样品名称
      sampleModel: 'test', // 型号
      manufacturingNo: 'test', // 出厂编号
      orderId: 'test', // 委托书id
      orderNo: 'test', // 委托书编号
      customerNo: 'test', // 客户编号
      customerName: 'test', // 客户名称
      measureCatogory: 'test', // 检校类别
      measureCatogoryName: 'test', // 检校类别
      crateUserName: 'test', // 检定人员
      printNum: 'test', // 打印状态-打印次数
      printStatus: 'test', // 可打印状态 0不可打印1可打印
      printStatusName: 'test', // 可打印状态 0不可打印1可打印
      createTime: 'test', // 生成时间
      approvalStatus: 'test', // 审批状态
      approvalStatusName: 'test', // 审批状态
      printFileName: 'test', // 文件名称
      taskId: 'test', // 任务id
      id: 'test', // 主键
      reason: 'test', // 操作原因
      sampleId: 'test', // 样品id
      status: 'test', // 状态变更(无需检测状态7,收入状态2,归还6，回退状态2.5.1,终止5)
      processId: 'test', // 流程实例id
      decisionItem: 'test', // 控制同意、驳回、拒绝按钮
    },
  ]
}
// 多选发生改变时
function handleSelectionChange(e: any) {
  checkoutList.value = e.map((item: { id: string }) => item.id)
}

// 点击搜索
const searchList = () => {
  fetchData(true)
}
// 点击重置
const clearList = () => {
  listQuery.value = {
    certificateNo: '', // 证书编号
    createUserId: 0,
    printStatus: '', // 可打印(证书可打印传0,全部传null)
    orderNo: '', // 委托书编号
    customerName: '', // 委托方名称
    sampleNo: '', // 样品编号
    sampleName: '', // 样品名称
    certificateClass: '', // 证书类型
    printNum: '', // 打印次数 -未打印和全部用
    approvalStatus: active.value, // 审批状态-审批查询用
    orderId: '', // 委托书id
    reason: '', // 操作原因
    sampleId: '', // 样品id
    status: '', // 状态变更(无需检测状态7,收入状态2,归还6，回退状态2.5.1,终止5)
    formId: SCHEDULE.CERTIFICATE_PRINT_APPROVAL,
    startTime: '', // 开始时间
    endTime: '', // 结束时间
    offset: 1,
    limit: 20,
  }
  dateRange.value = ['', ''] // 清空时间
  filterQuery()
  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 approvalDialog = ref() // 审批组件ref

// 审批
const handleDistribute = (row: ICerPrintList, status: string) => {
  if (status === 'agree') {
    approvalDialog.value.initDialog('agree', row.taskId)
    fetchData(true)
  }
  else {
    approvalDialog.value.initDialog('refuse', row.taskId, row.id)
    fetchData(true)
  }
}

// 审批结束回调
const approvalSuccess = () => {
  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 = {
      ...listQuery.value,
      ids: checkoutList.value,
    }
    // exportCert(params).then((res) => {
    //   const blob = new Blob([res.data])
    loading.close()
    //   exportFile(blob, '证书打印列表.xlsx')
    // })
  }
  else {
    loading.close()
    ElMessage.warning('无数据可导出数据')
  }
}

// 按钮切换
const changeCurrentButton = (val: string) => {
  if (val === null) {
    activeTitle.value = '可打印'
    return
  }
  active.value = val
  activeTitle.value = menu.value.find(item => item.id === val)!.name
  window.sessionStorage.setItem(buttonBoxActive, val)
  clearList()
}
// ----------------------------------------操作---------------------------------------------
// 打印
const bindLabel = (row: ICerPrintList) => {
  // 判断状态第一次可以直接打印,之后的打印需要审批
  if (row.printStatusName === '可打印') {
    ElMessageBox.confirm(
      '确定要打印吗？',
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    ).then(() => {
      getPhotoUrl(row.printFileName as string).then((res) => {
        const url = res.data
        console.log(url)

        pdfUrl.value = res.data
        console.log(pdfUrl.value)
        changePrintStatus({ id: row.id }).then(() => {
          console.log('状态已经更改')
          fetchData(true)
        })
        printPdf(res.data)
      })
    })
  }
  else {
    ElMessageBox.confirm(
      '打印前需申请   确定要打印吗?',
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true,
      },
    ).then(() => {
      // submitApproval({ id: row.id, formId: listQuery.value.formId }).then((res) => {
      //   console.log(res)
      //   if (res.code === 200) {
      //     ElMessage.success('申请已发送')
      //     fetchData(true)
      //   }
      // })
    })
  }
}
// 点击详情
const handleDetail = (row: ICerPrintList) => {
  $router.push({
    // path: `/schedule/cert/detail/${row.certificationId}?pageType=detail&printStatus=${row.printStatus}&id=${row.id}&printFileName=${row.printFileName}`,
    path: '/cert/detail',
    query: {
      // approvalStatusName: row.approvalStatusName, // 审批状态名称
      // printFileName: row.printFileName,
      // printStatus: row.printStatus, // 证书打印状态
      // processId: row.processId, // 流程实例
      // decisionItem: `${row.decisionItem}`, // 控制同意、驳回、拒绝按钮
      // taskId: row.taskId, // 任务id，用于同意、驳回、拒绝审批
      // id: row.id,
    },
  })
}
// ---------------------------------------钩子-----------------------------------------------
watch(dateRange, (val) => {
  if (val) {
    listQuery.value.startTime = `${val[0]}`
    listQuery.value.endTime = `${val[1]}`
  }
  else {
    listQuery.value.startTime = ''
    listQuery.value.endTime = ''
  }
})
onMounted(async () => {
  await getDict() // 获取字典-审批状态
  fetchData(true)
})
</script>

<template>
  <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.customerName"
          placeholder="委托方"
          clearable
          class="short-input"
        />
      </search-item>
      <!-- <search-item>
        <el-input
          v-model.trim="listQuery.equipmentNo"
          placeholder="被检设备统一编号"
          clearable
          class="short-input"
        />
      </search-item> -->
      <search-item>
        <el-date-picker
          v-model="dateRange"
          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 v-if="activeTitle === '全部' || activeTitle === '可打印'" icon="icon-export" title="导出" type="primary" @click="exportAll" />
      </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 v-if="!['可打印', '全部'].includes(activeTitle)" label="审批状态" align="center" width="90px" prop="approvalStatusName" />
          <el-table-column label="操作" align="center" fixed="right" width="120">
            <template #default="{ row }">
              <el-button size="small" link type="primary" @click="handleDetail(row)">
                详情
              </el-button>
              <el-button v-if="activeTitle === '全部' || activeTitle === '可打印'" size="small" link type="primary" @click="bindLabel(row)">
                打印
              </el-button>
              <el-button v-if="activeTitle === '待审批'" size="small" type="primary" link @click="handleDistribute(row, 'agree')">
                同意
              </el-button>
              <el-button v-if="activeTitle === '待审批'" size="small" type="danger" link @click="handleDistribute(row, 'refuse')">
                拒绝
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
    <!-- 右上角审批状态按钮集合 -->
    <button-box :active="active" :menu="menu" @change-current-button="changeCurrentButton" />
    <!-- 审批弹窗 -->
    <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
    <!-- pdf预览 -->
    <!-- <vue-pdf-embed ref="pdf" :source="pdfUrl" class="vue-pdf-embed" /> -->
  </app-container>
</template>

<style lang="scss" scoped>
.short-input {
  width: 160px;
}
</style>

