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

<script>
import { mapGetters } from 'vuex'
import AdSingle from '@/components/ad/Ad'
import { getAssetsFile } from '@/utils'
import PDF from '@/views/article/components/PDF.vue'

export default {
  name: 'PdfViewExample',
  components: {
    AdSingle,
    PDF
  },
  data() {
    return {
      pdfUrl: '',
      pdf: null,
      totalPages: 0,
      currentPage: 1, // 新增
      batchSize: 5, // 新增
      config: {
        PAGE_TO_VIEW: 0,
        SCALE: 1.0,
        CMAP_URL:
          'https://cdn-common.jianyu360.com/cdn/lib/pdfjs-dist/2.1.266/cmaps/',
        CMAP_PACKED: true,
        workerSrc:
          'https://cdn-common.jianyu360.com/cdn/lib/pdfjs-dist/2.1.266/build/pdf.worker.min.js'
      }
    }
  },
  computed: {
    ...mapGetters('user', ['getUserId'])
  },
  created() {
    this.$toast.loading('加载中...')

    const { pdfUrl } = this.$route.query
    if (pdfUrl) {
      this.pdfUrl = decodeURIComponent(pdfUrl)
    } else {
      const pdfAssets = getAssetsFile('example-min.pdf')
      // this.pdfUrl = 'https://cdn-common.jianyu360.cn/cdn/assets/file/example.pdf'
      this.pdfUrl = pdfAssets
    }
  },
  mounted() {
    // const container = document.getElementById('pdf-view-container')
    //
    // this.loadPdf(this.pdfUrl, container)
    // // 监听窗口的 resize 事件，实现自适应效果
    // window.addEventListener('resize', () => {
    //   container.innerHTML = ''
    //   this.loadPdf(this.pdfUrl, container)
    // })
  },
  methods: {
    async loadPdf(pdfUrl, container) {
      console.log('pdfUrl', pdfUrl)
      try {
        pdfjsLib.GlobalWorkerOptions.workerSrc = this.config.workerSrc
        const loadingTask = pdfjsLib.getDocument({
          url: pdfUrl,
          cMapUrl: this.config.CMAP_URL,
          cMapPacked: this.config.CMAP_PACKED,
          disableRange: true,
          disableAutoFetch: false, // 启动自动分块加载
          // 添加缓存头
          httpHeaders: {
            'Cache-Control': 'max-age=3600' // 缓存 1 小时
          },
          // 增加网络请求超时时间，避免因网络问题导致加载失败
          timeout: 30000,
          // 减少初始加载的字节数，提高初始加载速度
          initialDataSize: 1024 * 1024
        })
        this.pdf = await loadingTask.promise
        this.totalPages = this.pdf.numPages
        this.currentPage = 1
        this.batchSize = 5 // 新增

        await this.loadBatchPages(container) // 新增
        this.$toast.clear()
        // 监听滚动事件
        container.addEventListener('scroll', () => this.handleScroll(container))
      } catch (error) {
        console.error('Error loading PDF:', error)
      }
    },
    async loadBatchPages(container) {
      // 加载当前页码开始的连续多页，这里以5页为例
      // 分批加载，从当前页码开始，最多加载5页
      const endPage = Math.min(
        this.currentPage + this.batchSize - 1,
        this.totalPages
      )
      for (let pageNum = this.currentPage; pageNum <= endPage; 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
      }
      this.currentPage = endPage + 1 // 更新当前页码
    },
    handleScroll(container) {
      const { scrollTop, scrollHeight, clientHeight } = container
      if (scrollTop + clientHeight >= scrollHeight - 100) {
        // 当滚动到底部附近时
        if (this.currentPage <= this.totalPages) {
          this.loadBatchPages(container)
        }
      }
    },
    // 计算缩放比例以适应容器宽度
    calculateScale(page) {
      const containerWidth =
        document.getElementById('pdf-view-container').clientWidth
      const viewport = page.getViewport({ scale: 1 })
      // 增加一个倍数来提高清晰度，例如 1.5
      return (containerWidth / viewport.width) * 3
    }
  }
}
</script>
<style lang="scss" scoped>
.pdf-view-example {
  ::v-deep {
    .pdf-box {
      height: 100%;
    }
    .pdfjs {
      padding-top: 0;
    }
    .pdfViewer {
      padding: 0;
    }
  }
}
</style>
