<template>
  <div class="m-right-block  fr mh576">
    <div v-if="show!=4">
      <ICourseInfo  :info="info" :tpl="tpl" @printCert="printCert" @startExam="startExam"></ICourseInfo>
    </div>
    <div class="right-block-bd ng-scope" ui-view="myStudyContent" style="position: relative;">
      <div class="m-account">
        <div class="account-tit" style="height:30px">
          <a :class="{'current':show===1}"  @click="show=1" class="">正在学习</a>
          <a :class="{'current':show===2}"  @click="show=2" class="">已经完成</a>
          <a :class="{'current':show===3}"  @click="show=3" class="" v-if="tpl.examGroupId>0||tpl.type=='检测试验人员'">考试记录</a>
          <a :class="{'current':show===4}" v-if="show==4" >{{media.name}}</a>
        </div>

        <div v-if="show <3" class="lwh-ul-form mt20">
          <!-- 列表展示 -->
          <el-table :data="showList.slice(page*size-size, page*size)" border stripe style="width: 100%;"  >
            <el-table-column label="课程名称" prop="name" min-width="200">
            </el-table-column>

            <el-table-column label="开始学习时间" prop="type" align="center" width="155">
              <template v-slot="{row}">
                <span>{{row.createAt||'-'}}</span>
              </template>
            </el-table-column>

            <el-table-column label="最近学习时间" prop="type" align="center" width="155">
              <template v-slot="{row}">
                <span>{{row.prevTick|toDatetime}}</span>
              </template>
            </el-table-column>

            <el-table-column label="学时" prop="xs" align="center" width="80">
              <template v-slot="{row}">
                <span> {{row.xs/10}}</span>
              </template>
            </el-table-column>

            <el-table-column label="学习进度" prop="useTime" align="left" width="200">
              <template v-slot="{row}">
                <span style="display: flex;">
                  <el-progress
                    type="line"
                    style="width: 120px;"
                    :stroke-width="26"
                    :text-inside="true"
                    :show-text="false"
                    :percentage="row.percent"
                    :class="row.percent|showProgressColor">
                  </el-progress>
                  <span style="margin-left: 10px;"> {{row.percent}}% </span>
                </span>
              </template>
            </el-table-column>

            <el-table-column label="操作" prop="xs" align="center" width="80">
              <template v-slot="{row, $index}">
                <el-button @click="loadMedia(row, $index)" type="text">播放</el-button>
              </template>
            </el-table-column>

          </el-table>
          <el-pagination :current-page="page" :page-size="size"
          :page-sizes="[5, 10, 20, 50, 100]"
          :style="{ float: 'right', padding: '20px' }"
           :total="showList.length"
           @current-change="(page)=>{this.page= page}"
           @size-change="(size)=>{this.size= size}"
           layout="total, sizes, prev, pager, next, jumper"></el-pagination>
        </div>

        <div v-if="show ==3" class="lwh-ul-form mt20">
          <exam-list :courseId="courseId"> </exam-list>
        </div>

        <div v-if="show ==4" class="lwh-ul-form mt20">
          <div>
            <i-media
              :media-id="mediaId"
              :options="options"
              :dialog="mediaDialog"
              :media="media"
              :duration="info.duration"
              :list = "list"
              :chapter = "chapter"
              @close="closeMedia"
              @loadMedia="loadMedia"
              :mediaType="mediaType"
              :heartbeat="heartbeat"
              :max-error-count="maxErrorCount"
              :collect-beat='collectBeat'
              :close-face="closeFace"
              @changeMedia="changeMedia"
              @updateOption = "updateOption"
              @update="update">
            </i-media>
          </div>
        </div>

        <el-dialog class="previewDialog" :visible.sync="testExamDalog"
          top="50px" width="1024px"
          @close="testExamDalog=false">
          <ICourseAnswerTest :info="info" :extraXs="extraXs" @updateExtraXs="updateExtraXs"> </ICourseAnswerTest>
        </el-dialog>
      </div>
     </div>


    <el-dialog title="输入认证" center :visible.sync="editRzcode"  >
      <el-form  label-width="120px" ref="elAdd">
        <el-form-item  label="认证编号">
          <el-input v-model="info.rzCode" type="text" disabled></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="cancelRzCode">取 消</el-button>
        <el-button @click="doAddRzCode" type="primary">确定打印</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {httpServer } from "@/components/httpServer/httpServer.js";
  import IMedia from "./components/iMedia.vue";
  import ExamList from "./components/ExamList.vue";
  import ICourseInfo from "./components/iCourseInfo.vue";
  import ICourseInfoTest from "./components/iCourseInfoTest.vue";
  import ICourseInfoXsExtra from "./components/iCourseInfoXsExtra.vue";
  import ICourseAnswerTest from "./components/iCourseAnswerTest.vue";
  import {getPercent} from '@/utils/index.js'
  import {toDatetime} from '@/utils/date.js'
  import {delExam} from '../exam/components/util.js'
  import md5 from 'js-md5';
  export default {
    name: "Index",
    data() {
      return {
        courseId: 0,
        show:1,
        mediaDialog: false,
        mediaType:'hls',
        mediaUrl:'',
        editRzcode: false,
        testExamDalog: false,
        info: {score:0, percent:0},
        tpl:{},
        media:{},
        extraXs:{},
        chapter:{required:[],normal:[]},
        page:1,
        size:5,
        mediaId:0,
        heartbeat:5,
        maxErrorCount:20,
        collectbeart: 20,
        closeFace: 0,
        options:{
          // controls:true,
          autoplay: false, // 如果true,浏览器准备好时开始回放。
          muted: false, // 默认情况下将会消除任何音频。
          loop: false, // 导致视频一结束就重新开始。
          preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
          language: 'zh-CN',
          aspectRatio: '4:3', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
          fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
          sources: [],
          poster: '', // 你的封面地址
          notSupportedMessage: '无法播放媒体源', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
          // controlBar: {
          //   timeDivider: true,
          //   durationDisplay: true,
          //   remainingTimeDisplay: false,
          //   fullscreenToggle: true
          // },
          playtimes:""
        },
        list: [],
        showList:[],
      };
    },
    components:{IMedia,ExamList,ICourseInfo,ICourseInfoTest,ICourseAnswerTest,ICourseInfoXsExtra},
    beforeMount() {
      this.courseId = +this.$route.params.courseId
      this.getData()
    },
    watch:{
      show(val){
        this.updateShowList()
      }
    },
    filters:{
      showProgressColor: function (val) {
      	if (val == '进行中') {
          	return val = 'el-bg-inner-running';
          } else if (val == '失败') {
             return val = 'el-bg-inner-error'
         } else if (val == '完成') {
             return val = 'el-bg-inner-done'
         }
      },
      toDatetime
    },
    methods: {
      changeMedia( val ){
        if( !val ) return;
        let mediaUrl = this.mediaUrl;
        if( val == 'ld'){
          mediaUrl = mediaUrl.replace('/hls/', '/ld/');
        }else{
          mediaUrl = mediaUrl.replace('/ld/', '/hls/');
        }
        this.mediaType = val;
        this.options.sources = [{src:mediaUrl,type: "application/x-mpegURL"}];
        this.options.playtimes = this.media.position||0;
        this.options.autoplay = true;
        this.mediaDialog = true;
      },
      updateInfo( param ){
        this.info = Object.assign(this.info, param);
      },
      startExamTest(){
        this.testExamDalog = true;
      },
      startExam( groupId ){
        let courseId = this.courseId
        let endDate = new Date( )
        delExam()
        this.$router.push({path:`/center/exam/${courseId}`, query:{groupId}});
      },
      printCert( ){
        if(  this.info.isPass ==0 ){
          this.$message.errorMsg("课程未完成", 2)
          return;
        }
        let {id, rzCode} = this.info
        // this.editRzcode = true
        httpServer('Cert.printCert', {rzCode, id}).then( res => {
          if( res.code == 200 ){
            this.editRzcode = false;
            this.info.tmpRzCode="";
            window.open(  res.data.url )
          }
        })
      },
      cancelRzCode(){
        this.info.rzCode= this.info.tmpRzCode;
        this.editRzcode = false;
      },
      doAddRzCode(){
        let {type, rzCode, id} = this.info;
        if( !rzCode ) rzCode = "sm"+id
        httpServer('Cert.printCert', {rzCode, id}).then( res => {
          if( res.code == 200 ){
            this.editRzcode = false;
            this.info.tmpRzCode="";
            window.open(  res.data.url )
          }
        })
      },
      formatFinish() {
        let {gxs,axs} = this.info;
        if( !axs ) axs = 1;
        return `获得${gxs}学时, 总共${axs}学时`;
      },
      formatExam() {
        let {score} = this.info
        if( score == -1 ) return `已答0次，未通过`;
        return `最高${score<1?0:score}分, ${score>=60?'通过':'未通过'}`;
      },
      formatPass() {
        let {score} = this.info
        if( score == -1 ) return `未参加`;
        return `${score||0}分,${score>=60?'通过':'未通过'}`;
      },
      formatString(val){
        return ()=> val;
      },
      calcChapter( list ){
        let required = {};
        let normal = {};
        let chapter = {required: [],normal: []}
        let requiredkeys = [];
        let normalkeys = [];
        for( let i in list){
          let item = list[i];
          if( item.required){
            if( required[ item.chapterName] ){
              required[ item.chapterName] = required[ item.chapterName]+item.xs
            }else{
              required[ item.chapterName ] = item.xs
              requiredkeys.push( item.chapterName )
            }
          }else{
            if( normal[ item.chapterName] ){
              normal[ item.chapterName] = normal[ item.chapterName]+item.xs
            }else{
              normal[ item.chapterName ] = item.xs
              normalkeys.push( item.chapterName )
            }
          }
        }
        for( let name of requiredkeys){
          chapter.required.push({name: name, active: false, xs:required[name]})
        }
        for( let name of normalkeys){
          chapter.normal.push({name: name, active: false, xs:normal[name]})
        }
        this.chapter = chapter;
      },
      getData() {
        let param = { courseId: this.courseId }
        httpServer("course.getCourse", param).then(res => {
          if (res.code == 200) {
            let {info, extra, list, tpl, extraXs} = res.data;
            this.info =  Object.assign( info, extra||{});
            this.heartbeat = res.data.heartbeat||5;
            this.collectBeat = res.data.collectBeat||20;
            this.maxErrorCount = res.data.maxErrorCount||3;
            this.closeFace = res.data.info.closeFace;
            this.tpl = tpl||{};
            this.extraXs = extraXs||{};
            this.list = list.map( (item)=>{
              item.percent = getPercent(item)||0;
              return item;
            })
            this.list.sort((i,j)=>{ return i.chapter-j.chapter?1:-1;})
            this.calcChapter( this.list );
            this.updateShowList()
          }
        })
      },
      updateShowList(){
        let show = this.show;
        this.showList = this.list.filter( item=>{
          if( show == 1) return !item.isFinish
          if( show == 2) return !!item.isFinish
          return false
        })
        //
        let gxs = 0
        let axs = 0;
        this.info.tcount = this.list.length;
        this.info.fcount =0;
        this.info.percent = 0;
        for( let i = 0; i< this.list.length;i++){
          let item = this.list[i]
          axs  += item.xs
          if( item.isFinish){
            gxs += item.xs
            this.info.fcount++
          }
        }
        this.info.gxs = gxs/10
        this.info.axs = axs/10
        this.info.percent = (this.info.gxs*10000/this.info.axs)/100;
      },
      updateOption( param ){
        this.options = Object.assign( this.options, param);
      },
      updateExtraXs( param ){
        this.extraXs = Object.assign( this.extraXs, param);
      },
      //
      update( item ){
        if( item.position> this.media.position) {
          this.media.position = item.position
        }
        this.media.isFinish = item.isFinish
        this.media.id = item.id
        this.media.percent = getPercent(this.media);
        this.updateShowList()
      },
      closeMedia(){
        this.mediaType = '';
        this.show = 1;
        this.mediaDialog=false;
      },
      // 加载媒体
      loadMedia( item, index ) {
        this.media = item;
        this.media.index = index
        httpServer('course.GetMedia', {id:item.id}).then( res => {
          if( res.code != 200) return;
          let {mediaUrl, id, position, duration, marks} = res.data||{};
          if( position >= duration) position = duration||0;
          this.mediaUrl = res.data.mediaUrl;
          this.options.marks = !!marks;
          this.media.position = position;
          this.options.playtimes = position+'';
          this.media.id = id;
          this.mediaId = id;
          this.mediaType ='hls'
          this.options.sources = [{src:this.mediaUrl,type: "application/x-mpegURL"}];
          this.show = 4
        });
      }
    }
  };
