<template>
  <div id="dplayer" ref="dplayer" style="height: 480px;" />
</template>

<script>
import { videoUrl } from '@/api/video'
import SocketInstance from '@/utils/ws/socket-instance'

import flvjs from 'flv.js'
import DPlayer from 'dplayer'
import { getAccessToken } from '@/utils/auth'

export default {
  name: 'VideoPlayer',
  props: {
    videoProp: {
      type: Object,
      default: () => null
    }
  },
  data() {
    return {
      flvjs,
      DPlayer,
      danmaku: {
        api: '//api.reghao.cn/api/comment/danmaku/',
        token: 'bili'
      },
      getUrl: true
    }
  },
  created() {
  },
  mounted() {
    const videoId = this.videoProp.videoId
    if (this.getUrl) {
      this.getVideoUrl(videoId)
    }
  },
  methods: {
    getVideoUrl(videoId) {
      videoUrl(videoId).then(res => {
        if (res.code === 0) {
          var event = false
          const token = getAccessToken()
          if (token != null) {
            SocketInstance.connect()
            event = true
          }

          const urlType = res.data.type
          if (urlType === 'mp4') {
            const urls = res.data.urls
            for (const url of urls) {
              url.type = 'normal'
            }
            this.initMp4Player(this.videoProp.userId, videoId, this.videoProp.coverUrl, urls, res.data.currentTime, event)
          } else if (urlType === 'flv') {
            const urls = res.data.urls
            this.initFlvPlayer(this.videoProp.userId, videoId, this.videoProp.coverUrl, urls, res.data.currentTime, event)
          } else {
            this.$notify.error({
              message: '视频 url 类型不合法',
              type: 'warning',
              duration: 3000
            })
          }
        } else {
          this.$notify.error({
            message: '视频 url 获取失败',
            type: 'warning',
            duration: 3000
          })
        }
      }).catch(error => {
        this.$notify.error({
          message: error.message,
          type: 'error',
          duration: 3000
        })
      })
    },
    danmakuConfig() {
      // TODO 获取弹幕配置，将 videoUrl 作为本函数的回调
    },
    initMp4Player(userId, videoId, coverUrl, urls, pos, event) {
      const player = new DPlayer({
        container: document.querySelector('#dplayer'),
        lang: 'zh-cn',
        logo: '/logo.png',
        screenshot: true,
        autoplay: true,
        volume: 0.1,
        mutex: true,
        video: {
          pic: coverUrl,
          defaultQuality: 0,
          quality: urls,
          hotkey: true
        },
        danmaku: {
          id: videoId,
          maximum: 10000,
          api: this.danmaku.api,
          token: this.danmaku.token,
          user: userId,
          bottom: '15%',
          unlimited: true
        }
      })

      // 设置音量
      // player.volume(0.1, true, false)
      // 跳转到上次看到的位置
      player.seek(pos)

      /* 事件绑定 */
      player.on('progress', function() {
        if (event) {
          const payload = {}
          payload.videoId = videoId
          payload.currentTime = player.video.currentTime
          payload.ended = false

          const jsonData = {}
          jsonData.event = 'progress'
          jsonData.payload = JSON.stringify(payload)
          SocketInstance.send(jsonData)
        }
      })

      player.on('ended', () => {
        if (event) {
          const payload = {}
          payload.videoId = videoId
          payload.currentTime = player.video.currentTime
          payload.ended = true

          const jsonData = {}
          jsonData.event = 'progress'
          jsonData.payload = JSON.stringify(payload)
          SocketInstance.send(jsonData)
        }
      })

      player.on('volumechange', () => {
        console.log('声音改变')
      })
    },
    initFlvPlayer(userId, videoId, coverUrl, urls, pos, event) {
      const player = new DPlayer({
        container: document.getElementById('dplayer'),
        lang: 'zh-cn',
        logo: '/logo.png',
        screenshot: true,
        autoplay: true,
        volume: 0.1,
        mutex: true,
        video: {
          pic: coverUrl,
          defaultQuality: 0,
          quality: urls,
          hotkey: true,
          type: 'customFlv',
          customType: {
            customFlv: function(video, player) {
              const flvPlayer = flvjs.createPlayer({
                type: 'flv',
                url: video.src
              })
              flvPlayer.attachMediaElement(video)
              flvPlayer.load()
            }
          }
        }
      })

      // 跳转到上次看到的位置
      player.seek(pos)

      /* 事件绑定 */
      player.on('progress', function() {
        if (event) {
          const payload = {}
          payload.videoId = videoId
          payload.currentTime = player.video.currentTime
          payload.ended = false

          const jsonData = {}
          jsonData.event = 'progress'
          jsonData.payload = JSON.stringify(payload)
          SocketInstance.send(jsonData)
        }
      })

      player.on('ended', () => {
        if (event) {
          const payload = {}
          payload.videoId = videoId
          payload.currentTime = player.video.currentTime
          payload.ended = true

          const jsonData = {}
          jsonData.event = 'progress'
          jsonData.payload = JSON.stringify(payload)
          SocketInstance.send(jsonData)
        }
      })

      player.on('volumechange', () => {
        console.log('声音改变')
      })
    }
  }
}
</script>

<style>
</style>
