<template>
  <div ref="videoWrapper">
    <video
      v-if="isAdd"
      ref="videoPlayer"
      class="video-js vjs-default-skin vjs-big-play-centered vjs-16-9"
      id="videoJS"
    ></video>
  </div>
</template>

<script>
import videojs from 'video.js'
import 'video.js/dist/video-js.css'

const DEFAULT_OPTIONS = {
  controls: true,
  autoplay: false,
  fluid: true
}

export default {
  name: 'AppVideoPlayer',
  props: {
    isAdd: {
      type: Boolean,
      default: false
    },
    options: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      player: null,
      times: Date.parse(new Date())
    }
  },
  computed: {
    videoOptions() {
      return Object.assign({}, DEFAULT_OPTIONS, this.options)
    }
  },
  watch: {
    options: {
      deep: true,
      handler() {
        if (this.player) {
          this.player.dispose()
          this.player = null
        }
        this.createVideo()
        this.$nextTick(() => {
          this.initPlayer()
        })
      }
    }
  },
  mounted() {
    if (this.isAdd) {
      this.initPlayer()
    }
    this.player && this.initPlayer()
    // this.$emit()
  },
  beforeUnmount() {
    this.player && this.player.dispose()
  },
  methods: {
    createVideo() {
      const html = `<video class="video-js vjs-default-skin vjs-big-play-centered vjs-16-9" id="videoJS"></video>`
      this.$refs.videoWrapper.innerHTML = html
    },
    initPlayer() {
      const self = this
      this.player = videojs(document.querySelector('#videoJS'), this.videoOptions, function onPlayerReady() {
        self.$emit('ready', this)
        self.$emit('videoHeight', document.getElementById('videoJS')?.offsetHeight)
        self.$emit('videoWidth', document.getElementById('videoJS')?.offsetWidth)
        const DEFAULT_EVENTS = [
          'abort',
          'canplay',
          'canplaythrough',
          'durationchange',
          'emptied',
          'ended',
          'error',
          'loadeddata',
          'loadedmetadata',
          'pause',
          'play',
          'playing',
          'progress',
          'ratechange',
          'resize',
          'seeked',
          'seeking',
          'stalled',
          'suspend',
          'timeupdate',
          'volumechange',
          'waiting'
        ]
        // 注册事件
        DEFAULT_EVENTS.forEach(eventName => {
          this.on(eventName, (...args) => {
            self.$emit(eventName, ...args)
          })
        })
      })
    }
  }
}
</script>