</script>

<style>
  @import "../../../assets/css/content.css";
  @import "../../../assets/css/course.css";
  @import url("../../../assets/css/m-account.css");
  @import url("./index.css");
  .media-dialog .el-dialog__header{
    /* display: none !important; */
   }
  .media-dialog .el-dialog__body{
    padding: 0 0 16px 0 !important;
   }
   .media-dialog .el-scrollbar__wrap {
    overflow-x: hidden!important;
  }
   .mprocess{
     margin: 0 auto;
     width: 150px !important;
   }
   .el-progress{
     width: 100%;
   }
   .el-progress__text{
     font-size: 16px;
     font-weight: 700;
     line-height:1.5;
     color: #3290D4;
   }
   .el-progress-bar__outer{
     height: 20px!important;
     border: 1px solid #78335f;
     background-color:transparent;
   }

   /* 渐变进度条 */
   .el-bg-inner-running .el-progress-bar__inner{
     background-color: unset;
     background-image: linear-gradient(to right, #3587d8 , #6855ff);
   }
   .el-bg-inner-error .el-progress-bar__inner{
     background-image: linear-gradient(to right, #3587d8 , #fb3a7e);
   }
   .el-bg-inner-done .el-progress-bar__inner{
     background-image: linear-gradient(to right, #3587d8 , #53ff54);
   }

</style>
