<template>
  <div>
    <div class="app-container">

      <div class="filter-container">
        <el-input v-model="KEYWORDS" placeholder="搜索课件名称或主讲人" class="filter-item" style="width: 200px;"/>
        <el-button v-waves class="filter-item ml-10" type="primary" icon="el-icon-search" @click="getQuery">
          搜索
        </el-button>
        <el-button v-waves class="filter-item" type="success" icon="el-icon-refresh" @click="goKeyReset">
          重置
        </el-button>
      </div>
      <el-table
        v-loading="listLoading"
        ref="multipleTable"
        :data="varList"
        :row-key="getRowKey"
        :header-cell-style="{
          'font-weight': 'bold',
          'color': '#000'
        }"
        tooltip-effect="dark"
        border
        fit
        highlight-current-row
      >
        <el-table-column
          :reserve-selection="true"
          type="selection"
          width="55"
          align="center"/>
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="COURSEWARETYPE" label="课件类别" align="center" width="140">
          <template slot-scope="{row}">
            {{ row.COURSEWARETYPE === '1' ? '视频课件' : '资料课件' }}
          </template>
        </el-table-column>
        <el-table-column prop="COURSEWARENAME" label="课件名称" />
        <el-table-column prop="SPEAKER" label="主讲人" width="100" align="center" />
        <el-table-column prop="CLASSHOUR" label="课件学时(分钟)" width="140" align="center"/>
        <el-table-column prop="COURSEWAREINTRODUCE" label="课件描述" />
        <el-table-column label="操作" align="center" width="300">
          <template slot-scope="{row}">
            <el-button v-if="row.COURSEWARETYPE === '1'" type="primary" icon="el-icon-collection" size="mini" @click="goViewVideo(row)">学习</el-button>
            <el-button v-if="row.COURSEWARETYPE === '2'" type="primary" icon="el-icon-collection" size="mini" @click="goViewPdf(row)">学习</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page-btn-group">
        <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
      </div>
    </div>
    <el-dialog :visible.sync="dialogViewVideo" title="视频" width="800px" @close="closePlay">
      <div>
        <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>
    </el-dialog>

    <el-dialog :visible.sync="dialogViewPdf" title="文档" width="90%" >
      <div>
        <pdf
          :page="pageNum"
          :src="pdfUrl"
          @progress="loadedRatio = $event"
          @num-pages="pageTotalNum=$event"
        />
        <div style="marginTop: 10px; color: #409EFF">{{ pageNum }} / {{ pageTotalNum }}</div>
        <el-button-group>
          <el-button type="primary" icon="el-icon-arrow-left" size="mini" @click="prePage">上一页</el-button>
          <el-button type="primary" size="mini" @click="nextPage">下一页<i class="el-icon-arrow-right el-icon--right"/></el-button>
        </el-button-group>
      </div>
    </el-dialog>
    <div class="ui-height" />
    <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 pdf from 'vue-pdf'
