<!--
 * @Author: 纪泽龙 jizelong@qq.com
 * @Date: 2022-09-20 20:14:18
 * @LastEditors: 纪泽龙 jizelong@qq.com
 * @LastEditTime: 2023-02-03 15:59:38
 * @FilePath: /danger-manage-web/src/views/myLessons/CheckLesson.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="check-lession flex">
    <div class="top-title">
      <div class="item allone">
        <div class="text">{{ state != 2 ? "学习课程" : "查看课程" }}</div>
        <div v-if="userlessonData.state!=3" class="gotime">{{minute}}:{{calculation(second)}}/{{parseInt(lessonData.duration/60)}}:{{calculation(lessonData.duration%60)}}</div>
        <div v-if="userlessonData.state==3" style="background: red" class="gotime"> 已过期 </div>
      </div>

      <div class="bt flex fz14 border-bottom">
        <div class="a">课程标题</div>
        <div class="b">
          <div>{{ lessonData.courseName }}</div>
        </div>
      </div>

      <div class="bt flex fz14 border-bottom">
        <div class="a">培训计划</div>
        <div class="b">
          <div>{{ lessonTypeName }}</div>
        </div>
      </div>

      <div class="bt flex fz14 border-bottom">
        <div class="a">课程内容</div>
        <div class="b" v-html="lessonData.courseConent">
          <!-- <div>安全生产规范</div>
          <div>安全生产规范</div>
          <div>安全生产规范</div>
          <div>安全生产规范</div>
          <div>安全生产规范</div> -->
        </div>
      </div>

      <div class="bt flex fz14 video" >
        <div class="a">视频文件</div>
        <div class="b">
          <div class="video" v-if="lessonData.video">
            <video-player
              class="video-player vjs-custom-skin"
              ref="videoPlayer"
              :playsinline="true"
              :options="playerOptions"
            ></video-player>
          </div>
          <div v-else>未上传视频</div>
        </div>
      </div>

      <div class="bt flex fz14" v-if="lessonData.enclosure">
        <div class="a">学习附件</div>
        <div class="b flex">
          <div class="download flex">
            <span>学习资料</span>
            <el-button style="padding: 0; margin-left: 20px" type="text">
              <a :href="lessonData.enclosure">下载</a>
            </el-button>
            <el-button style="padding: 0; margin-left: 20px" type="text">
              <a @click="openXslx(lessonData.enclosure)">预览</a>
            </el-button>
          </div>
        </div>
      </div>

      <div class="bt flex fz14" v-if="lessonData.video">
        <div class="a">学习视频</div>
        <div class="b flex">
          <div class="download flex">
            <span>学习视频</span>
            <el-button style="padding: 0; margin-left: 20px" type="text">
              <a @click="downLoad(lessonData.video, lessonData.courseName)"
                >下载</a
              >
            </el-button>
          </div>
        </div>
      </div>

      <div v-if="state == 2&&lessonData.topicNum!=0" class="bt flex fz14">
        <div class="a">考试结果</div>
        <div style="color: #1d84ff" class="b flex">
          已完成学习，课后测试得分{{ fenshu }}，成绩合格！
        </div>
      </div>

      <div class="btn-wrapper flex">
        <!-- topicNum>0代表有考试题，没考试题不需要考试 -->
        <el-button v-if="this.finish &&lessonData.topicNum>0 " @click="againQuesstion" type="primary">{{
          state == 2 || state == 1 ? "重新考试" : "开始考试"
        }}</el-button>
        <el-button @click="$router.back()" type="primary" plain>取消</el-button>
      </div>
    </div>
    <AnswerLesson
      v-if="answerOpen"
      :courseId="courseId"
      :userCourseId="userCourseId"
      :courseName="lessonData.courseName"
      :visible.sync="answerOpen"
      @jj="jj"
    />
    <el-dialog :visible.sync="iframeVisible" width="80%">
      <!--<div v-if="userlessonData.state!=3" class="gotime2">{{minute}}:{{calculation(second)}}/{{parseInt(lessonData.duration/60)}}:{{calculation(lessonData.duration%60)}}</div>-->
      <iframe style="width: 100%; height: 600px" :src="ky"></iframe>
    </el-dialog>
  </div>
</template>

<script>
import { getLessonById,getUserLessonById ,changeUserLesson} from "@/api/train/lessonsProgram";
import { getPlanList } from "@/api/train/trainingProgram";

