<template>
  <div class="video-player" id="player"></div>
</template>

<script>
export default {
  name: 'VideoPlayer',
  props: {
    isSkip: Boolean,
    video: Object,
    autoplay: { type: Boolean, default: true },
    disabled: { type: Boolean, default: false }
  },
  data() {
    let videoRetry = parseInt(window.localStorage.getItem('videoRetry'))
    videoRetry = isNaN(videoRetry) ? 3 : videoRetry
    return { player: null, videoRetry }
  },
  methods: {
    createPlayer() {
      const _this = this
      const { FD, LD, SD } = this.video
      /*
        "OD" : "原画"
        "FD" : "流畅"
        "LD" : "标清"
        "SD" : "高清"
        "HD" : "超清"
        "2K" : "2K"
        "4K" : "4K"
      */
      this.player = new Aliplayer(
        {
          id: 'player',
          source: JSON.stringify({ SD, LD, FD }),
          width: '100%',
          height: '100%',
          autoplay: this.autoplay,
          isLive: false,
          controlBarVisibility: 'always',
          definition: 'FD,LD,SD',
          defaultDefinition: 'SD',
          useHlsPluginForSafari: true,
          language: this.$i18n.locale === 'zh-CN' ? 'zh-cn' : 'en-us'
        },
        function (player) {
          // 禁止调整进度，隐藏声音和倍数
          if (_this.disabled) {
            $('.prism-volume, .prism-setting-speed').hide()
            $('.prism-progress').css('pointer-events', 'none')
          }

          player.on('ready', function () {
            // 跳过片头
            _this.isSkip && player.seek(6)
            _this.$emit('ready', player)
          })
          player.on('timeupdate', function (event) {
            const currentTime = player.getCurrentTime()
            _this.$emit('timeupdate', currentTime)
            if (currentTime > 1) {
              window.localStorage.setItem('videoRetry', 3)
            }
          })
          player.on('error', function (event) {
            _this.$emit('error', event)
            if (_this.videoRetry) {
              window.localStorage.setItem('videoRetry', _this.videoRetry - 1)
              window.location.reload()
            }
            console.log(event)
          })
          player.on('ended', function () {
            _this.$emit('ended')
          })
        }
      )
    }
  },
  mounted() {
    this.createPlayer()
  },
  beforeDestroy() {
    this.player && this.player.dispose()
  }
}
</script>

<style lang="scss" scoped>
.video-player {
  width: 100%;
  height: 100%;
}
</style>
