<style scoped>
</style>

<template>
  <div class="video-wrapper" :style="{
    width: width === 'auto' ? '100%' : width,
    height: height === 'auto' ? '100%' : height
  }">
    <video ref="videoPlayer" class="video-js" :controls="controls" :poster="poster" preload="auto" :style="{
      width: width === 'auto' ? '100%' : width,
      height: height === 'auto' ? '100%' : height
    }">
      <p>
        您的浏览器不支持这个视频。
      </p>
    </video>
  </div>
</template>

<script>
import util from '../common/util.js'

export default {
  data () {
    return {}
  },
  props: {
    // 视频源
    src: {
      type: String,
      required: true
    },
    // 视频海报
    poster: {
      type: String,
      default: ''
    },
    // 自动播放
    autoPlay: {
      type: Boolean,
      default: false
    },
    // 面板
    controls: {
      type: Boolean,
      default: true
    },
    // 宽
    width: {
      type: String,
      default: 'auto'
    },
    // 高
    height: {
      type: String,
      default: 'auto'
    }
  },
  computed: {},
  watch: {
    async src (val) {
      const videojs = await this.loadLibrary()

      let player = videojs(this.$refs['videoPlayer'])
      player.reset()

      player.src(val)

      player.on('canplay', () => {
        this.autoPlay && player.play()
      })

      player.on('error', () => {
        // console.log('error')
      })
    },
    poster(val) {
      if (window.videojs) {
        let player = window.videojs(this.$refs['videoPlayer'])
        player.poster(val)
      }
    }
  },
  methods: {
    init () {
      let videojs = window.videojs
      let self = this
      videojs(this.$refs['videoPlayer']).ready(function() {
        this.src(self.src)
        self.autoPlay && this.play()
      })
    },
    async loadLibrary () {
      if (typeof window.videojs === 'undefined') {
        try {
          await util.loadJS('./lib/video.js/video.min.js')
        } catch (e) {
          console.error('video.js is missing', e.toString())
          return null
        }
        try {
          await Promise.all([
            util.loadJS('./lib/video.js/ie8/videojs-ie8.min.js'),
            util.loadCSS('./lib/video.js/video-js.min.css')
          ])
        } catch (e) {
          console.error('video ie8 css file is missing', e.toString())
          return null
        }
      }

      return window.videojs
    }
  },
  async created () {
  },
  async mounted () {
    await this.loadLibrary()

    this.init()
  }
}
</script>
