<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'
import { WorksapceApi } from '@/utils/index'
PDFJS.GlobalWorkerOptions.workerSrc = import('pdfjs-dist/build/pdf.worker.entry')

export default {
  name: 'PDFReader',
  props: {
    document: { type: String, default: '' }
  },
  data() {
    return {
      loadingTask: null,
      currentPage: 1,
      numPages: 0,
      selectedPage: 1
    }
  },
  mounted() {
    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)
        })
      })
    },
    async renderPDF() {
      const response = await WorksapceApi.fetchAttachedFileAsMediaData(
        '66673218fa83335c3b1b11ec',
        '6667321afa83335c3b1b11ee'
      )
      this.loadingTask = PDFJS.getDocument({ url: response.data })
      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>
