<template>
  <div class="aos-video" v-if="showVideo">
    <video class="video-js" ref="videoPlayer"></video>
  </div>
</template>

<script>
import 'video.js/dist/video-js.min.css'
import videojs from 'video.js';
export default {
  name: 'AosVideo',
  props: {
    options: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  watch: {
    options: {
      handler: function (options, oldOptions) {
        this.dispose(() => {
          if (options && options.sources && options.sources.length) {
            this.initialize()
          }
        })
      },
      deep: true
    }
  },
  data() {
    return {
      player: null,
      defaultOption: {
        language: 'zh',
        playbackRates: [0.5, 1, 1.5, 2],
        autoplay: false,
        controls: true,
      },
      showVideo: true
    }
  },
  mounted() {
    this.initialize()
  },
  beforeDestroy() {
    if (this.player) {
      this.dispose();
    }
  },
  methods: {
    initialize () {
      const options = Object.assign(this.defaultOption, this.options)
      this.player = videojs(this.$refs.videoPlayer, options, () => {
        this.player.log('onPlayerReady', this);
      });
    },
    destory () {
      if (this.player) {
        this.player.dispose();
        this.player = null
      }
      this.showVideo = false;
    },
    dispose(callback) {
        if (this.player && this.player.dispose) {
          if (this.player.techName_ !== 'Flash') {
            this.player.pause && this.player.pause()
          }
          this.player.dispose()
          this.player = null
          this.$nextTick(() => {
            this.showVideo = false
            this.$nextTick(() => {
              this.showVideo = true
              this.$nextTick(() => {
                callback && callback()
              })
            })
          })
        }
      }
  }
}
</script>

<style>

</style>