<template>
  <div>
    <video ref="videoPlayer" class="video-js video-player">
      <p>您的浏览器暂不支持本播放器，推荐使用Chrome等主流浏览器访问视频。</p>
    </video>
    <div v-show="!isSrc && playlist.length > 0" class="vjs-playlist"></div>
    <!-- <div v-show="playlist.length > 0" class="vjs-playlist"></div> -->
  </div>
</template>
<script>
import 'video.js/dist/video-js.css'
import '@videojs/themes/city/index.css'
import '@videojs/themes/fantasy/index.css'
import '@videojs/themes/forest/index.css'
import '@videojs/themes/sea/index.css'
import 'videojs-playlist-ui/dist/videojs-playlist-ui.vertical.css'
import './assets/css/default.css'
import enObj from  './assets/lang/en.json'
import zhObj from './assets/lang/zh-CN.json'
import videojs from 'video.js'
import 'videojs-playlist/dist/videojs-playlist.js'
import 'videojs-playlist-ui/dist/videojs-playlist-ui.js'
export default {
  name: 'st-video-player',
  props: {
    src: {
      type: String,
      default() {
        return null
      }
    },                                  // 视频源
    options: {
      type: Object,
      default() {
        return {
        }
      }
    },                                  // 传入的播放器选项设置
    /**
     * 播放列表单个元素内容如下示例：
     * {
     *    sources: [{
     *      src: 'URL地址',
     *      type: 'video/mp4' 
     *    }],
     *    poster: '海报封面URL地址'
     * }
     * @see {@link https://github.com/brightcove/videojs-playlist/blob/master/docs/api.md}
     */
    playlist: {
      type: Array,
      default() {
        return []
      }
    },                                  // 播放列表
    showForwardBtn: {
      type: Boolean,
      default() {
        return false
      }
    },                                  // 是否开启视频快进快退功能
    showFlipBtn: {
      type: Boolean,
      default() {
        return true
      }
    },                                  // 是否开启视频翻转功能
    showSettingBtn: {
      type: Boolean,
      default() {
        return false
      }
    },                                  // 是否开启播放器设置功能
    showPictureInPictureBtn: {
      type: Boolean,
      default() {
        return false
      }                                 // 是否开启画中画功能
    }
  },
  data() {
    return {
      defaultOptions: {
        /**
         * ******************************************************************
         *                          标准video标签选项
         * ******************************************************************
         */
        autoplay: false,                 // 是否自动播放
        controls: true,                 // 是否允许用户控制视频的播放等操作
        loop: false,                    // 是否循环播放
        muted: false,                   // 是否静音播放
        poster: '',                     // 视频海报、封面URL
        preload: 'auto',                // 视频预加载模式，默认遵循浏览器定义
        src: '',                        // 视频播放URL地址
        height: 500,

        /**
         * ******************************************************************
         *                          video.js特定选项
         * ******************************************************************
         */
        // aspectRatio: '4:3',             // 播放器宽高比
        // language: 'zh',              // 播放器默认语言为中文简体，以index.html文件指定的语言为准
        playbackRates: [1, 1.5, 2],     // 播放倍速
        playOnSelect: true,             // 播放列表中是否默认选择播放
      },                                // 默认播放器选项配置

      player: null,                     // 播放器
      flipBtn: null,                    // 视频翻转按钮
      isFliped: false,                  // 视频是否翻转标志
      settingBtn: null,                 // 播放器设置按钮
      isSrc: false,                      // 是否是通过src传入单视频
      forwardBtn: null,   // 快进
      backwardBtn: null,  // 快退
    }
  },
  watch: {
    playlist: function(val) {
      this.isSrc = false
      if (val && val.length > 0) {
        this.playVideo(val)
      }
    },
    src: function(val) {
      this.isSrc = true
      if (val) {
        let list = []
        let _item = {
          name: 'video',
          sources: [{
            src: val || '',
            type: 'video/mp4'
          }]
        }
        list.push(_item)
        this.playVideo(list)
      }
    }
  },
  mounted() {
    this.initial()
    if(this.showForwardBtn) {
      let self = this
      document.onkeydown = function(){
        switch(window.event.keyCode){
          case 37:
            if (self.player) {
              self.player.currentTime(self.player.currentTime() - 5)
            }
            break;
          case 39:
            if (self.player) {
              self.player.currentTime(self.player.currentTime() + 5)
            }
            break;
          default:
          break;
        }
      }
    }
  },
  beforeDestroy() {
    if (this.player) {
      this.player.dispose()
      this.player = null
    }
  },
  methods: {
    /**
     * @descripton: 注册视频播放
     * @param {Array} val
     * @return {*}
     * @Author: YYX
     */
    playVideo(val) {
      this.player.playlist(val)
      this.player.playlistUi()
      let that = this
      // 为每一个播放列表视频元素添加点击事件
      let playItemArr = document.querySelectorAll('.vjs-playlist-item')
      playItemArr.forEach(item => {
        item.addEventListener('click', () => {
          let domItem = item.querySelector('.vjs-playlist-name')
          if (domItem) {
            that.$emit('stClickVideoItem', domItem.innerHTML)
            this.isFliped && this.flipBtn.trigger('click')
          } else {
            console.error('[ST-VIDEO-PLAYER Error]:未找到指定的播放列表元素DOM，vjs-playlist-name')
          }
        })
      })
    },
    /**
     * 播放器初始化
     */
    initial() {
      // 播放器选项合并
      let videoOptions = Object.assign({}, this.defaultOptions, this.options)

      // 播放器添加国际化支持
      videojs.addLanguage('en', enObj)
      videojs.addLanguage('zh', zhObj)

      this.player = videojs(this.$refs.videoPlayer, videoOptions, function onPlayerReady() {
        // todo 打点，变色
        // that.progressSign(that.videoItem['phase'], that.twoPersonDetectList, that.player.duration())
      })

      // 添加自定义功能
      if (this.player && (this.showFlipBtn || this.showSettingBtn  || this.showForwardBtn)) {
        let controlBar = this.player.getChild('controlBar')
        let Button = videojs.getComponent('Button')

        // 添加视频翻转按钮
        if (this.showFlipBtn) {
          let flip = new Button(this.player)
          flip.controlText('Flip')
          flip.addClass('vjs-icon-flip')
          flip.on('click', () => {
            let videoDom = document.getElementsByTagName('video')
            videoDom[0] && (videoDom[0].style['transform'] = this.isFliped ? 'none' : 'perspective(1px) rotateY(180deg)')
            this.isFliped = !this.isFliped
          })
          this.flipBtn = controlBar.addChild(flip)
        }
        // 添加视频快进快退按钮
        if (this.showForwardBtn) {
          // 快退
          let backward = new Button(this.player)
          backward.controlText('Backward')
          backward.addClass('vjs-icon-backward')
          backward.on('click', () => {
            this.player.currentTime(this.player.currentTime() - 5)
          })
          this.backwardBtn = controlBar.addChild(backward)
          // 快进
          let forward = new Button(this.player)
          forward.controlText('Forward')
          forward.addClass('vjs-icon-forward')
          forward.on('click', () => {
            this.player.currentTime(this.player.currentTime() + 5)
          })
          this.forwardBtn = controlBar.addChild(forward)
        }

        // todo 添加播放器设置按钮
        if (this.showSettingBtn) {
          let setting = new Button(this.player)
          setting.controlText('Setting')
          setting.addClass('vjs-icon-setting')
          setting.on('click', () => {
            let videoPlayerDom = document.getElementById('videoPlayer')
            videoPlayerDom.className = 'video-js vjs-theme-sea'
          })
          this.settingBtn = controlBar.addChild(setting)
        }

        // 添加播放列表
        if (this.playlist.length > 0) {
          this.player.playlist(this.playlist)
          this.player.playlistUi()
        }
      }

      // 添加画中画展示功能
      let pictureBtn = document.querySelector('.vjs-picture-in-picture-control')
      if (this.player && pictureBtn) {
        if (this.showPictureInPictureBtn) {
          pictureBtn.style = 'display: block;'
        } else {
          pictureBtn.style = 'display: none;'
        }
      }
    },

    /**
     * 设置当前视频
     * @param {int} index 视频索引，从0开始计数
     */
    setCurrentVideoIndex(index) {
      this.player.playlist.currentItem(index)
    },

    /**
     * 获取当前视频索引
     * @returns {int} 视频索引，从0开始计数，如播放器无播放列表，则返回 -1
     */
    getCurrentVideoIndex() {
      return this.player.playlist.currentItem()
    },

    /**
     * 下一个视频
     */
    nextVideo() {
      return this.player.next()
    },

    /**
     * 上一个视频
     */
    previousVideo() {
      return this.player.previous()
    },

    /**
     * 设置当前播放时间
     */
    setCurrentTime(seconds) {
      this.player.currentTime(seconds)
    },

    /**
     * 播放
     */
    play() {
      this.player.play()
    },

    /**
     * 暂停
     */
    pause() {
      this.player.pause()
    },
  }
}
</script>
<style>
  .video-player {
    display: inline-block;
  }
  .vjs-playlist {
    display: inline-block;
    width: 100px;
    height: 500px;
  }
  .vjs-playlist .vjs-playlist-name {
    color: #ccc;
  }
  .vjs-playlist.vjs-playlist-vertical .vjs-playlist-item {
    cursor: pointer;
  }
  .vjs-playlist.vjs-playlist-vertical .vjs-playlist-item .vjs-playlist-thumbnail-placeholder {
    height: 42px;
  }
  .vjs-playlist .vjs-selected .vjs-playlist-title-container {
    font-weight: 900;
    background-color: #666;
  }
  .vjs-playlist .vjs-selected .vjs-playlist-title-container .vjs-playlist-name {
    color: white;
  }
 .vjs-playlist .vjs-selected .vjs-playlist-now-playing-text, .vjs-playlist .vjs-up-next .vjs-up-next-text {
    display: none;
  }
  .vjs-remaining-time.vjs-time-control.vjs-control > span:nth-child(2) {
    display: none;
  }
  .video-js .vjs-big-play-button {
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
</style>