<template>
  <div class="startLearning" v-loading="studyLoading">
    <div class="learn-top-user-info-box">
      <img class="logo-img" :src="circularLogo">
      <p class="title-p">实验室安全学习与考试系统</p>
      <p class="time-p">{{timeText}}</p>
      <div class="user-box">
        <img v-if="userInfo.avatar" :src="userInfo.avatar">
        <img v-else src="@/assets/ZDimages/basicsModules/tx_cion.png">
        <p>{{userInfo.userName}}</p>
      </div>
    </div>
    <div class="learning-data-box">
      <div class="top-title-box">
        <div class="top-name-box">
          <p class="top-name-p">{{newList[chapterIndex].title}}<span style="margin-left:20px;">{{learningData.title}}</span></p>
          <p class="top-time-max-p">已学习时长：<span v-if="learningData.hourTwo">{{learningData.hourTwo}}小时</span><span v-if="learningData.minuteTwo>0">{{learningData.minuteTwo}}分钟</span>{{learningData.secondTwo}}秒</p>
        </div>
        <div class="top-button-box">
          <p class="top-time-p">时长：<span v-if="learningData.hourOne>0">{{learningData.hourOne}}小时</span><span v-if="learningData.minuteOne>0">{{learningData.minuteOne}}分钟</span>{{learningData.secondOne}}秒</p>
          <p class="top-null-p"></p>
          <div class="button-bottom-max-box" :class="timeType?'button-color-a':'button-color-b'" @click="shadeTypeClick(1)">完成学习</div>
          <p class="out-button" @click="outClick">返回</p>
        </div>
      </div>
      <div class="bottom-data-box scrollbar-box" :class="videoDraggable==0?'video-jz-box':''">
        <!--图片-->
        <img
          style="display: block;margin:auto;"
          v-if="learningData.postfix == 'png' || learningData.postfix == 'jpeg' || learningData.postfix == 'gif' || learningData.postfix == 'jpg'"
          :src="learningData.chapterData" >
        <video class="video-player vjs-custom-skin"
               style="width:1100px;height:619px;"
               autoplay="autoplay"
               :poster="videoCover"
               v-if="learningData.chapterData && learningData.postfix == 'mp4'">
          <source :src="learningData.chapterData" type="video/mp4">
        </video>
        <vue-office-docx
          v-if="learningData.postfix == 'docx'"
          :src="learningData.iframeSrc"
          @rendered="renderedHandler"
          @error="errorHandler"
        />
        <vue-office-pdf
          v-if="learningData.postfix == 'pdf'"
          :src="learningData.iframeSrc"
          @rendered="renderedHandler"
          @error="errorHandler"
        />
        <!--富文本-->
        <div v-if="learningData.type == 5" v-html="learningData.chapterData" style="width:896px;margin:0 auto;padding:40px 0;"></div>
      </div>
    </div>
    <div class="shade-max-box" v-if="shadeType">
      <div class="shade-big-box">
        <img class="off-shade-button" src="@/assets/ZDimages/safetyEducationExam/icon_jlfgz_gb_2.png" @click="shadeTypeClick(2)">
        <div class="shade-text-box">
          <p>您已学习完该章节</p>
          <p>已学习时长{{newTime}}，共获得{{integral}}奖励分</p>
          <img src="@/assets/ZDimages/safetyEducationExam/img_wcxx.png">
          <p @click="shadeTypeClick(3)">学习下一章节</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  //引入VueOfficeDocx组件
  import VueOfficeDocx from '@vue-office/docx'
  import '@vue-office/docx/lib/index.css'
  //引入VueOfficePdf组件
  import VueOfficePdf from '@vue-office/pdf'
  import { examElCourseLearnStart,examElCourseLearnFinish } from "@/api/safetyEducationExam/index";
  import { profile } from "@/api/commonality/noPermission";
  import { videoPlayer } from 'vue-video-player'
  import 'video.js/dist/video-js.css'
  export default {
    name: "startLearning",
    props:{
      infoId:{},
    },
    components:{
      videoPlayer,
      VueOfficeDocx,
      VueOfficePdf
    },
    data() {
      return {
        videoCover:localStorage.getItem('fileBrowseEnvironment')+ localStorage.getItem('videoCover'),
        circularLogo:localStorage.getItem('circularLogo'),
        studyLoading:false,
        //时间
        timeText:"",
        timeData:{},
        //定时器
        timer:{},
        timeType:false,
        //视频设置
        playerOptions: {
          playbackRates: [], // 可选的播放速度
          autoplay: true, // 如果为true,浏览器准备好时开始回放。
          muted: false, // 默认情况下将会消除任何音频。
          loop: false, // 是否视频一结束就重新开始。
          preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
          language: 'zh-CN',
          aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
          fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
          sources: [],
          poster: '', // 封面地址
          notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
          controlBar: {
            timeDivider: true, // 当前时间和持续时间的分隔符
            durationDisplay: true, // 显示持续时间
            remainingTimeDisplay: false, // 是否显示剩余时间功能
            fullscreenToggle: false // 是否显示全屏按钮
          }
        },
        //信息设置
        userInfo:{
          time:"",
          userName:"",
        },
        //学习数据
        newList:[],
        //章index,
        chapterIndex:"",
        //节index
        festivalIndex:"",
        //视频可否拖拽
        videoDraggable:"",
        //当前学习数据
        learningData:{},
        //遮罩层状态
        shadeType:false,
        //flv视频数据
        leftVideoList:{},
        //时间
        newTime:"",
        integral:"",
      }
    },
    created(){
      this.getTime();
      this.newList = JSON.parse(localStorage.getItem('learningList'));
      this.chapterIndex = this.$route.query.chapterIndex;
      this.festivalIndex = this.$route.query.festivalIndex;
      this.videoDraggable = this.$route.query.videoDraggable;
      localStorage.removeItem('learningList');
      this.getInfo();
      this.learnFinish();
    },
    methods:{
      getInfo(){
        profile().then( res => {
          this.userInfo = res.data;
        });
      },
      //文件加载成功
      renderedHandler() {
        // console.log("渲染完成")
        // this.$set(this,'officeNullType',false);
      },
      //文件加载失败
      errorHandler() {
        // console.log("渲染失败")
        // this.$set(this,'officeNullType',true);
      },
      //下一节方法
      nextSection(){
        if(this.newList[this.chapterIndex].children.length > this.festivalIndex){
          //该章未学完
          this.festivalIndex++;
          this.learnFinish();
        }else{
          //该章已学完
          if(this.newList.length > this.chapterIndex+1){
            this.chapterIndex++;
            this.festivalIndex = 0;
            this.learnFinish();
          }else{
            //所有章节已学习学习完毕
            this.msgSuccess('所有章节已学习完毕')
            this.$router.replace({
              path: `/safetyEducationExam/safeLearning/safeLearning`
            })
            // this.$router.go(1)
          }
        }
      },
      //初始化数据-开始学习
      learnFinish(){
        let obj = {
          courseId:this.newList[this.chapterIndex].courseId,
          chapterId:this.newList[this.chapterIndex].children[this.festivalIndex].id,
        };
        examElCourseLearnStart(obj).then( res => {
          this.learningData = JSON.parse(JSON.stringify(this.newList[this.chapterIndex].children[this.festivalIndex]))
          let hour = parseInt(this.learningData.duration/3600);
          let hourOne = parseInt(this.learningData.duration/3600);
          let hourNum = this.learningData.duration - this.accMul(hour,3600);
          let hourNumOne = this.learningData.duration - this.accMul(hour,3600);
          let minute = parseInt(hourNum/60)
          let minuteOne = parseInt(hourNumOne/60)
          let second = hourNum - this.accMul(minute,60);
          let secondOne = hourNumOne - this.accMul(minute,60);
          this.learningData.hour = hour;
          this.learningData.hourOne = hourOne;
          this.learningData.hourTwo = 0;
          this.learningData.minute = minute;
          this.learningData.minuteOne = minuteOne;
          this.learningData.minuteTwo = 0;
          this.learningData.second = second;
          this.learningData.secondOne = secondOne;
          this.learningData.secondTwo = 0;
          if(this.learningData.postfix == "mp4"){
            this.learningData.chapterData = localStorage.getItem('fileBrowseEnvironment')+this.learningData.chapterData
          }else if(this.learningData.postfix == "pdf" || this.learningData.postfix == "docx"){
            this.getWord();
          }else if(this.learningData.type == 5){
            this.getRichText();
          }
          this.timeType = false;
          this.time();
          this.shadeType = false;
        });
      },
      shadeTypeClick(type){
        if(type == 1){
          if(!this.timeType){
            return
          }
          this.studyLoading=true;
          let endObj = {
            courseId:this.newList[this.chapterIndex].courseId,
            chapterId:this.newList[this.chapterIndex].children[this.festivalIndex].id,
          };
          examElCourseLearnFinish(endObj).then( res => {
            this.newTime = res.data.durationStr;
            this.integral = res.data.points;
            this.shadeType = true;
            this.studyLoading=false;
            this.timeType=false;
          });
        }else if(type == 2){
          this.shadeType = false;
        }else if(type == 3){
          this.nextSection();
        }
      },
      //富文本处理
      getRichText(){
        this.learningData.chapterData = unescape(this.learningData.chapterData)
      },
      //word处理
      async getWord(){
        this.learningData.iframeSrc = localStorage.getItem('fileBrowseEnvironment')+this.learningData.chapterData
      },
      //乘法
      accMul(arg1,arg2){
        var m=0,s1=arg1.toString(),s2=arg2.toString();
        try{m+=s1.split(".")[1].length}catch(e){}
        try{m+=s2.split(".")[1].length}catch(e){}
        return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
      },
      //返回按钮
      outClick(){
        this.$router.replace({
          path: `/safetyEducationExam/safeLearning/safeLearning`
        })
      },
      //定时器
      getTime(){
        let self = this;
        window.clearInterval(this.timeData);
        this.timeData = {};
        this.timeData = window.setInterval(refreshCount, 1000);
        function refreshCount() {
          let newTime = new Date();
          let n = newTime.getFullYear();
          let y = newTime.getMonth()+1;
          let r = newTime.getDate();
          let s = newTime.getHours();
          let f = newTime.getMinutes();
          let m = newTime.getSeconds();
          self.timeText = n+'年'+y+'月'+r+'日'+' '+s+':'+f+':'+m;
          if(self.learningData.secondTwo>59){
            self.learningData.secondTwo = 0;
            if(self.learningData.minuteTwo>59){
              self.learningData.minuteTwo = 0
              this.learningData.hourTwo++
            }else{
              self.learningData.minuteTwo++
            }
          }else{
            self.learningData.secondTwo++;
          }
        }
      },
      //定时器
      time(){
        let self = this;
        window.clearInterval(this.timer);
        this.timer = {};
        this.timer = window.setInterval(refreshCount, 1000);
        function refreshCount() {
          if(self.learningData.hour == 0 && self.learningData.minute == 0 && self.learningData.second == 0){
            self.timeType = true;
          }else{
            if(self.learningData.second > 0){
              self.learningData.second--;
            }else if(self.learningData.minute > 0){
              self.learningData.minute--;
              self.learningData.second = 59;
            }else if(self.learningData.hour > 0){
              self.learningData.hour--;
              self.learningData.minute = 59;
              self.learningData.second = 59;
            }
          }
        }
      },
    },
    beforeDestroy() {
      //清除定时器
      clearInterval(this.timer);
    },
    destroyed() {
      //清除定时器
      clearInterval(this.timer);
    }
  }