export default {
  components: { Pagination, videoPlayer, pdf },
  directives: { waves },
  data() {
    return {
      listLoading: true,
      add: false,
      del: false,
      edit: false,
      listQuery: {
        page: 1,
        limit: 10
      },
      total: 0,
      config: config,
      KEYWORDS: '',
      varList: [],
      pd: { // 用户视频播放返回值
        CURRICULUM_ID: '', // 课程ID
        VIDEOCOURSEWARE_ID: '', // 视频课件ID
        USER_ID: '', // 学员ID
        RESOURCETIME: '', // 播放时间
        PLAYCOUNT: ''// 播放次数
      },
      form: {
        COURSEWARENAME: '', // 课件名称
        SPEAKER: '', // 主讲人
        COURSEWAREINTRODUCE: '', // 课件介绍
        COURSEWAREFILES: '', // 课件文件路径
        COURSEWARECAPTURE: '', // 课件截图
        VIDEOUSERS: [], // 适用人员
        vfile: '',
        vcfile: ''
      },
      multipleSelectionAll: [], // 所有选中的数据包含跨页数据
      multipleSelection: [], // 当前页选中的数据
      dialogFormEdit: false,
      dialogType: 'add',
      LearnerCategoryList: [],
      serverurl: config.fileUrl,
      VIDEOCOURSEWARE_ID: '',
      dialogViewVideo: false,
      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 // 是否显示全屏按钮
        }
      },
      // pdf预览
      dialogViewPdf: false,
      pdfUrl: '',
      pageNum: 1,
      pageTotalNum: 1, // 总页数
      loadedRatio: 0, // 当前页面的加载进度，范围是0-1 ，等于1的时候代表当前页已经完全加载完成了

      timer: null,
      playTime: 0,
      isPaused: false
    }
  },
  created() {
    this.getList(this.ROLE_ID)
    this.getDict()
  },
  destroyed() {
    // 如果定时器在运行则关闭
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  methods: {
    getRowKey(row) {
      return row.COURSEWAREID
    },
    // 搜索
    getQuery() {
      this.$refs.multipleTable.clearSelection()
      this.getList()
    },
    goKeyReset() {
      this.KEYWORDS = ''
      this.getQuery()
    },
    // 获取列表
    getList() {
      this.listLoading = true
      requestFN(
        '/kcmiddlekj/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          KEYWORDS: this.KEYWORDS,
          CURRICULUMID: this.$parent.CURRICULUM_ID,
          STUDYTASK_ID: this.$parent.STUDYTASK_ID
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.varList
        this.total = data.page.totalResult
        this.hasButton()
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 判断按钮权限，用于是否显示按钮
    hasButton: function() {
      var keys = 'courseware:add,courseware:del,courseware:edit,toExcel'
      requestFN(
        '/head/hasButton',
        {
          keys: keys
        }
      ).then((data) => {
        this.add = data.coursewarefhadminadd		// 新增权限
        this.del = data.coursewarefhadmindel		// 删除权限
        this.edit = data.coursewarefhadminedit	// 修改权限
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 获取数据字典数据
    getDict: function() {
      requestFN(
        '/dictionaries/getLevels',
        {
          DICTIONARIES_ID: '532282f9c48346b8b646531909c739df'
        }
      ).then((data) => {
        this.LearnerCategoryList = data.list
      }).catch((e) => {

      })
    },
    // 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 = this.serverurl + row.COURSEWAREFILES
    //   this.playerOptions.poster = this.serverurl + row.COURSEWARECAPTURE
    //   this.playerOptions.sources[0].type = 'video/' + type
    //
    //   this.dialogViewVideo = true
    //   // this.playerOptions.autoplay = true
    //   if (this.isPaused) {
    //     this.$refs.videoPlayer.player.play()
    //   }
    //
    //   window.addEventListener('beforeunload', () => {
    //     console.info('beforeunload----------------------')
    //     if (this.timer) {
    //       clearInterval(this.timer)
    //       console.info('closed----------------------')
    //       // console.info(JSON.parse(sessionStorage.getItem('videoParams')))
    //       this.saveVideoRecord()
    //     }
    //   })
    //
    //   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()
    //     }
    //   }, 15000)
    // },

    goViewVideo(row) {
      this.$parent.videoMoudel = row
      this.$parent.activeName = 'Video'
    },
    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()
    },
    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()
    },
    saveVideoRecord() {
      requestFN(
        '/coursestudyvideorecord/save',
        {
          CURRICULUM_ID: this.$parent.STUDYTASK_ID,
          VIDEOCOURSEWARE_ID: this.VIDEOCOURSEWARE_ID,
          RESOURCETIME: this.playTime
        }
      ).then((data) => {
        this.pd = data.pd
      }).catch((e) => {
      })
    },
    getVideoProgress() {
      return new Promise((resolve) => {
        requestFN(
          '/coursestudyvideorecord/getVideoProgress',
          {
            CURRICULUM_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) => {
        })
      })
    },

    // pdf 预览
    goViewPdf(row) {
      this.$parent.pdfMoudel = row
      this.$parent.activeName = 'Pdf'
      // this.pageNum = 1
      // this.pdfUrl = config.fileUrl + filePath
      // console.log(this.pdfUrl)
      // this.dialogViewPdf = true
    },
    // 上一页
    prePage() {
      let page = this.pageNum
      page = page > 1 ? page - 1 : this.pageTotalNum
      this.pageNum = page
    },

    // 下一页
    nextPage() {
      let page = this.pageNum
      page = page < this.pageTotalNum ? page + 1 : 1
      this.pageNum = page
    },
    goBack() {
      this.$parent.activeName = 'Mine'
    }
  }
}

</script>

<style scoped>
  /*.vjs-progress-control{*/
  /*  display: none !important;*/
  /*  pointer-events: none !important;*/
  /*}*/
  /*.vjs-playback-rate{*/
  /*  display: none !important;*/
  /*}*/
</style>
