<template>
<div :class="['play', (state.sideBar ? '' : 'sidebar-hide')]">
  <div class="left-content">
    <div class="play-top cl" :style="(state.sideBar ? {} : { marginRight: 0 })">
      <router-link class="router-link-class" :to="{ path: `/app/my-learn/course-detail/${cid}` }"><i class="play-back el-icon-arrow-left"></i></router-link>
      <p>{{chapterList.title}}</p>
    </div>
    <div class="play-content">
      <router-view
        ref="comTotalChapter"
        :chapterName="curChapterName"
        :chapterId="chapterId"
        :courseInfo="courseInfo"
        :courseWork="courseWork"
        :chapterRead="chapterRead"
        :chapterWork="chapterWork"
        :chapterExam="chapterExam"
        :chapterVideo="chapterVideo"
        :ppts="chapterPpts"
        :videoType="videoType"
        @changeVideoArr="changeVideoArr"
        @handlePlayTime="handlePlayTime"
        @updateProgress="updateProgress"
      ></router-view>
    </div>
  </div>

  <div class="right-ctrl" :style="{ right: (state.sideBar ? 0 : -388) + 'px' }">
    <p class="ctrl-arrow" @click="changeSideBar('')"><span>&gt;</span></p>
    <div class="ctrl-pl">
      <ul class="pl-tab-hd">
        <li :class="[(state.sideBar === SIDEBAR_CHAPTER ? 'on' : '')]"><a :href="('#' + SIDEBAR_CHAPTER)" @click="changeSideBar(SIDEBAR_CHAPTER)">章节</a></li>
        <template v-if="state.isChapterVideo">
          <li :class="['br-l-line', (state.sideBar === SIDEBAR_PPT ? 'on' : '')]"><a :href="('#' + SIDEBAR_PPT)" @click="changeSideBar(SIDEBAR_PPT)">讲义</a></li>
        </template>
      </ul>
      <div class="pl-tab-bd">
        <template v-if="state.sideBar === SIDEBAR_CHAPTER">
          <side-chapter-list
            :list="chapterList"
            :sid="sid"
            :cid="cid"
          />
        </template>
        <template v-if="state.sideBar === SIDEBAR_PPT">
          <side-chapter-ppt
            ref="sidePpt"
            :ppt="pptList"
            @handleClickPpt="handleClickSidePpt"
          />
        </template>
      </div>
    </div>
  </div>
  <template v-if="!state.sideBar">
    <div class="switch">
      <a :href="('#' + SIDEBAR_CHAPTER)" class="switch-chapter" @click="changeSideBar(SIDEBAR_CHAPTER)">
        <i class="el-icon-self-wenjian"></i>
        <div>章节</div>
      </a>
      <template v-if="state.isChapterVideo">
        <a :href="('#' + SIDEBAR_PPT)" class="switch-handout" @click="changeSideBar(SIDEBAR_PPT)">
          <i class="el-icon-self-PPT"></i>
          <div>讲义</div>
        </a>
      </template>
    </div>
  </template>
</div>
</template>

<script>
import cAction from '@actions'
import cTool from '@tools'

import sideChapterList from './rightSide/sideChapterList.vue'
import sideChapterPpt from './rightSide/sideChapterPpt.vue'

