<template>
  <div class="canvas-container">
    <canvas ref="pdfCanvas" class="pdf-container"> </canvas>
  </div>
  <div class="pagination-wrapper">
    <button @click="clickPre">上一页</button>
    <span>第{{ pageNo }} / {{ pdfPageNumber }}页</span>
    <button @click="clickNext">下一页</button>
  </div>
</template>

<script lang="ts">
  import { GlobalWorkerOptions, getDocument } from 'pdfjs-dist'
  import { defineComponent, PropType, reactive, ref, watch, toRefs } from 'vue'
  import { PdfData } from '/#/tree'
  import workerSrc from 'pdfjs-dist/build/pdf.worker.entry'
  GlobalWorkerOptions.workerSrc = workerSrc
  export default defineComponent({
    name: 'PreviewPdf',
    props: { url: { type: String as PropType<string>, required: true } },
    setup(props) {
      const pdfCanvas = ref(null)
      const pdfData: any = ref(null)
      const pdfVM = reactive<PdfData>({
        pageNo: 0,
        pdfPageNumber: 0,
        pdfTotalPages: 1,
        renderingPage: false,
        scale: 1 // 缩放值
      })
      loadPdf(props.url)
      watch(props, props => {
        loadPdf(props.url)
      })
      function loadPdf(url: string) {
        // 引入pdf.js的字体
        let CMAP_URL = 'https://unpkg.com/pdfjs-dist@2.0.943/cmaps/'
        pdfData.value = getDocument({
          url,
          cMapUrl: CMAP_URL,
          cMapPacked: true
        })
        renderPage(1)
        // renderScrollPdf()
      }
      function clickPre() {
        if (!pdfVM.renderingPage && pdfVM.pageNo && pdfVM.pageNo > 1) {
          renderPage(pdfVM.pageNo - 1)
        }
      }
      function clickNext() {
        if (
          !pdfVM.renderingPage &&
          pdfVM.pdfPageNumber &&
          pdfVM.pageNo &&
          pdfVM.pageNo < pdfVM.pdfPageNumber
        ) {
          renderPage(pdfVM.pageNo + 1)
        }
      }

      function renderPage(num: number) {
        pdfVM.renderingPage = true
        console.log(pdfData.value)

        pdfData.value?.promise?.then(pdf => {
          console.log(111)

          pdfVM.pdfPageNumber = pdf.numPages
          pdf.getPage(num).then(page => {
            // 获取DOM中为预览PDF准备好的canvasDOM对象
            let canvas = pdfCanvas.value as any
            let viewport = page.getViewport(pdfVM.scale)
            canvas.height = viewport.height
            canvas.width = viewport.width
            let ctx = canvas.getContext('2d')
            let renderContext = {
              canvasContext: ctx,
              viewport: viewport
            }
            page.render(renderContext).then(() => {
              pdfVM.renderingPage = false
              pdfVM.pageNo = num
            })
          })
        })
      }

      return { pdfCanvas, clickPre, clickNext, ...toRefs(pdfVM) }
    }
  })
</script>

<style lang="less" scroped></style>
