<style scoped>
     .show_pdf {
      position: relative;
      top: 0;
      left: 0;
      width: 100%;
    }
    .page {
      /* position: absolute;
      left: 0;
      right: 0;
      top: 0; */
      background: rgba(0, 0, 0, 0.2);
      z-index: 100;
      padding: 0 15px;
      line-height: 25px;
      text-align: center;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
      color: #fff;
    }
    .page  .span_1 {
        float: left;
        cursor: pointer;
    }
    .page .span_2 {
        float: right;
        cursor: pointer;
    }
    
    .main_content {
      width: 100%;
      overflow-y:auto;
    }
    .pdf-box {
      position: relative;
      text-align: left;
      display: inline-block;
    }
.auditPopu{z-index:99999999;position: fixed;text-align: center;top:50%;margin-top:-10rem;min-height: 16.4rem;width: 84%;background: rgba(255, 255, 255, 1);margin-left:8%;border-radius: 0.2rem;}
.auditPopu img{display: block;margin: 0 auto;}
.auditPopu .successImg{width: 5rem;height: 5rem;margin-top: 2rem;}
.auditPopu h4{font-weight: normal;}
.auditPopu p{width:86%;margin: 0 auto;color:#3A8AFB; }
.auditPopu p .btnReturn{border: 0.1rem solid #3A8AFB;
border-radius: 0.3rem;width: 7rem;display: inline-block;
line-height: 1.5rem;height: 1.5rem;margin-top: 1rem;}
.auditPopu .closeImg{width: 2rem;height: 2rem;position: absolute;bottom: -3.2rem;margin-left:-1rem;left: 50%;}
.mask {position: fixed;top: 0;left: 0;height: 100%;width: 100%;background: rgba(0, 0, 0, 0.5);}
</style>
<template>
  <div id="showPdf">
    <div ref="elscrollbar" class="show_pdf">
      <div class="container">
        <div class="page">
          <span class="span_1" @click="pageUp">上一页</span>
          <span>页码：{{`${Pager.CurrentPage}/${Pager.TotalPage}`}}</span>
          <span class="span_2" @click="pageDown">下一页</span>
        </div>
        <div class="main_content" id="mainContent" ref="mainContent" style="height:100%">
           <center v-if="!Pager.IsShowPdf">pdf文档正在努力解析中...</center>
           <canvas id="the-canvas" class="canvas-pdf"></canvas>
        </div>
      </div>
    </div>

   <div class="mask" v-show="isShow.IsshowMask"></div>
       <div class="auditPopu" v-show="isShow.IsshowWinOk">
          <img class="successImg" src="http://image.supercarrier8.com/h5_key/studyCenter/icon-giftBlue.png" alt="success">
          <h4>
           恭喜您完成本次课程学习!
          </h4>
          <p>
            获的奖励：<span v-html="CourseModel.AwardsName"></span>
          </p>
          <p>
            <span @click="goPage('S_HomeP')" class="btnReturn">返回学习中心</span>
          </p>
          <img class="closeImg" src="http://image.supercarrier8.com/h5_key/icon-close-white.png" alt="close" @click="goPage('S_HomeP')"> 
    </div>
      <ReturnHome ref="returnhome"></ReturnHome>
  </div>
</template>
<script>
import PDFJS from 'pdfjs-dist'
	import ReturnHome from "@/components/channel/temp001/ReturnHome";
import channelHelper from "@/assets/js/channelHelper.js";
//import axios from 'axios'
export default {
  name: 'S_PDFViewer',
   components: {ReturnHome},
  provide(){       
     return{           
        goPage:this.goPage       
     }   
  },
  data () {
    return {
      pdfUrl:"/static/pdf/chao8.pdf",
      Pager:{
        IsShowPdf:false,
        TotalPage:"0",
        CurrentPage:"1",
        PageRendering:false,/* 防止重复点击 */
        pageNumPending:null,/* 取得最新页码 */
        pdfData:null,
        canvas:null,
        Author:"刘星-全网找不到这么完整的PDF兼容H5的预览-花了我好多心血,大家有相关需求疑问可以找我，嘿嘿"
      },
      isShow:{
           IsshowMask:false,
           IsshowWinOk:false,
      },
      CourseModel:{},
      CourseRecordModel:{},
      setTimeoutData:null
    }
  },
  mounted () {
    //this.renderPdf(this.pdfUrl);
   
  },
  methods: {
    goPage(pagetype){
        this.$parent.changeSelectedPage(pagetype);
    },
    SetTimerStudy(TotalWinSecond){
      var that=this;
      if(TotalWinSecond==0)
      { 
          that.WinRecord();
          window.clearTimeout(that.setTimeoutData);
      }else if(TotalWinSecond!=0&&TotalWinSecond%60==0)
      {
        that.SetCourseRecord(TotalWinSecond/60);
      }
      TotalWinSecond--;

      that.setTimeoutData=window.setTimeout(function(){
          that.SetTimerStudy(TotalWinSecond);
      },1000);

    },
    WinRecord(){
        var that=this; 
        var url = "/channel/WinCoursePrizeH5";
        var dataParams = {
            EnterpriseNo:that.sup8.context.enterpriseno,
            UserToken:channelHelper.GetUserToken(),
            LanguageType:channelHelper.GetLanguageType(),
            StudyId:that.CourseModel.ID,
            StudyRecordId:that.CourseRecordModel.ID,
            StudyTime:that.CourseModel.StudyLimit
        };
        var cbSuccess = function(res){
           if(res.flag)
            {
               that.isShow.IsshowMask=true;
               that.isShow.IsshowWinOk=true;

               that.isShow.ShowStudy=false;
               that.TipStateTxt ="已经完成";
               that.TipBtnTxt="重新学习";
            }
        };
        //请求后端
        channelHelper.CommonCallService(url,dataParams,cbSuccess,null,null,null)
    },
    SetCourseRecord(StudyTime){
        var that=this; 
        var url = "/channel/InsertCourseRecordH5";
        var dataParams = {
            EnterpriseNo:that.sup8.context.enterpriseno,
            UserToken:channelHelper.GetUserToken(),
            LanguageType:channelHelper.GetLanguageType(),
            CourseId:that.CourseModel.ID,
            StudyTime:StudyTime
        };
        var cbSuccess = function(res){
            if(res.flag&&res.data)
             {
                that.CourseRecordModel=res.data;
             }
        };
        //请求后端
        channelHelper.CommonCallServiceAuto(url,dataParams,cbSuccess,null,null,null)
    },
    loadCourseDetail(id)
    {
        var that=this; 
        var url = "/channel/GetCourseDetailH5";
        var dataParams = {
            EnterpriseNo:that.sup8.context.enterpriseno,
            UserToken:channelHelper.GetUserToken(),
            LanguageType:channelHelper.GetLanguageType(),
            ID:id
        };
        var cbSuccess = function(res){
            if(res.flag&&res.data)
             {
                that.CourseModel=res.data;
                that.CourseModel.CourseIntro=decodeURIComponent(res.data.CourseIntro);
                const regex = new RegExp('<img', 'gi');
                that.CourseModel.CourseIntro = that.CourseModel.CourseIntro.replace(regex, `<img style="max-width: 100%; height: auto"`);
                that.getPdfFun();
             }
        };
        //请求后端
        channelHelper.CommonCallService(url,dataParams,cbSuccess,null,null,null)
    },
    
      // 当PDF地址跨域时，后台以流的形式传输PDF
    getPdfFun () {
      var that=this;
     let config = this.sup8.$utils.ssg("appConfig");
      $.get(config.dash+"/e_studycenter/PDFViewer/SendNew",{filepath:that.CourseModel.LinkUrl},function(data){
          let raw = window.atob(data) //从这里 到下面 得到 rawArray
	      	let rawLength = raw.length
	      	let rawArray = new Uint8Array(new ArrayBuffer(rawLength))
	        for(var i = 0;i<rawLength;i++){
	       		rawArray[i] = raw.charCodeAt(i)
          }
          that.renderPdf(rawArray);
      });
    },
    renderPdf (pdfData) {  
      var that=this;
      console.log("Base64已经加载...");
      PDFJS.cMapUrl = 'https://unpkg.com/pdfjs-dist@1.9.426/cmaps/'; 
      PDFJS.cMapPacked = true;
      that.Pager.canvas=document.getElementById("the-canvas");
      PDFJS.getDocument(pdfData).promise.then(pdf => {
        let totalPage = pdf.numPages
        that.Pager.IsShowPdf=true;
        that.Pager.TotalPage=totalPage;
        that.Pager.pdfData=pdf;
        
        $(".main_content").css("overflow-y","scroll");
        /* 调用中奖逻辑 */
        that.SetCourseRecord(0);
        var StudyTime=that.CourseModel.StudyLimit;
        var TotalWinSecond=parseInt(StudyTime)*60;
        that.SetTimerStudy(TotalWinSecond);
        that.renderPage(1);
      })
    },
    renderPage (pageNum) {
      var that=this;
      that.Pager.PageRendering= true;
		  that.Pager.pdfData.getPage(pageNum).then(function(page) {
        let viewportFirst = page.getViewport(1);
        let width = window.getComputedStyle(that.$refs.mainContent).width;
        let scale =parseInt(width) / viewportFirst.width;
        var viewport = page.getViewport(scale*2);
        that.Pager.canvas.height = viewport.height;
        that.Pager.canvas.width = viewport.width;

        var renderContext = {
          canvasContext: that.Pager.canvas.getContext('2d'),
          viewport: viewport
        };
        var renderTask = page.render(renderContext);

        renderTask.promise.then(function() {
          that.Pager.PageRendering = false;
          if (that.Pager.pageNumPending !== null) {
              that.renderPage(that.Pager.pageNumPending);
              that.Pager.pageNumPending = null;
          }
        });
		  });
      that.Pager.CurrentPage = pageNum;
    },
    /*
      防止频繁点击
    */
    queueRenderPage(pageNum) {
		  if (this.Pager.pageRendering) {
			  this.Pager.pageNumPending = pageNum;
		  } else {
			  this.renderPage(pageNum);
		  }
		},
    /**
     * 上一页
     */
    pageUp () {
      if (this.Pager.CurrentPage <= 1) {
			  return;
		  }
		  this.Pager.CurrentPage--;
		  this.queueRenderPage(this.Pager.CurrentPage);
    },
    /**
     * 下一页
     */
    pageDown () {
      if (this.Pager.CurrentPage >= this.Pager.pdfData.numPages) {
			  return;
		  }
		  this.Pager.CurrentPage++;
		  this.queueRenderPage(this.Pager.CurrentPage);
    }
  },
  created: function() {
    var that = this;
     //PDFJS.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';
    //PDFJS.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';
    /*Base64用这个 */
    PDFJS.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.min.js');
    /*指定链接用这个 */
    //PDFJS.workerSrc = require('pdfjs-dist/build/pdf.worker.min.js');
    //this.$router.push('/S_HomePage')
    var ID=localStorage.getItem("studyId");
    //ID="5801cd06e417436097a3f37316c90170";
    that.loadCourseDetail(ID);
  },
  beforeDestroy:function(){
     window.clearTimeout(this.setTimeoutData);
  }
}
</script>


