<template>
  <div id="dplayer" ref="dplayer" />
</template>

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

    this.videoId = this.$route.params.id
    this.getVideoUrl(this.videoId)
  },
  methods: {
    // TODO 获取弹幕配置，将 videoUrl 作为本函数的回调
    danmakuConfig() {
    },
    /* videoUrl() {
      fetch(`/api/media/video/url/${this.videoId}`, {
        headers: {
          'Content-Type': 'application/json; charset=UTF-8',
          'X-XSRF-TOKEN': this.$cookies.get('XSRF-TOKEN')
        },
        method: 'GET',
        credentials: 'include'
      }).then(response => response.json())
        .then(json => {
          if (json.code === 0) {
            var coverUrl = json.data.coverUrl
            var videoUrl = json.data.videoUrl
            this.initDplayer(this.videoId, coverUrl, videoUrl)
          } else {
            // TODO 显示错误信息
            // this.$router.push('/')
          }
        })
        .catch(e => {
          return null
        })
    },*/
    getVideoUrl(videoId) {
      videoUrl(videoId)
        .then(res => {
          if (res.code === 0) {
            var coverUrl = res.data.coverUrl
            var videoUrl = res.data.videoUrl
            this.initDplayer(this.videoId, coverUrl, videoUrl)
          } else {
            this.$notify({
              title: res.code,
              message: res.msg,
              type: 'warning',
              duration: 500
            })
          }
        })
        .catch(error => {
          this.$message.error(error.message)
        })
    },
    initDplayer(videoId, coverUrl, videoUrl) {
      new DPlayer({
        container: document.querySelector('#dplayer'),
        lang: 'zh-cn',
        screenshot: true,
        video: {
          pic: coverUrl,
          url: videoUrl,
          type: 'auto'
        },
        logo: '/logo.png',
        danmaku: {
          id: videoId,
          maximum: 10000,
          api: '/api/media/danmaku/',
          token: 'hertube',
          user: this.userId,
          bottom: '15%',
          unlimited: true
        }
      })
    }
  }
}
</script>

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