export default {
  components: { sideChapterList, sideChapterPpt },
  props: {
    sid: { type: String, require: false },
    cid: { type: String, require: false },
    id: { type: String, require: false }, // 章节id
    videoType: { type: String, require: false } // 视频播放类型 // 1 是CC加密，2 是非加密，3 是阿里云
  },
  data () {
    return {
      SIDEBAR_CHAPTER: 'sidebar_chapter',
      SIDEBAR_PPT: 'sidebar_ppt',
      state: {
        sideBar: 'sidebar_chapter',
        isChapterVideo: false
      },
      chapterList: {
        // title: '',
        // currentChapterId: '11', // 当前章节id
        // course: [{
        //   title: '第一章：重要概念',
        //   chapters: [
        //     { id: '11', time: '28:18', name: '1.1 现值（PV）和终值（FV）' },
        //     { id: '12', time: '19:09', name: '1.2 净现值（NPV）及实际收益率' }
        //   ]
        // }, {
        //   title: '第二章：证券估值',
        //   chapters: [
        //     { id: '21', time: '27:49', name: '2.1 债券和股票的现金流贴现估值方法' },
        //     { id: '22', time: '16:04', name: '2.2 债券评级及债券协议' },
        //     { id: '23', time: '', name: '公司金融第二周测验' },
        //     { id: '24', time: '', name: '公司金融第二周作业' }
        //   ]
        // }],
        // nextVideo: {}, // 下一章 音视频对象
        // prevVideo: {} // 上一章音视频对象
      },
      pptList: {
        // imgUrls: [
        //   'http://pd4t7ae3m.bkt.clouddn.com/imgs-test1.jpg',
        //   'http://pd4t7ae3m.bkt.clouddn.com/imgs-test2.jpg',
        //   'http://pd4t7ae3m.bkt.clouddn.com/imgs-test3.jpg'
        // ], // 所有图片数组
        // current: 0, // 当前跟着音视频走，播放的是第几个图片
        // selectIndex: 0,
        // timeArr: [2, 10] // 时间数组，在这个时间时，图片需要切换到对应下角标图片
      },
      /* 课程资料 */
      courseInfo: [],
      /* 课程大作业 */
      courseWork: {},
      /* 当前选择 - 章节名字 */
      curChapterName: '',
      /* 当前选择 - 章节id */
      chapterId: '',
      /* 章节阅读 */
      chapterRead: {},
      /* 章节问题、作业提交 */
      chapterWork: {},
      /* 章节测试 */
      chapterExam: {},
      /* 章节视频 */
      chapterVideo: {},
      chapterPpts: []
    }
  },
  beforeRouteUpdate (to, from, next) {
    /* 只有 视频时 才有PPT */
    if (to.name === 'chapterVideo') {
      this.state.isChapterVideo = true
      const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
      let str = to.params.videoType !== '3' ? 'getCurrentChapterDetail' : 'getCurrentChapterDetailAliyun'
      cAction.chapterAction[str](to.params.id).then(json => {
        this.pptList = json.image
        this.chapterPpts = json.rData.ppts
      }).catch(e => { this.$message.error(e.message) }).finally(() => { loading.close() })
    } else {
      this.state.isChapterVideo = false
    }
    const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
    cAction.chapterAction.getChapterList(to.params.cid, to.params.sid, to.params.id).then(json => {
      this.chapterList = json.json
      this.courseInfo = json.courseInfo
      this.courseWork = json.courseWork
      /* 章节选择 */
      this.curChapterName = json.curJson.name
      this.chapterId = json.curJson.chapterId
      /* 如果 是 视频 再调用 进度信息接口 */
      if (json.curJson.type === 2) {
        cAction.chapterAction.getProgress(this.id, cTool.other.getIdt(), this.sid).then(_d => {
          this.chapterVideo = ((json.curJson.type === 2) && json.curJson.chapterVideo) || {}
          this.chapterVideo.progress = _d
        }).catch(e => { this.$message.error(e.message) })
      }
      this.chapterRead = ((json.curJson.type === 4) && json.curJson.chapterRead) || {}
      this.chapterExam = ((json.curJson.type === 3 && json.curJson.work_type === 1) && json.curJson.homework) || {}
      this.chapterWork = ((json.curJson.type === 3 && json.curJson.work_type === 2) && json.curJson.chapterWork) || {}
    }).catch(e => { this.$message.error(e.message) }).finally(() => { loading.close() })
    next()
  },
  mounted () {
    /* 只有 视频时 才有PPT */
    if (this.$route.name === 'chapterVideo') {
      this.state.isChapterVideo = true
      const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
      let str = this.videoType !== '3' ? 'getCurrentChapterDetail' : 'getCurrentChapterDetailAliyun'
      cAction.chapterAction[str](this.id).then(json => {
        this.pptList = json.image
        this.chapterPpts = json.rData.ppts
      }).catch(e => { this.$message.error(e.message) }).finally(() => { loading.close() })
    }
    const loading = this.$loading({ lock: true, text: '', spinner: '', background: 'rgba(255, 255, 255, 0.9)' })
    if (this.cid === '0' && this.sid === '0') {
      this.$message({
        message: 'URL异常，请点击“返回首页”，重新选择课程学习！',
        type: 'info',
        duration: 10000
      })
      loading.close()
      return
    }
    cAction.chapterAction.getChapterList(this.cid, this.sid, this.id).then(json => {
      this.chapterList = json.json
      this.courseInfo = json.courseInfo
      this.courseWork = json.courseWork
      /* 章节选择 */
      this.curChapterName = json.curJson.name
      this.chapterId = json.curJson.chapterId
      /* 如果 是 视频 再调用 进度信息接口 */
      if (json.curJson.type === 2) {
        cAction.chapterAction.getProgress(this.id, cTool.other.getIdt(), this.sid).then(_d => {
          this.chapterVideo = ((json.curJson.type === 2) && json.curJson.chapterVideo) || {}
          this.chapterVideo.progress = _d
        }).catch(e => { this.$message.error(e.message) })
      }
      this.chapterRead = ((json.curJson.type === 4) && json.curJson.chapterRead) || {}
      this.chapterExam = ((json.curJson.type === 3 && json.curJson.work_type === 1) && json.curJson.homework) || {}
      this.chapterWork = ((json.curJson.type === 3 && json.curJson.work_type === 2) && json.curJson.chapterWork) || {}
    }).catch(e => { this.$message.error(e.message) }).finally(() => { loading.close() })
  },
  methods: {
    changeSideBar (str) { this.state.sideBar = str },
    // 视频播放时间变更调用此方法
    handlePlayTime (time) {
      // 侧边ppt对应位置
      if (this.$refs.sidePpt) {
        this.$refs.sidePpt.setIndexByPoint(time)
      }
    },
    /* 通过 右侧 sider ppt 控制 左侧视频播放位置 */
    handleClickSidePpt (index) {
      const ppts = this.chapterPpts || []
      if (ppts.length > index && this.$refs.comTotalChapter) {
        const ppt = ppts[index]
        this.$refs.comTotalChapter.setVideoTime(ppt.ppt_point)
      }
    },
    updateProgress (_rProgress) {
      if (_rProgress.cpt) {
        /* 处理一下 视频帧栈，另存一个数组，防止请求事件过长，或超时，导致数据上送失败 */
        let _arr = []
        let _intCountPrev = 0
        for (let i = 0; i < _rProgress.ps.length; i++) {
          _arr[i] = _rProgress.ps[i]
          /* 客户端，处理一下，统计整个 视频帧数组 都有哪些帧 播过 */
          let _intCount = Math.floor(_rProgress.ps[i]) || 1
          if (_intCount !== _intCountPrev) {
            _rProgress.map[_intCount - 1] += 1
            _intCountPrev = _intCount
          }
        }
        /* 帧点取整 */
        let _arrTmp = _arr
        _intCountPrev = 0
        _arr = []
        for (let i = 0; i < _arrTmp.length; i++) {
          if (Math.floor(_arrTmp[i]) !== _intCountPrev) {
            _arr.push(Math.floor(_arrTmp[i]))
            _intCountPrev = Math.floor(_arrTmp[i])
          }
        }
        let _userInfo = window.G.UserInfo
        cAction.chapterAction.updateProgress({
          sid: (_userInfo && _userInfo.student_info && _userInfo.student_info.id) || '',
          uid: (_userInfo && _userInfo.uid) || '',
          d: cTool.other.getIdt(),
          i: cTool.other.getIdt(),
          c: this.cid,
          s: this.sid,
          v: _rProgress.vid, // this.id, // 这个不能保证退出组件时，刷新视频 从 crouse_work 切换 到 chapter_video
          _p: parseInt(_rProgress.pt), // 累计时间
          _m: parseInt(_rProgress.mpt), // 当前播放最大时间
          _c: parseInt(_rProgress.cpt), // 当前播放位置
          ps: _arr.join(',') // 播放时，播放过的 帧
          // map: _rProgress.map// 播放时，统计帧
        }).then(json => {
          if (json.success) {
            /* 将已经上传 并 成功的 帧 全部从 栈中删除 */
            for (let i = 0; i < _arr.length; i++) {
              _rProgress.ps.shift()
            }
          } else {
            /* 兼容 阿里云视频、CC视频 停止播放 */
            let $dom = document.getElementById('player')
            let flag = !!$dom.callAction
            flag ? ($dom.callAction('pause')) : ($dom.children[0].pause())
          }
        }).catch(e => {
          this.$message.error(e.message)
          /* 兼容 阿里云视频、CC视频 停止播放 */
          let $dom = document.getElementById('player')
          let flag = !!$dom.callAction
          flag ? ($dom.callAction('pause')) : ($dom.children[0].pause())
        }).finally(() => { })
      }
    },
    changeVideoArr (obj) {
      // beforeRouteUpdate 已经实现
      console.log('已经实现')
      obj.callback && obj.callback()
    }
  }
}
</script>


