<template>
  <video
      id="videoElement"
      ref="videoElement"
      controls
      muted
      width="100%"
      height="100%"
  ></video>
</template>

<script>
import { videoUrl } from '@/api/media/video'
const flvjs = require('flv.js')
export default {
  name: 'LivePlayer',
  data() {
    return {
      flvjs,
      videoId: ''
    }
  },
  mounted() {
    const userInfo = this.$store.state.user.userInfo
    if (userInfo != null) {
      this.userId = userInfo.userId.toString()
    } else {
      this.userId = 111222333
    }

    this.videoId = this.$route.params.id
    this.getVideoUrl(this.videoId)
  },
  methods: {
    // TODO 获取弹幕配置，将 videoUrl 作为本函数的回调
    danmakuConfig() {
    },
    getVideoUrl(videoId) {
      videoUrl(videoId)
        .then(res => {
          if (res.code === 0) {
            // TODO 返回一个 dplayer 播放器对象，包含一些常用的属性
            var coverUrl = res.data.coverUrl
            var videoUrl = res.data.videoUrl
            var urlType = res.data.urlType
            if (urlType === 'mp4') {
              this.initMp4Player(this.videoId, coverUrl, videoUrl)
            } else if (urlType === 'hls') {
              this.initHlsPlayer(this.videoId, coverUrl, videoUrl)
            } else if (urlType === 'dash') {
              this.initDashPlayer(this.videoId, coverUrl, videoUrl)
            } else if (urlType === 'flv') {
              this.initFlvPlayer(this.videoId, coverUrl, videoUrl)
            } else {
              console.log('无法识别 url 类型')
            }
          } else {
            console.error(res.msg)
          }
        })
        .catch(error => {
          console.error(error.message)
        })
    },
    initFlvPlayer(videoId, coverUrl, videoUrl) {
      var videoElement = document.getElementById('videoElement')
      const flvPlayer = flvjs.createPlayer({
        type: 'flv',
        isLive: true,
        url: videoUrl
      })
      flvPlayer.attachMediaElement(videoElement)
      flvPlayer.load()
      flvPlayer.play()
    }
  }
}
</script>

<style>
#dplayer {
  height: 500px;
}
</style>
