<template>
  <video
    id="videoElement"
    ref="videoElement"
    controls
    muted
    width="60%"
    height="30%"
  />
</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)*/
    const videoUrl = 'http://127.0.0.1:9090/live/01.flv'
    this.initFlvPlayer(videoUrl)
  },
  methods: {
    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 === 'flv') {
              this.initFlvPlayer(this.videoId, coverUrl, videoUrl)
            } else {
              console.log('无法识别 url 类型')
            }
          } else {
            console.error(res.msg)
          }
        })
        .catch(error => {
          console.error(error.message)
        })
    },
    initFlvPlayer(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>