</script>

<style scoped lang="scss">
  .startLearning{
    height:100%;
    width:100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    background: #fff;
    *{
      margin:0;
      padding:0;
      font-weight:500;
      color:#333;
    }
    .learn-top-user-info-box{
      display: flex;
      background: #0045AF;
      box-shadow: 0 0 8px 2px rgba(0, 0, 0, 0.1);
      .logo-img{
        height:50px;
        width:50px;
        margin:15px 12px 15px 18px;;
      }
      .title-p{
        width: 300px;
        font-size:24px;
        line-height:80px;
        color:#fff;
      }
      .time-p{
        flex:1;
        line-height:80px;
        font-size:18px;
        color:#fff;
        text-align: center;
        margin-right:100px;
      }
      .home-box{
        width:100px;
        display: flex;
        margin-top:25px;
        margin-right:30px;
        img{
          width:30px;
          height:30px;
          margin-right:20px;
        }
        p{
          color:#fff;
          line-height:30px;
        }
      }
      .user-box{
        min-width:100px;
        display: flex;
        margin-top:20px;
        margin-right:30px;
        img{
          width:40px;
          height:40px;
          margin-right:20px;
          border-radius:50%;
        }
        p{
          color:#fff;
          line-height:40px;
        }
      }
      .button-p{
        width:82px;
        height:34px;
        background: #0045af;
        color:#fff;
        text-align: center;
        line-height:34px;
        margin:23px 20px 0 0;
        border-radius:4px;
        cursor:pointer;
      }
    }
    .learning-data-box{
      flex:1;
      margin:20px 0;
      box-shadow: 0 0 8px 2px rgba(0, 0, 0, 0.1);
      display: flex;
      flex-direction: column;
      overflow: hidden;
      .top-title-box{
        .top-name-box{
          display: flex;
          padding:0 20px;
          .top-name-p{
            flex:1;
            line-height:40px;
            color:#0183FA;
            font-weight:700;
            font-size:18px;
            span{
              line-height:40px;
              color:#0183FA;
              font-weight:700;
              font-size:18px;
            }
          }
          .top-time-max-p{
            flex:1;
            text-align: right;
            line-height:40px;
            font-size:16px;
          }
        }
        .top-button-box{
          display: flex;
          .top-time-p{
            font-size:16px;
            line-height:40px;
            padding:0 20px;
          }
          .top-null-p{
            flex:1;
          }
          .button-color-a{
            background: #0045AF;
            color:#fff;
          }
          .button-color-b{
            background: #999;
            color:#fff;
          }
          .button-bottom-max-box{
            width:100px;
            height:28px;
            font-size:14px;
            text-align: center;
            line-height: 28px;
            border-radius:4px;
            cursor:pointer;
            margin-right:20px;
          }
          .out-button{
            width:80px;
            height:28px;
            font-size:14px;
            text-align: center;
            line-height: 28px;
            border-radius:4px;
            cursor:pointer;
            color:#666;
            border:1px solid #666;
            background-color: #fff;
            margin-right:20px;
          }
        }
      }
      .bottom-data-box{
        margin:0 20px 0;
        overflow-y: scroll;
        display: flex;
        flex: 1;
        flex-direction: column;
        background: #dedede;
        iframe{
          flex:1;
        }
        .video-player{
          width:1100px;
          margin:auto auto;
        }
      }
    }
    .shade-max-box{
      height:100%;
      width:100%;
      position: fixed;
      background: rgba(0,0,0,0.4);
      overflow: hidden;
      z-index:10;
      .shade-big-box{
        position: absolute;
        top:50%;
        left:50%;
        margin-left:-300px;
        margin-top:-241px;
        width:600px;
        height:486px;
        .off-shade-button{
          height:32px;
          width:32px;
          margin:0 284px 30px;
          cursor:pointer;
        }
        .shade-text-box{
          width:600px;
          height:470px;
          background: #fff;
          border-radius:6px;
          overflow: hidden;
          p:nth-child(1){
            text-align: center;
            font-size:24px;
            line-height:24px;
            margin:31px 0 0;
          }
          p:nth-child(2){
            text-align: center;
            font-size:20px;
            line-height:20px;
            color:#0183FA;
            margin:20px 0 13px;
          }
          img:nth-child(3){
            display: block;
            width:256px;
            height:270px;
            margin:0 auto;
          }
          p:nth-child(4){
            width:200px;
            background: #0045af;
            color: #fff;
            height:40px;
            line-height:40px;
            text-align: center;
            font-size:16px;
            margin:23px auto 19px;
            border-radius:6px;
            cursor:pointer;
          }
        }

      }
    }
  }
</style>
