<template>
  <div class="pdf-view-example j-contanter">
    <div class="pdf-view-container j-main">
      <div id="pdf-container" />
    </div>
    <div v-if="!getUserId" class="j-footer">
      <a href="/jyapp/free/login?url=/jy_mobile/order/create/creditreport&activity=bidCreditReportPreview" class="adsense-container">
        <AdSingle
          ad="app-credit-report-sample"
          :show-tag="false"
          :show-close-icon="false"
          class="adsense-container"
        />
      </a>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import * as pdfjsLib from 'pdfjs-dist/build/pdf'
import AdSingle from '@/components/ad/Ad'
import { getAssetsFile } from '@/utils'
import 'pdfjs-dist/build/pdf.worker.mjs'

export default {
  name: 'PdfViewExample',
  components: {
    AdSingle
  },
  data() {
    return {
      pdfUrl: '',
      pdf: null,
      totalPages: 0
    }
  },
  computed: {
    ...mapGetters('user', ['getUserId'])
  },
  created() {
    const { pdfUrl } = this.$route.query
    if (pdfUrl) {
      this.pdfUrl = decodeURIComponent(pdfUrl)
    }
    else {
      const pdfAssets = getAssetsFile('example.pdf')
      this.pdfUrl = pdfAssets
    }
  },
  mounted() {
    const container = document.getElementById('pdf-container')

    this.loadPdf(this.pdfUrl, container)
    // 监听窗口的 resize 事件，实现自适应效果
    window.addEventListener('resize', () => {
      container.innerHTML = ''
      this.loadPdf(this.pdfUrl, container)
    })
  },
  methods: {
    async loadPdf(pdfUrl, container) {
      try {
        const loadingTask = pdfjsLib.getDocument({
          url: pdfUrl,
          disableRange: true
        })
        this.pdf = await loadingTask.promise
        this.totalPages = this.pdf.numPages

        for (let pageNum = 1; pageNum <= this.totalPages; pageNum++) {
          const page = await this.pdf.getPage(pageNum)
          const viewport = page.getViewport({ scale: this.calculateScale(page) })
          const canvas = document.createElement('canvas')
          const ctx = canvas.getContext('2d')
          canvas.height = viewport.height
          canvas.width = viewport.width
          container.appendChild(canvas)

          await page.render({
            canvasContext: ctx,
            viewport,
          }).promise
        }
      }
      catch (error) {
        console.error('Error loading PDF:', error)
      }
    },
    // 计算缩放比例以适应容器宽度
    calculateScale(page) {
      const containerWidth = document.getElementById('pdf-container').clientWidth
      const viewport = page.getViewport({ scale: 1 })
      return containerWidth / viewport.width
    }
  }
}
</script>

<style lang="scss" scoped>
.pdf-container {
  width: 100%;
  height: 100%;
  iframe {
    width: 100%;
    height: 100%;
  }
}
</style>
