<!-- 证书打印列表 -->
<script lang="ts" setup name="CustomerList" crossorigin="anonymous">
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 { ICerPrintList, ICertPrintSearch } from './cert-interface'
import ApprovalDialogPart from './components/ApprovalDialogPart.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 menu = ref<IMenu[]>([]) // 右上角审批状态按钮组合
const active = ref('') // 选中的按钮
const activeTitle = ref('') // active对应的审批状态名字
// 查询条件
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.BUSINESS_CERT_PRINT,
  ids: null, // 设置默认值
  offset: 1,
  limit: 20,
})
const approvalDialogPart = ref() // 审批组件
// --------------获取所需字典值----------------
const certificationClassList = ref<dictType[]>([]) // 样品属性列表
function getDict() {
  // 获取样品属性
  getDictByCode('certificationClass').then((response) => {
    certificationClassList.value = response.data
  })

  // 制作右上角的菜单
  // 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('certPrintActive')) {
      active.value = window.sessionStorage.getItem('certPrintActive') as string
    }
    else {
      active.value = menu.value.find(item => item.name === '可打印')!.id as string// 可打印
    }
  })
}

// 表头
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: 'measurePersonId', 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 filterQuery() {
  const StatuFlag = activeTitle.value == '可打印'
  const value = menu.value.find(item => item.name === activeTitle.value)!.id as string
  if (StatuFlag) {
    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
  })
}
// 多选发生改变时
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.BUSINESS_CERT_PRINT,
    offset: 1,
    limit: 20,
  }
  filterQuery()
  fetchData(true)
}
// 点击详情
const handleDetail = (row: ICerPrintList) => {
  $router.push(`/schedule/cert/detail/${row.certificationId}?pageType=detail&printStatus=${row.printStatus}&id=${row.id}`)
}

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

// 审批结束回调
const approvalSuccess = () => {
  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 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])
      exportFile(blob, '证书打印列表.xlsx')
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  loading.close()
}

const doPrint = (val: any) => {
  // var ordonnance = document.getElementById(val)!.contentWindow
  var ordonnance = document.getElementById(val)!.contentWindow
  setTimeout(() => {
    console.log('调出打印机')
    ordonnance.print()
  }, 100)
}

// 打印
const bindLabel = (row: ICerPrintList) => {
  // 判断状态第一次可以直接打印,之后的打印需要审批
  // if (row.printNum == 0) {
  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)

        // pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.worker.js'
        // proxy.$refs.pdf.print()
        // download(url, row.printFileName as string)
      })
      const loading = ElLoading.service({
        lock: true,
        background: 'rgba(255, 255, 255, 0.8)',
      })
      getPdfStream(row.printFileName as string).then((res) => {
        const blob = new Blob([res.data], { type: 'application/pdf' })
        var date = (new Date()).getTime()
        var ifr = document.createElement('iframe')
        // ifr.style.frameborder = 'no'
        ifr.style.display = 'none'
        ifr.style.pageBreakBefore = 'always'
        ifr.setAttribute('id', `printPdf${date}`)
        ifr.setAttribute('name', `printPdf${date}`)
        ifr.src = window.URL.createObjectURL(blob)
        document.body.appendChild(ifr)
        doPrint(`printPdf${date}`)
        window.URL.revokeObjectURL(ifr.src) // 释放URL 对象
        loading.close()
      })
    })
  }
  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 === 200) {
          ElMessageBox.confirm(
            '已经发送申请！',
            '确认操作',
            {
              type: 'success',
            },
          )
        }
      })
    })
  }
}
// var printObj = ref({
//   // asyncUrl : 'http://111.198.10.15:21408/test/测试_1680242558223_1681889965885.pdf',
//   // asyncUrl(reslove) {
//   //   getPhotoUrl(row.printFileName as string).then((res) => {
//   //     const url = res.data
//   //     console.log(url)

//   //     pdfUrl.value = res.data
//   //     console.log(pdfUrl.value)
//   //     reslove('http://111.198.10.15:21408/test/测试_1680242558223_1681889965885.pdf')
//   //     // printPdf(res.data)

//   //     // pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.worker.js'
//   //     // proxy.$refs.pdf.print()
//   //     // download(url, row.printFileName as string)
//   //   })
//   // },
//   // id: 'printBox', // 这里的id就是上面我们的打印区域id，实现指哪打哪
//   // popTitle: '配置页眉标题', // 打印配置页上方的标题
//   // extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
//   // preview: false, // 是否启动预览模式，默认是false
//   // previewTitle: '预览的标题', // 打印预览的标题
//   // previewPrintBtnLabel: '预览结束，开始打印', // 打印预览的标题下方的按钮文本，点击可进入打印
//   // zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
//   // previewBeforeOpenCallback() { console.log('正在加载预览窗口！') }, // 预览窗口打开之前的callback
//   // previewOpenCallback() { console.log('已经加载完预览窗口，预览打开了！') }, // 预览窗口打开时的callback
//   // beforeOpenCallback() { console.log('开始打印之前！') }, // 开始打印之前的callback
//   // openCallback() { console.log('执行打印了！') }, // 调用打印时的callback
//   // closeCallback() { console.log('关闭了打印工具！') }, // 关闭打印的callback(无法区分确认or取消)
//   // clickMounted() { console.log('点击v-print绑定的按钮了！') },

// })
// 打印列表
function 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: ICerPrintList) => checkoutList.value.includes(item.certificationId))
    printJSON(printList, properties, '证书打印列表')
  }
  else {
    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('certPrintActive', val)
  clearList()
}

onMounted(async () => {
  await getDict() // 获取字典-审批状态
  fetchData(true)
})
</script>

<template>
  <app-container>
    <approval-dialog-part ref="approvalDialogPart" @on-success="approvalSuccess" />
    <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.orderNo"
          placeholder="委托书编号"
          clearable
          class="short-input"
        />
      </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.sampleName"
          placeholder="样品名称"
          class="short-input"
          clearable
        />
      </search-item>
      <search-item>
        <el-select v-model="listQuery.certificateClass" placeholder="证书类型" style="width: 160px;" clearable>
          <el-option v-for="item in certificationClassList" :key="item.id" :label="item.name" :value="item.value" />
        </el-select>
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm('/schedule/certPrint/export')" icon="icon-export" title="导出" type="primary" @click="exportAll" />
        <icon-button v-if="proxy.hasPerm('/schedule/certPrint/print')" icon="icon-print" title="打印" type="primary" @click="printList" />
      <!-- <button @click="print">打印</button> -->
      </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="proxy.hasPerm('/schedule/certPrint/certPrint') && ((activeTitle === '全部' && row.printStatusName === '可打印' || row.printStatusName === '不可打印') || activeTitle === '可打印')" size="small" link type="primary" @click="bindLabel(row)">
                打印
              </el-button> -->
              <el-button v-if="proxy.hasPerm('/schedule/certPrint/certPrint') && ((activeTitle === '全部' && row.printStatusName === '可打印') || activeTitle === '可打印')" size="small" link type="primary" @click="bindLabel(row)">
                打印
              </el-button>
              <el-button v-if="proxy.hasPerm('/schedule/certPrint/agree') && activeTitle === '待审批'" size="small" type="primary" link @click="handleDistribute(row, 'agree')">
                同意
              </el-button>
              <el-button v-if="proxy.hasPerm('/schedule/certPrint/refuse') && activeTitle === '待审批'" size="small" type="primary" 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" />
    <!-- pdf预览 -->
    <!-- <vue-pdf-embed ref="pdf" :source="pdfUrl" class="vue-pdf-embed" /> -->
  </app-container>
</template>

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