
<template>
  <video ref="jswebrtc" style="width: 100%;height: 100%;object-fit: fill;" playsinline @click="(e) => handler().click(e)"/>
</template>

<script>
import JSWebrtc from '@/utils/jswebrtc.min.js'
import { mapState, mapMutations } from 'vuex'
export default {
  name: "WebRTCPlayer",
  props: {
    videoSrc: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      player: null
    }
  },
  computed: {
    ...mapState([
      'zoom',
    ]),
    ...mapState('audio', [
      'videoPlay',
    ]),
    ...mapState('audio', [
      'volumeMachine'
    ]),
  },
  watch: {
    volumeMachine(value) {
      this.$refs.jswebrtc.volume = this.volumeMachine / 100
    },
    videoPlay() {
      // this.$refs.jswebrtc.play()
      this.$refs.jswebrtc.muted = false
    },
  },
  mounted() {
    this.$watch('videoSrc', () => {
      if (this.videoSrc) {
        this.initVideo(this.videoSrc)
      }
    }, {
      immediate: true
    })
  },
  beforeDestroy() {
    // 播放器存在清除播放器
    if (this.player) {
      this.player.destroy()
    }
  },
  methods: {
    ...mapMutations('audio', [
      'SetVideoPlay',
    ]),
    /**
     * 初始化播放器并播放
     * 两种调用方式
     *  一种通过 watch监听 props 传过来的 src 进行播放
     *  一种通过 引用组件上的 ref 直接调用 initVideo 如 this.$refs.webrtc.initVideo('src')
     * */
    initVideo(url) {
      // 播放器存在 清空重置
      if (this.player) {
        this.player.destroy()
        this.player = null
      }

      // 获取承载元素dom
      this.$refs.jswebrtc.volume = this.volumeMachine / 100
      const videoDom = this.$refs.jswebrtc

      // 初始化播放器
      this.player = new JSWebrtc.Player(url, {
        video: videoDom,
        autoplay: true,
        onPlay: (obj) => {
          // 监听video元素状态，可播放时进行播放 。 某些情况下  autoplay 会失效
          // mdn https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLMediaElement/canplay_event
          // 菜鸟 https://www.runoob.com/tags/av-event-canplay.html
          videoDom.addEventListener('canplay', function(e) {
            videoDom.play()
          })
          console.log(obj, '播放器开始播放！')
        }
      })
    },
    handler() {
      return {
        click: (e) => {
          this.SetVideoPlay()
          const { zoom } = this
          const video = this.$refs.jswebrtc
          const { offsetWidth, offsetHeight } = video // 组件宽高
          const { offsetX, offsetY } = e // 点击位置
          const clickPercenY = (offsetHeight * zoom - offsetY) / (offsetHeight * zoom)
          const clickPercenX = (offsetX) / (offsetWidth * zoom)

          // 计算点击区域对应的十六进制
          const max = 32639
          const y16 = (+(max * clickPercenY).toFixed(0)).toString(16)
          const x16 = (+(max * clickPercenX).toFixed(0)).toString(16)
          this.$emit('click', {x16, y16})
        },
      }
    },
  },
}
</script>
