<template>
  <div class="pdf-viewer">
    <canvas ref="pdfCanvas"></canvas>
    <div class="pagination">
      <button @click="prevPage" :disabled="pageNum <= 1">上一页</button>
      <span> {{ pageNum }} / {{ pdf ? pdf.numPages : 0 }}</span>
      <button @click="nextPage" :disabled="pageNum >= pdf.numPages">下一页</button>
    </div>
  </div>
</template>

<script>
import * as pdfjsLib from 'pdfjs-dist';
import pdfWorker from 'pdfjs-dist/build/pdf.worker.entry';

pdfjsLib.GlobalWorkerOptions.workerSrc = pdfWorker;

export default {
  props: {
    pdfUrl: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      pdf: null,
      pageNum: 1,
    };
  },
  mounted() {
    this.loadPdf();
  },
  methods: {
    async loadPdf() {
      try {
        const loadingTask = pdfjsLib.getDocument(this.pdfUrl);
        this.pdf = await loadingTask.promise;
        this.renderPage(this.pageNum);
      } catch (error) {
        console.error('Error loading PDF: ', error);
      }
    },
    async renderPage(num) {
      const page = await this.pdf.getPage(num);
      const viewport = page.getViewport({ scale: 1.5 });
      const canvas = this.$refs.pdfCanvas;
      const context = canvas.getContext('2d');
      canvas.height = viewport.height;
      canvas.width = viewport.width;
      const renderContext = {
        canvasContext: context,
        viewport,
      };
      await page.render(renderContext).promise;
    },
    prevPage() {
      if (this.pageNum <= 1) return;
      this.pageNum--;
      this.renderPage(this.pageNum);
    },
    nextPage() {
      if (this.pageNum >= this.pdf.numPages) return;
      this.pageNum++;
      this.renderPage(this.pageNum);
    },
  },
};
</script>

<style scoped>
.pdf-viewer {
  display: flex;
  flex-direction: column;
  align-items: center;
}

canvas {
  margin-bottom: 10px;
  border: 1px solid #000;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
}

.pagination button {
  margin: 0 5px;
}
</style>
