<template>
  <div
    class="o-video"
    :class="{ offline: !online, mask: loading }"
  >
    <template v-if="online">
      <video
        ref="video"
        class="o-video__player o-simple-video"
        :poster="poster"
        autoplay
        muted
        @play="onPlay"
      />
      <div class="o-video__mask">
        <div class="l-flex--row center o-video__btn">
          <i class="el-icon-loading" />
        </div>
      </div>
    </template>
    <div
      v-else
      class="o-video__tag"
    />
    <slot />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import flvjs from 'flv.js'
import { GATEWAY_CAMERA } from '@/constant'
import videoPoster from '@/assets/video-poster.png'

export default {
  name: 'CameraPlayer',
  props: {
    camera: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      poster: videoPoster,
      loading: false
    }
  },
  computed: {
    ...mapGetters(['token']),
    online () {
      return this.camera.onlineStatus === 1
    }
  },
  watch: {
    online (val) {
      if (val) {
        this.$nextTick(this.createPlayer)
      } else {
        this.destroyPlayer()
      }
    }
  },
  mounted () {
    this.online && this.createPlayer()
  },
  beforeDestroy () {
    this.destroyPlayer()
  },
  methods: {
    onPlay () {
      if (this.loading) {
        this.loading = false
      }
    },
    createPlayer () {
      this.destroyPlayer()
      if (flvjs.isSupported()) {
        const { identifier } = this.camera
        const player = flvjs.createPlayer({
          type: 'flv',
          isLive: true,
          hasAudio: false,
          url: `${GATEWAY_CAMERA}/${identifier}?authorization=${this.token}`
        })
        player.on(flvjs.Events.ERROR, e => {
          console.log('flvjs', this.camera.name, flvjs.Events.ERROR, e)
          this.$message({
            type: 'warning',
            message: e
          })
        })
        try {
          this.loading = true
          this.$player = player
          player.attachMediaElement(this.$refs.video)
          player.load()
        } catch (error) {
          console.log('连接异常', error)
          this.destroyPlayer()
        }
      }
    },
    destroyPlayer () {
      this.loading = false
      if (this.$player) {
        const player = this.$player
        player.pause()
        player.unload()
        player.detachMediaElement()
        player.destroy()
        this.$player = null
      }
    }
  }
}
</script>
