<template>
  <div class="video-warpz">
    <div v-show="shadows" class="viedo-sidows">
      <div class="viedo-drop">
        <div>
          请使用手机浏览器扫码,进行人脸识别(苹果用户请使用Safari浏览器)
        </div>
        <div style="margin: 15px 0">
          <vue-qr :text="qrcodeStr" :margin="0" :size="300" color-dark="#000" color-light="#fff" />
        </div>
        <el-button type="primary" @click="goBack">返回列表</el-button>
      </div>
    </div>
    <div class="video-area">
      <div class="bpx-player-video-area">
        <video-player
          ref="videoPlayer"
          :playsinline="true"
          :options="playerOptions"
          class="video-player vjs-custom-skin"
          @loadeddata="onPlayerLoadeddata($event)"
          @play="onPlayerPlay($event)"
          @pause="onPlayerPause($event)"
          @ended="onPlayerEnded($event)"
          @ready="playerReadied"
          @timeupdate="onPlayerTimeupdate($event)" />
      </div>
      <div class="video-side">
        <table class="table-ui">
          <tr>
            <td class="tbg">课程名称</td>
            <td>{{ videoMoudel.COURSEWARENAME }}</td>
          </tr>
          <tr>
            <td class="tbg">主讲人</td>
            <td>{{ videoMoudel.SPEAKER }}</td>
          </tr>
          <tr>
            <td class="tbg">课程介绍</td>
            <td>{{ videoMoudel.COURSEWAREINTRODUCE }}</td>
          </tr>
          <tr>
            <td class="tbg">岗位培训类型</td>
            <td>{{ videoPd.post_type_name }}</td>
          </tr>
          <tr>
            <td class="tbg">培训行业类型</td>
            <td>{{ videoPd.train_type_name }}</td>
          </tr>
        </table>
      </div>
    </div>
    <div class="ui-foot">
      <el-button plain type="info" @click="goBack">返 回</el-button>
    </div>
</div></template>

