<template>
  <div class="flv">
    <span class="errorMsg">{{ errorMsg }}</span>
    <video id="video" autoplay @timeupdate="progress($event)"></video>
  </div>
</template>

<script>
import flv from 'flv.js'
import { getQxToken } from '@/api/video/camera'
import { selectVideoLoginInfo } from '@/api/screen/screen'
export default {
  data() {
    return {
      errorMsg: '错误消息',
      flvPlayerList: [],
      replayCount: 0,
      playUrl: '',
      qxToken: null,
      qxInfo: null,
    }
  },
  // 监听设备信息
  watch: {
    playerInfo: {
      handler(newValue) {
        if (newValue) {
          // 1. 监听到数据后 调token 和 ip 的接口
          Promise.all([this.getQxToken(), this.selectVideoLoginInfo()]).then(() => {
            //  2. Promise.all 等待两个异步请求结束后 再组装url
            const { puid, ballIndex } = newValue

            this.playUrl =
              this.qxInfo.q2Url + 'stream.flv?puid=' + puid + '&idx=' + ballIndex + '&stream=0&token=' + this.qxToken
            console.log('this.playUrl', this.playUrl)
            this.playvideo()
          })
        } else {
          this.stopvideo()
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    async playvideo() {
      console.log('播放---', this.playUrl)
      const _this = this
      this.errorMsg = ''
      if (flv.isSupported()) {
        await this.stopvideo()
        let videoElement = document.getElementById('video')
        videoElement.contorls = true
        let flvPlayer = flv.createPlayer({
          type: 'flv',
          isLive: true,
          hasAudio: false,
          hasVideo: true,
          url: this.playUrl,
        })
        flvPlayer.attachMediaElement(videoElement)
        flvPlayer.load()
        setTimeout(function () {
          flvPlayer.play()
        }, 100)
        flvPlayer.on('error', function (error) {
          _this.errorMsg = error
          if (_this.replayCount > 0) {
            return
          }
          _this.replayCount++
          setTimeout(function () {
            console.log('flvjs replayCount', _this.replayCount)
            _this.playvideo()
          }, 100)
        })
        flvPlayer.on('scriptdata_arrived', function (e) {
          errorMsg.value = ''
          this.flvPlayerList.push(flvPlayer)
        })
      } else {
        ElMessage({
          message: '当前浏览器不支持flvjs播放',
          type: 'error',
          duration: 2000,
        })
      }
    },
    async stopvideo() {
      if (this.flvPlayerList.length) {
        this.flvPlayerList.forEach(item => {
          if (item) {
            item.unload()
            item.detachMediaElement()
            item.destroy()
          }
        })
        this.flvPlayerList = []
      }
    },
    progress(e) {
      let self = this
      var bf = e.srcElement.buffered
      var currentTime = e.srcElement.currentTime
      if (bf.length > 0) {
        let end = bf.end(0)
        if (end - currentTime > 10) {
          e.srcElement.currentTime = end - 0.1
        }
      }
    },
    async getQxToken() {
      const res = await getQxToken()

      console.log('res播放视频的token', res)
      this.qxToken = res.msg
    },
    async selectVideoLoginInfo() {
      const res = await selectVideoLoginInfo()
      this.qxInfo = res.data
    },
    childPlayVideo(e) {
      if (this.qxToken && this.qxInfo) {
        const { puid, ballIndex } = e
        this.playUrl =
          this.qxInfo.q2Url + 'stream.flv?puid=' + puid + '&idx=' + ballIndex + '&stream=0&token=' + this.qxToken
        this.playvideo()
      } else {
        Promise.all([this.getQxToken(), this.selectVideoLoginInfo()]).then(async () => {
          //  2. Promise.all 等待两个异步请求结束后 再组装url
          const { puid, ballIndex } = e
          this.playUrl =
            this.qxInfo.q2Url + 'stream.flv?puid=' + puid + '&idx=' + ballIndex + '&stream=0&token=' + this.qxToken
        })

        this.playvideo()
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.flv {
  height: 100%;
  & > #video {
    width: 100%;
    height: 100%;
    object-fit: fill;
    background-color: black;
  }
  .errorMsg {
    display: inline-block;
    font-size: 30px;
    color: rgb(146, 110, 110);
    font-weight: bold;
    position: absolute;
    top: 50%;
    left: 40%;
    z-index: 999;
  }
}
</style>
