<template>
  <div class="startLearning" v-loading="studyLoading">
    <div class="learn-top-user-info-box">
      <!--<img class="logo-img" src="@/assets/ZDimages/logo.jpg">-->
      <img class="logo-img" :src="circularLogo">
      <p class="title-p">实验室安全学习与考试系统</p>
      <p class="time-p">{{timeText}}</p>
      <div class="user-box">
        <img src="userInfo.avatar">
        <p>{{userInfo.userName}}</p>
      </div>
      <!--<p class="button-p">退出</p>-->
      <p class="button-p" @click="outClick">返回</p>
    </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>
        <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>
      </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'"
          :src="c" >
        <!--视频-->
        <!--<video-player-->
          <!--class="video-player vjs-custom-skin"-->
          <!--v-if="learningData.postfix == 'mp4' || learningData.postfix == 'webm'"-->
          <!--@pause="demo($event)"-->
          <!--:playsinline="true"-->
          <!--:options="playerOptions">-->
        <!--</video-player>-->
        <!--poster="@/assets/ZDimages/video_logo.jpg"-->
        <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>
        <!--<video id="videoRef" ref="videoRef"-->
               <!--v-if="learningData.postfix == 'mp4' || learningData.postfix == 'webm'"-->
               <!--autoplay controls  muted width="610px" height="429px"></video>-->
        <!--word-->
        <iframe
          class="iframe"
          v-if="learningData.postfix == 'pdf' || learningData.postfix == 'doc' || learningData.postfix == 'docx' || learningData.postfix == 'ppt' || learningData.postfix == 'pptx'"
          :src="learningData.iframeSrc" scrolling="auto" frameborder="0">
        </iframe>
        <!--富文本-->
        <div v-if="learningData.type == 5" v-html="learningData.chapterData" style="width:896px;margin:0 auto;"></div>
      </div>
      <div class="button-bottom-max-box" :class="timeType?'button-color-a':'button-color-b'" @click="shadeTypeClick(1)">完成学习</div>
    </div>
    <div class="shade-max-box" v-if="shadeType">
      <div class="shade-big-box">
        <img class="off-shade-button" src="@/assets/ZDimages/icon_jlfgz_gb_2.png" @click="shadeTypeClick(2)">
        <div class="shade-text-box">
          <p>您已学习完该章节</p>
          <p>已学习时长{{newTime}}，共获得{{integral}}奖励分</p>
          <img src="@/assets/ZDimages/img_wcxx.png">
          <p @click="shadeTypeClick(3)">学习下一章节</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import flvjs from 'flv.js'
  import { learnStart,learnFinish,profile } from "@/api/myPage/safeLearning";
  import { videoPlayer } from 'vue-video-player'
  import 'video.js/dist/video-js.css'
  export default {
    name: "startLearning",
    props:{
      infoId:{},
    },
    components:{
      videoPlayer
    },
    data() {
      return {
        videoCover:window.location.href.split('://')[0]+'://' + this.judgmentNetworkReturnAddress() + 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;
        });
      },
      //下一节方法
      nextSection(){
        // console.log("this.chapterIndex",this.chapterIndex);
        // console.log("this.festivalIndex",this.festivalIndex);
        // console.log("this.newList[this.chapterIndex]",this.newList[this.chapterIndex]);
        // console.log("this.newList[this.chapterIndex].children[this.festivalIndex]",this.newList[this.chapterIndex].children[this.festivalIndex]);
        // let endObj = {
        //   courseId:this.newList[this.chapterIndex].courseId,
        //   chapterId:this.newList[this.chapterIndex].children[this.festivalIndex].id,
        // };
        // // console.log("endObj",endObj);
        // learnFinish(endObj).then( res => {
        //   if(this.newList[this.chapterIndex].children.length > this.festivalIndex+1){
        //     //该章未学完
        //     console.log('该章未学完');
        //     this.festivalIndex++;
        //     this.learnFinish();
        //   }else{
        //     //该章已学完
        //     if(this.newList.length > this.chapterIndex+1){
        //       console.log('该章已学完');
        //       this.chapterIndex++;
        //       this.festivalIndex = 0;
        //       this.learnFinish();
        //     }else{
        //       //所有章节已学习学习完毕
        //       console.log('所有章节已学习学习完毕');
        //       this.msgSuccess('所有章节已学习完毕')
        //       this.$router.push({
        //         path: `/user/safeLearning`
        //       })
        //     }
        //   }
        // });
        if(this.newList[this.chapterIndex].children.length > this.festivalIndex+1){
          //该章未学完
          console.log('该章未学完');
          this.festivalIndex++;
          this.learnFinish();
        }else{
          //该章已学完
          if(this.newList.length > this.chapterIndex+1){
            console.log('该章已学完');
            this.chapterIndex++;
            this.festivalIndex = 0;
            this.learnFinish();
          }else{
            //所有章节已学习学习完毕
            console.log('所有章节已学习学习完毕');
            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,
        };
        learnStart(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.getVideo();
            // this.getVideoTwo();
          }else if(this.learningData.postfix == "pdf" || this.learningData.postfix == "doc" || this.learningData.postfix == "docx"||this.learningData.postfix == "ppt" || this.learningData.postfix == "pptx"){
            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,
          };
          // console.log("endObj",endObj);
          learnFinish(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(){
        console.log("fuwenben")
        this.learningData.chapterData = unescape(this.learningData.chapterData)
      },
      //视频处理
      getVideo(){
        let list = [];
        let obj = {
          type:'video/'+this.learningData.postfix,
          src:this.learningData.chapterData,
        };
        list.push(obj);
        this.playerOptions.sources = list;
      },
      //word处理
      async getWord(){
        this.learningData.iframeSrc = this.urlJudge(this.learningData.chapterData)
      },
      //视频事件
      demo(player){
        console.log("123",player)
      },
      //乘法
      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(){
        console.log('返回');
        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);
      console.log("beforeDestroy");
    },
    destroyed() {
      //清除定时器
      clearInterval(this.timer);
      console.log("destroyed");
    }
  }
</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;
      box-shadow: 0 0 8px 2px rgba(0, 0, 0, 0.1);
      .logo-img{
        height:57px;
        width:57px;
        margin:21px 20px 0 40px;
      }
      .title-p{
        width: 300px;
        font-size:18px;
        font-weight:700;
        line-height:100px;
      }
      .time-p{
        flex:1;
        font-weight:700;
        line-height:100px;
        font-size:14px;
      }
      .home-box{
        width:100px;
        display: flex;
        margin-top:35px;
        margin-right:30px;
        img{
          width:30px;
          height:30px;
          margin-right:20px;
        }
        p{
          line-height:30px;
        }
      }
      .user-box{
        min-width:100px;
        display: flex;
        margin-top:35px;
        margin-right:30px;
        img{
          width:30px;
          height:30px;
          margin-right:20px;
        }
        p{
          line-height:30px;
        }
      }
      .button-p{
        width:82px;
        height:34px;
        background: #0045af;
        color:#fff;
        text-align: center;
        line-height:34px;
        margin:33px 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-time-p{
          font-size:16px;
          line-height:40px;
          padding:0 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;
        }
      }
      .button-color-a{
        background: #0045af;
        color:#fff;
      }
      .button-color-b{
        background: #999;
        color:#fff;
      }
      .button-bottom-max-box{
        width:300px;
        height:40px;
        margin:20px auto;
        font-size:18px;
        text-align: center;
        line-height: 40px;
        border-radius:6px;
        cursor:pointer;
      }
    }
    .shade-max-box{
      height:100%;
      width:100%;
      position: fixed;
      background: rgba(0,0,0,0.4);
      overflow: hidden;
      .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>