<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import waves from '@/directive/waves' // waves directive
import { videoPlayer } from 'vue-video-player'
import 'video.js/dist/video-js.css'
import vueQr from 'vue-qr'
export default {
  components: { Pagination, videoPlayer, vueQr },
  directives: { waves },
  data() {
    return {
      shadows: true,
      USER_ID: JSON.parse(sessionStorage.getItem('user')).USER_ID,
      qrcodeStr: '',
      fwebsocket: {},
      videoMoudel: {},
      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: 'video/mp4', // 类型
          src: config.fileUrl + 'uploadFiles/file/13cf0f4ec77e4d98ae8cdd9c3386ae0c/20210625/691910cd81024986a392f6203c4045f8.mp4' // url地址
        }],
        poster: '', // 封面地址
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: true, // 是否显示剩余时间功能
          fullscreenToggle: true // 是否显示全屏按钮
        }
      },

      VIDEOCOURSEWARE_ID: '',
      timer: null,
      playTime: 0,
      videoPd: {},
      isPaused: false,
      config: config
    }
  },
  created() {
    this.qrcodeStr = config.weburl + 'static/face/face_camera.html?USER_ID=' + this.USER_ID
    const videoMoudel = this.$parent.videoMoudel
    this.videoMoudel = videoMoudel
    this.goViewVideo(videoMoudel)
    this.joinWebSocket()
    this.getvideo(videoMoudel)
  },
  destroyed() {
    // 如果定时器在运行则关闭
    if (this.timer) {
      clearInterval(this.timer)
    }
    this.saveVideoRecord(0)
  },
  methods: {
    getvideo(row) {
      requestFN(
        '/videocourseware/goEdit',
        {
          VIDEOCOURSEWARE_ID: row.COURSEWAREID
        }
      ).then((data) => {
        this.videoPd = data.pd
      }).catch((e) => {
      })
    },
    joinWebSocket() {
      if (window.WebSocket) {
        this.fwebsocket = new WebSocket(encodeURI(config.faceOnlineAdress)) // oladress在main.jsp页面定义
        this.fwebsocket.onopen = () => {
          this.fwebsocket.send('[face]' + this.USER_ID) // 连接成功
        }
        this.fwebsocket.onerror = function() {
          // 连接失败
        }
        this.fwebsocket.onclose = function() {
          // 连接断开
        }
        // 消息接收
        this.fwebsocket.onmessage = (message) => {
          var messageMsg = JSON.parse(message.data)
          if (messageMsg.type == 'success') {
            this.shadows = false
            this.$refs.videoPlayer.player.play()
            this.isPaused = false
            console.log('shadows')
            var randomTiem = (Math.random() * 5).toFixed(0)
            setTimeout(() => {
              this.shadows = true
              this.$refs.videoPlayer.player.pause()
              this.isPaused = true
            }, (Number(randomTiem) + 10) * 60 * 1000)
          }
        }
      }
    },
    async goViewVideo(row) {
      // console.info(1)
      // if (this.VIDEOCOURSEWARE_ID != row.COURSEWAREID) {
      //   this.isPaused = false
      // }
      this.VIDEOCOURSEWARE_ID = row.COURSEWAREID
      await this.getVideoProgress()
      const type = row.COURSEWAREFILES.slice(row.COURSEWAREFILES.lastIndexOf('.') + 1)
      this.playerOptions.sources[0].src = config.fileUrl + row.COURSEWAREFILES
      this.playerOptions.poster = config.fileUrl + row.COURSEWARECAPTURE
      this.playerOptions.sources[0].type = 'video/' + type

      this.$refs.videoPlayer.player.pause()
      this.isPaused = true
      // this.playerOptions.autoplay = true
      // if (this.isPaused) {
      //   this.$refs.videoPlayer.player.play()
      // }
      window.addEventListener('beforeunload', () => {
        if (this.timer) {
          clearInterval(this.timer)
          // console.info(JSON.parse(sessionStorage.getItem('videoParams')))
          this.saveVideoRecord(0)
        }
      })

      this.timer = setInterval(() => {
        if (!this.isPaused) {
          // sessionStorage.setItem(
          //   'videoParams',
          //   JSON.stringify({
          //     userId: JSON.parse(sessionStorage.getItem('user')).USER_ID,
          //     videoId: row.DATACOURSEWARE_ID,
          //     RESOURCETIME: this.playTime
          //   })
          // )
          // console.info(JSON.parse(sessionStorage.getItem('videoParams')))
          this.saveVideoRecord(0)
        }
      }, 15000)
    },
    onPlayerLoadeddata(player) {
      // console.info(4)
      // player.play()
    },
    // 监听播放
    onPlayerPlay(player) {
      this.isPaused = false
    },
    // 监听暂停
    onPlayerPause(player) {
      this.isPaused = true
    },
    // 当前播放位置发生变化时触发。
    onPlayerTimeupdate(player) {
      this.playTime = player.cache_.currentTime
    },
    onPlayerEnded(player) {
      // 如果定时器在运行则关闭
      if (this.timer) {
        clearInterval(this.timer)
      }
      this.isPaused = true
      this.playTime = 0
      // sessionStorage.setItem(
      //   'videoParams',
      //   JSON.stringify({
      //     userId: JSON.parse(sessionStorage.getItem('user')).USER_ID,
      //     // videoId: row.DATACOURSEWARE_ID,
      //     resourceTime: 0
      //   })
      // )
      this.saveVideoRecord(1)
    },
    playerReadied(player) {
      // if (JSON.parse(sessionStorage.getItem('videoParams')).resourceTime) { player.currentTime(JSON.parse(sessionStorage.getItem('videoParams')).resourceTime) }
      player.currentTime(this.playTime)
      // console.info(3)
    },
    closePlay() {
      if (this.timer) {
        clearInterval(this.timer)
      }
      this.$refs.videoPlayer.player.pause()
      this.saveVideoRecord(0)
    },
    saveVideoRecord(isEnd) {
      if (this.playTime != '0') { // 去除进入页面后直接返回，没有播放的情况
        requestFN(
          '/coursestudyvideorecord/save',
          {
            CURRICULUM_ID: this.$parent.CURRICULUM_ID,
            STUDYTASK_ID: this.$parent.STUDYTASK_ID,
            VIDEOCOURSEWARE_ID: this.VIDEOCOURSEWARE_ID,
            RESOURCETIME: this.playTime,
            IS_END: isEnd,
            TYPE: 1
          }
        ).then((data) => {
          this.pd = data.pd
        }).catch((e) => {
        })
      }
    },
    getVideoProgress() {
      return new Promise((resolve) => {
        requestFN(
          '/coursestudyvideorecord/getVideoProgress',
          {
            STUDYTASK_ID: this.$parent.STUDYTASK_ID,
            VIDEOCOURSEWARE_ID: this.VIDEOCOURSEWARE_ID
          }
        ).then((data) => {
          if (data.pd != '') {
            this.pd = data.pd
            this.playTime = this.pd.RESOURCETIME
            // console.info(2)
          }
          resolve()
        }).catch((e) => {
        })
      })
    },
    goBack() {
      // this.$refs.videoPlayer.player.play()
      this.$parent.activeName = 'Courseware'
    }
  }
}
</script>

<style lang="scss" scoped>
.video-warpz {
  min-height: calc(100vh - 150px);

  .viedo-sidows {
    position: absolute;
    z-index: 999;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
    .viedo-drop {
      background: #fff;
      padding: 20px;
      width: 420px;
      margin: 0 auto;
      text-align: center;
      border-radius: 10px;
      height: 500px;
      margin-top: 100px;
    }
  }
  .video-area {
    display: flex;
    position: relative;
    padding: 20px;
    .bpx-player-video-area {
      width: 1100px;
      height: auto;
    }
    .video-side {
      margin-left: 30px;
    }
  }
}
</style>
