<template>
  <div class="view-wrapper">
    <page-model
      v-if="picaWechat != 'wechat'"
      ref="PageModel"
      :header-info="headerInfo"
    />
    <div
      class="box"
      style="background: #fff"
    >
      <div>
        <canvas
          v-for="page in pages"
          :id="'the-canvas'+page"
          :key="page"
        />
      </div>
      <div
        id="canvas-wrap"
        class="view"
      />
    </div>
    <van-loading
      v-show="loadding"
      type="spinner"
    />
  </div>
</template>
<script>

  import PDFJS from 'pdfjs-dist';
  import workerSrc from 'pdfjs-dist/build/pdf.worker.entry';
  PDFJS.workerSrc = workerSrc;
  export default {
    data() {
      return {
        picaWechat:window._picaWechat,
        headerInfo: {
          title: '查看报告',
          isBlack: true,
          backMethod: 'web',
          style: 'backgroundColor:#ffffff;zIndex:100;',
          background: '',
        },
        pdfDoc: null,
        pages: 0,
        pdfUrl:'',
        pdfname:'',
        src:'',
        loadding:true,
        file:true,
        isDestory:true
      };
    },
    metaInfo: {
      meta: [
        { name: 'viewport', content: 'width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=5,user-scalable=yes' }
      ]
    },
    watch: {
    },
    created() {
      const {name, url} = this.$route.query;
      console.log('--url', url);
      this.pdfname = name;
      this.pdfUrl = url;
    },
    mounted() {
      this._loadFile(this.pdfUrl);
      this.$sendBuriedData({
        action: 'ACTION_WEB_AFTER',
        component_tag: '0000000#7802856#0#0',
      });
    },
    beforeDestroy() {
      console.log('destory');
      this.isDestory = false;
      this._renderPage = null;

    },
    methods: {
      _renderPage (num) {
        // getPage 处理每个页面
        // 返回单页内容实例（页面引索） pdf.getPage(index)
        this.pdfDoc.getPage(num).then((page) => {
          // canvas 绘制 PDF
          const canvas = document.getElementById('the-canvas' + num);
          const ctx = canvas.getContext('2d');
          ctx.mozImageSmoothingEnabled = false;
          ctx.webkitImageSmoothingEnabled = false;
          ctx.msImageSmoothingEnabled = false;
          ctx.imageSmoothingEnabled = false;
          const dpr = window.devicePixelRatio || 1;
          const bsr = ctx.webkitBackingStorePixelRatio ||
            ctx.mozBackingStorePixelRatio ||
            ctx.msBackingStorePixelRatio ||
            ctx.oBackingStorePixelRatio ||
            ctx.backingStorePixelRatio || 1;
          const ratio = dpr / bsr;
          // 返回页面内容(比例) page.getViewport({scale:2.0})语法改这么写
          const viewport = page.getViewport({scale:screen.availWidth / page.getViewport({scale:1.0}).width});// 这是让pdf文件的大小等于视口的大小
          canvas.width = viewport.width * ratio;
          canvas.height = viewport.height * ratio;// 这里会进行压缩，解决模糊问题
          canvas.style.width = viewport.width + 'px';
          canvas.style.height = viewport.height + 'px';
          const renderContext = {
            canvasContext: ctx,
            viewport: viewport,
            transform: [ratio, 0, 0, ratio, 0, 0]// 这里会进行放大，解决模糊问题
          };
          const that = this;
          page.render(renderContext).promise.then(function() {
            //  防止 在 PDF未渲染完某页 就返回时 会报错，导致下一次打开PDF 不会渲染出来
            if(that.isDestory) {
              console.log('xuanran');
              // page.getTextContent()
              if (that.pages > num) {
                that._renderPage(num + 1);
              }
            }
          });
        });
      },
      _loadFile (url) {
        // 获取整个 文档
        PDFJS.getDocument({
          url,
          // cMapUrl: 'https://unpkg.zhimg.com/pdfjs-dist@1.9.426/cmaps/',//这里同样要引入字体解决水印问题，需自己提供
          // 注意：如果PDF的水印是收费字体，则需要 通过cMapUrl引入对应的字体，如果是免费字体，则不需要引入字体 水印会直接渲染出来
          cMapPacked: true
        }).promise.then((pdf) => {
          this.pdfDoc = pdf;
          this.pages = this.pdfDoc.numPages;
          this.loadding = false;
          const that = this;
          if(that.isDestory) {
            this.$nextTick(() => {
              this._renderPage(1);
            });
          }
        }, (err) => {
          console.log('pdf-error', err);
          this.$toast('无效的PDF链接');
        });
      }
    }
  };

</script>
<style lang="scss" scoped>
.view-wrapper {
}
.view-wrapper /deep/ .van-nav-bar .van-icon {
  color: #333;
  font-size: 18px;
  margin-right: 3px;
}
.view-wrapper /deep/ .van-loading {
  position: absolute;
  top: 50%;
  left: 46%;
}
</style>