<style lang="scss" scoped>
  @import './index.css';
/* 右侧面板结构 */
.right-ctrl {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  z-index: 200;
  width: 350px;
  background: #212121;
  border-left: 19px solid #1b1b1b;
  /* 箭头 */
  .ctrl-arrow {
    position: absolute;
    top: 0;
    left: -19px;
    bottom: 0;
    width: 19px;
    height: 100%;
    font-size: 14px;
    color: #969696;
    cursor: pointer;
    span {
      position: absolute;
      top: 50%;
      left: 0;
      width: 19px;
      margin-top: -10px;
      text-align: center;
      color: #fff;
    }
  }
  /* 面板 */
  .ctrl-pl {
    position: relative;
    height: 100%;
    /* 头部 - 选择项 */
    .pl-tab-hd {
      margin: 0;
      padding: 15px 0;
      line-height: 1.6;
      background-color: #232323;
      overflow: hidden;
      li {
        float: left;
        position: relative;
        width: 50%;
        padding: 0;
        font-size: 16px;
        color: #909090;
        text-align: center;
        list-style: none;
        cursor: pointer;
        a {
          color: #909090;
          text-decoration: none;
        }
        &.on {
          a {
            color: #b49441;
          }
        }
      }
      .br-l-line {
        border-left: 1px solid #3f3f3f;
      }
    }
    /* 内部 - 列表项 */
    .pl-tab-bd {
      height: 94%;
    }
  }
}

</style>
