<template>
  <div
    class="o-video"
    :class="{ offline: !online }"
  >
    <video
      v-if="online"
      ref="video"
      class="o-video__player o-simple-video"
      muted
      autoplay
      controls
      :poster="poster"
    />
    <slot />
  </div>
</template>

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

const CAMERA_URL = `${location.protocol === 'https:' ? 'wss' : 'ws'}://${process.env.VUE_APP_GATEWAY || location.host}${process.env.VUE_APP_CAMERA_PROXY}`

export default {
  name: 'CameraPlayer',
  props: {
    camera: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      poster: videoPoster
    }
  },
  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: {
    createPlayer () {
      this.destroyPlayer()
      if (flvjs.isSupported()) {
        const { identifier } = this.camera
        // 创建一个flvjs实例
        const player = flvjs.createPlayer({
          type: 'flv',
          isLive: true,
          hasAudio: false,
          url: `${CAMERA_URL}/${identifier}?authorization=${this.token}`
        })
        player.on('error', e => {
          console.log(e)
          this.$message({
            type: 'warning',
            message: e
          })
        })
        // 将实例挂载到video元素上面
        player.attachMediaElement(this.$refs.video)
        try {
          // 开始运行加载 只要流地址正常 就可以在h5页面中播放出画面了
          player.load()
          player.play()
        } catch (error) {
          console.log('连接websocker异常', error)
        }
        this.$player = player
      }
    },
    destroyPlayer () {
      if (this.$player) {
        this.$player.pause()
        this.$player.unload()
        this.$player.detachMediaElement()
        this.$player.destroy()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.o-video {
  position: relative;
  padding-top: 56.25%;
  border-radius: $radius--mini;
  overflow: hidden;

  &.offline {
    background: url("~@/assets/image_offline.svg") 0 0 / 100% 100% no-repeat;

    &::before {
      content: "当前设备离线了";
      position: absolute;
      top: 73%;
      left: 50%;
      color: $info;
      font-size: 12px;
      transform: translateX(-50%);
    }
  }

  &__player {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
}
</style>