import AnswerLesson from "../components/AnswerLesson";
export default {
  name: "CheckLesson",
  components: {
    AnswerLesson,
  },
  data() {
    return {
      finish:false,
      minute:0,
      second:0,
      playerOptions: {
        aspectRatio: "16:9",
      },

      dingshi:null,
      // 课程类型
      courseOptions: [],
      lessonData: {},
      userlessonData:{},
      // 课程id
      courseId: 0,
      // 用户学习id
      userCourseId: 0,
      state: 0,
      fenshu: 0,
      answerOpen: false,
      lessonTypeName: "",
      iframeVisible: false,
      ky: "https://view.xdocin.com/222-223-203-154-8082_o52uv3.htm",
    };
  },
  created() {
    this.saveId();
    this.getPlanList();
    this.getLessonById();
  },
  destroyed(){
    console.log('销毁');
    this.updateUserCourse();
    clearInterval(this.dingshi);
  },
  methods: {
    getPlanList() {
      getPlanList().then((res) => {
        this.courseOptions = res.data.map((item) => {
          return {
            planId: item.planId,
            planName: item.planName,
          };
        });
        this.lessonTypeName = this.courseOptions.find(
          (item) => item.planId == this.lessonData?.courseType
        ).planName;
      });
    },
    saveId() {
      const { courseId, userCourseId, state, fenshu } = this.$route.query;
      this.courseId = +courseId;
      this.userCourseId = +userCourseId;
      this.state = state;
      this.fenshu = fenshu;
    },

    getLessonById() {
      const { courseId, userCourseId } = this.$route.query;
      getLessonById(courseId).then((res) => {
        if (res.code == 200) {
          this.lessonData = res.data;
          console.log(this.lessonData);
          this.changeVideo(this.lessonData.video);
        }
      });
      getUserLessonById({"userCourseId":userCourseId}).then((res) => {
          if (res.code == 200) {
            this.userlessonData = res.data;
            this.second = this.userlessonData.finishDuration%60;
            this.minute = parseInt( this.userlessonData.finishDuration/60);
            if(this.userlessonData.state!=3){
              this.dingshi = setInterval(this.goTime,1000);

            }

          }
      });
    },
    goTime(){
      if(this.userlessonData.finishDuration>=this.lessonData.duration){
        console.log("结束");
        clearInterval(this.dingshi);
        this.userlessonData.trainState=1;
        this.userlessonData.finishDuration = this.lessonData.duration;
        this.updateUserCourse();
      }else {
         this.userlessonData.finishDuration = this.userlessonData.finishDuration+1;
         //console.log(this.userlessonData.finishDuration);
        this.second = this.userlessonData.finishDuration%60;
        this.minute = parseInt( this.userlessonData.finishDuration/60);
        if(this.userlessonData.finishDuration%60==0){
          this.updateUserCourse();
        }
      }
    },
    updateUserCourse(){
      this.userlessonData.state = null;
      changeUserLesson(this.userlessonData).then(response => {
        if(this.userlessonData.finishDuration == this.lessonData.duration){
          this.finish = true;
        }
      })
    },
    calculation(num){
      if(num<10){
        num = "0"+num;
      }
      return num;
    },
    changeVideo(src) {
      this.playerOptions = {
        // 视频播放
        playbackRates: [0.5, 1.0, 1.5, 2.0], //可选择的播放速度
        autoplay: false, //如果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: [
          {
            type: "",
            src, //url地址
          },
        ],
        poster: "", //你的封面地址
        // width: document.documentElement.clientWidth,
        notSupportedMessage: "此视频暂无法播放，请稍后再试", //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, //当前时间和持续时间的分隔符
          durationDisplay: true, //显示持续时间
          remainingTimeDisplay: false, //是否显示剩余时间功能
          fullscreenToggle: true, //全屏按钮
        },
      };
    },
    againQuesstion() {
      this.answerOpen = true;
    },
    jj(e) {
      if (e.answer >= e.qualifiedNum) {
        this.fenshu = Math.floor((e.answer / e.topicNum) * 100);
        this.state = 2;
      }
    },
    downLoad(url, name) {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "arraybuffer"; // 返回类型blob
      xhr.onload = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          let blob = this.response;
          console.log(blob);
          // 转换一个blob链接
          // 注: URL.createObjectURL() 静态方法会创建一个 DOMString(DOMString 是一个UTF-16字符串)，
          // 其中包含一个表示参数中给出的对象的URL。这个URL的生命周期和创建它的窗口中的document绑定
          let downLoadUrl = window.URL.createObjectURL(
            new Blob([blob], {
              type: "video/mp4",
            })
          );
          // 视频的type是video/mp4，图片是image/jpeg
          // 01.创建a标签
          let a = document.createElement("a");
          // 02.给a标签的属性download设定名称
          a.download = name;
          // 03.设置下载的文件名
          a.href = downLoadUrl;
          // 04.对a标签做一个隐藏处理
          a.style.display = "none";
          // 05.向文档中添加a标签
          document.body.appendChild(a);
          // 06.启动点击事件
          a.click();
          // 07.下载完毕删除此标签
          a.remove();
        }
      };
      xhr.send();
    },
    openXslx(url, name) {
      // window.open(`https://view.xdocin.com/view?src=${url}`);
      console.log(url)
      this.ky=`https://view.xdocin.com/view?src=${url}`;
      this.iframeVisible=true;
    },
  },
};
</script>
<style lang="scss" scoped>
.check-lession {
  // width: 91.3%;
  width: 100%;
  height: calc(100vh - 50px);
  overflow: auto;
  justify-content: center;

  .top-title {
    padding-top: 14px;
    padding-bottom: 14px;
    width: 93.2%;
    max-width: 1600px;
    .item {
      margin-bottom: 10px;
    }
    .bt {
      padding-bottom: 10px;
      margin-bottom: 10px;
      width: 85%;
      min-width: 1050px;
      .a {
        width: 70px;
        color: #101010;
      }
      .b {
        flex: 1;
        color: #606266;

        .video {
          width: 870px;
          height: 489px;
        }
      }
      &.border-bottom {
        border-bottom: 1px solid #bbbbbb;
        &.viedo-wrapper {
          border-bottom: none;
        }
      }
    }
    .btn-wrapper {
      justify-content: center;
    }
  }
}
.allone{
  display:flex;
  flex-direction:row;
  justify-content:flex-start;
}
  .gotime{
       background: #1c84c6;
       width: 80px;
       text-align: center;
       line-height: 22px;
       color: white;
       margin-left: 40px;
       border-radius: 10px;
     }
.gotime2{
  background: #1c84c6;
  width: 80px;
  text-align: center;
  line-height: 22px;
  color: white;
  margin-left: 20px;
  border-radius: 10px;
  position: absolute;
  top: 20px;
}
</style>
