<template>
  <div id="pdf-container" class="pdf-container">
    <canvas id="theCanvas"></canvas>
    <div class="oprate">
      <button class="btn btn-link" @click="prev">prev</button>
      <span> {{ currentPage }} / {{ numPages }} </span>
      <button class="btn btn-link" @click="next">next</button>
    </div>
  </div>
</template>

<script>
import * as PDFJS from 'pdfjs-dist/build/pdf'
PDFJS.GlobalWorkerOptions.workerPort = new Worker(
  new URL('pdfjs-dist/build/pdf.worker.mjs', import.meta.url),
  { type: 'module' }
)

// import * as PDFJS from 'pdfjs-dist/webpack.mjs'

export default {
  name: 'PDFReader',
  props: {
    doc: { type: Object, default: () => {} }
  },
  data() {
    return {
      loadingTask: null,
      currentPage: 1,
      numPages: 0,
      selectedPage: 1
    }
  },
  watch: {
    doc() {
      if (this.doc.url || this.doc.data) {
        this.renderPDF()
      }
    }
  },
  methods: {
    renderPage(num) {
      const canvas = document.getElementById('theCanvas')
      const context = canvas.getContext('2d')
      const scale = 1.5
      this.loadingTask.promise.then((pdf) => {
        pdf.getPage(num).then((page) => {
          const viewport = page.getViewport({ scale })
          canvas.height = viewport.height
          canvas.width = viewport.width
          const renderContext = {
            canvasContext: context,
            viewport: viewport
          }
          page.render(renderContext)
        })
      })
    },
    renderPDF() {
      this.loadingTask = PDFJS.getDocument(this.doc)
      this.loadingTask.promise.then((pdf) => {
        this.numPages = pdf.numPages
        this.renderPage(1)
      })
    },
    prev() {
      if (this.currentPage > 1) {
        this.currentPage--
        this.renderPage(this.currentPage)
      }
    },
    next() {
      if (this.currentPage < this.numPages) {
        this.currentPage++
        this.renderPage(this.currentPage)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.pdf-container {
  position: relative;
  .operate {
    position: absolute;
    right: 0;
    top: 0;
  }
}
</style>
