<template>
  <h-view class="previewPdf">
    <h-header :proportion="[5,1,1]" class="bar-custom">
      <div slot="left" class="h-header-btn" @click="$routeGo()" >
        <img src="@/assets/userBind/arrow.png">
        <span>合同预览</span>
      </div>
    </h-header>
    <h-content>
      <canvas v-for="page in pages" :id="'the-canvas'+page" :key="page"/>
    </h-content>
  </h-view>
</template>
<script>
// import PDFJS from 'pdfjs-dist'
// const Base64 = require('js-base64').Base64

export default {
  data () {
    return {
      attachUrl: this.$route.params.attachUrl,
      pages: 0,
      pdfDoc: null,
    }
  },
  // beforeRouteEnter (to, from, next) {
  //   next(vm => {
  //     // let attachUrl = vm.attachUrl.substr(vm.attachUrl.indexOf('/xcmg_file'))
  //     vm.hlsPopup.showLoading('请稍候...')
  //     // debugger
  //     // let url = Base64.decode(vm.attachUrl)
  //     vm.attachUrl = vm.$route.params.attachUrl
  //     console.log('vm.attachUrl === ' + vm.attachUrl)
  //     vm._loadFile(vm.attachUrl)
  //     vm.hlsPopup.hideLoading()
  //   })
  // },
  mounted () {
    let vm = this
    // let attachUrl = vm.attachUrl.substr(vm.attachUrl.indexOf('/xcmg_file'))
    vm.hlsPopup.showLoading('请稍候...')
    // debugger
    // let url = Base64.decode(vm.attachUrl)
    vm.attachUrl = vm.$route.params.attachUrl
    console.log('vm.attachUrl === ' + vm.attachUrl)
    vm._loadFile(vm.attachUrl)
    vm.hlsPopup.hideLoading()
  },
  methods: {
    _renderPage (num) {
      this.pdfDoc.getPage(num).then((page) => {
        let canvas = document.getElementById('the-canvas' + num)
        let ctx = canvas.getContext('2d')
        let dpr = window.devicePixelRatio || 1
        let bsr = ctx.webkitBackingStorePixelRatio ||
                  ctx.mozBackingStorePixelRatio ||
                  ctx.msBackingStorePixelRatio ||
                  ctx.oBackingStorePixelRatio ||
                  ctx.backingStorePixelRatio || 1
        let ratio = dpr / bsr
        let viewport = page.getViewport(screen.availWidth / page.getViewport(1).width)
        canvas.width = viewport.width * ratio
        canvas.height = viewport.height * ratio
        canvas.style.width = viewport.width + 'px'
        canvas.style.height = viewport.height + 'px'
        ctx.setTransform(ratio, 0, 0, ratio, 0, 0)
        let renderContext = {
          canvasContext: ctx,
          viewport: viewport,
        }
        page.render(renderContext)
        if (this.pages > num) {
          this._renderPage(num + 1)
        }
      })
    },
    _loadFile (url) {
      console.log('URL ==== ' + url)
      this.PDFJS.getDocument(url).promise.then((pdf) => {
        this.pdfDoc = pdf
        // debugger
        console.log('pdf ==== ' + pdf)
        this.pages = this.pdfDoc.numPages
        this.$nextTick(() => {
          this._renderPage(1)
        })
      })
    },
  },
}
</script>
<style lang="less" rel="stylesheet">
</style>
