import flvjs from 'flv.js'
import { authCode } from '@/api/camera'
const CAMERA_URL = `${location.protocol}//${process.env.VUE_APP_GATEWAY || location.host}`
export default {
  data () {
    return {
      maskShow: false,
      refreshShow: false,
      first: false
    }
  },
  created () {
    this.$timer = -1
    this.getAuthCode()
  },
  methods: {
    getAuthCode () {
      authCode({ deviceId: this.device.id }).then(({ data }) => {
        this.createPlayer(data)
      })
    },
    createPlayer ({ timestamp, token, expire }) {
      if (flvjs.isSupported()) {
        // 创建一个flvjs实例
        const url = `${CAMERA_URL}/live/${this.device.id}.flv?authorization=${token}&timestamp=${timestamp}&expire=${expire}`
        this.$player = flvjs.createPlayer({
          type: 'flv',
          isLive: true,
          hasAudio: false,
          url
        })
        this.$player.on('error', () => {
          this.refreshShow = true
          this.destroyPlay()
          this.$message({
            type: 'warning',
            message: '设备视频流出错'
          })
        })
        let decodedFrames = -1
        this.$player.on('statistics_info', res => {
          decodedFrames = res.decodedFrames
        })
        this.$timer = setTimeout(() => {
          if (decodedFrames === 0) {
            this.destroyPlay()
            this.$message({
              type: 'warning',
              message: `${this.device.name}设备没有视频流`
            })
            this.refreshShow = true
          }
        }, 10000)
        // 将实例挂载到video元素上面
        this.$player.attachMediaElement(this.$refs.player)

        try {
          // 开始运行加载 只要流地址正常 就可以在h5页面中播放出画面了
          this.$player.load()
          this.$player.play()
        } catch (error) {
          console.log('连接websocker异常', error)
        }
      }
    },
    destroyPlay () {
      this.$player.pause()
      this.$player.unload()
      this.$player.detachMediaElement()
      this.$player.destroy()
      this.$player = null
    }
  },
  beforeDestroy () {
    if (this.$player) {
      clearTimeout(this.$timer)
      this.destroyPlay()
    }
  }
}
