<!--
 * @Author: zhangtq 2452618307@qq.com
 * @Date: 2024-11-15 14:26:52
 * @LastEditors: zhangtq 2452618307@qq.com
 * @LastEditTime: 2024-11-19 09:32:40
 * @FilePath: src/views/screen/components/video/components/Player.vue
 * @Description: 这是默认设置,可以在设置》工具》File Description中进行配置
 -->
<template>
  <div :class="{ player: true, selected: isSelected }" @click="handlePlayerClick" @dblclick="dblclick">
    <!-- {{ title }}号窗口 -->
    <video class="cell-player-1" ref="videosmallone" preload="auto" muted type="rtmp/flv" :id="id">
      <source src="" />
    </video>
  </div>
</template>

<script>
import flvjs from 'flv.js'
import { getQxToken } from '@/api/video/camera'
import { selectVideoLoginInfo } from '@/api/screen/screen'

export default {
  props: {
    isHistory: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String,
      default: '',
    },
    title: {
      type: Number,
      default: 1,
    },
    activePlayer: {
      type: Number,
      default: null,
    },
  },
  data() {
    return {
      player: null,
      loading: false,
      videoUrl: '',
      videoToken: '',
      qxToken: '',
      qxInfo: {},
    }
  },
  beforeUnmount() {
    if (this.player) {
      this.player.pause()
      this.player.unload()
      this.player.detachMediaElement()
      this.player.destroy()
      this.player = null
    }
  },
  computed: {
    // Use a computed property to determine if the player is active
    isSelected() {
      return this.activePlayer === this.title
    },
    playerClass() {
      return ['player', `cell-player-1`, { active: this.title === this.activePlayer }]
    },
  },
  created() {
    this.getQxToken()
  },
  methods: {
    getQxToken() {
      getQxToken().then(res => {
        this.qxToken = res.msg
      })
    },
    selectVideoLoginInfo() {
      selectVideoLoginInfo().then(res => {
        this.qxInfo = res.data
        console.log('selectVideoLoginInfo', res)
      })
    },
    handlePlayerClick() {
      // 在点击事件中调用父组件的方法，传递数据
      this.$emit('playerClick', { title: this.title, token: this.qxToken })
    },
    dblclick() {
      this.$emit('dblclick', this.title)
    },
    openVideo(puid, ballIndex) {
      console.log('播放视频--------', puid, ballIndex)
      this.init(puid, ballIndex)
    },
    init(puid, ballIndex) {
      this.getQxToken()
      this.selectVideoLoginInfo()
      setTimeout(() => {
        //使用定时器是因为，在mounted声明周期里调用，可能会出现DOM没加载出来的原因
        var videoElement = this.$refs.videosmallone // 获取到html中的video标签
        if (videoElement && flvjs.isSupported()) {
          //因为我这个是复用组件，进来先判断 player是否存在，如果存在，销毁掉它，不然会占用TCP名额
          if (this.player !== null) {
            this.player.pause()
            this.player.unload()
            this.player.detachMediaElement()
            this.player.destroy()
            this.player = null
          }
          this.player = flvjs.createPlayer(
            //创建直播流，加载到DOM中去
            {
              type: 'flv',
              url:
                this.qxInfo.q2Url + 'stream.flv?puid=' + puid + '&idx=' + ballIndex + '&stream=0&token=' + this.qxToken, //你的url地址
              isLive: true, //数据源是否为直播流
              hasAudio: false, //数据源是否包含有音频
              hasVideo: true, //数据源是否包含有视频
              enableStashBuffer: true, //是否启用缓存区
            },
            {
              enableWorker: false, //不启用分离线程
              enableStashBuffer: false, //关闭IO隐藏缓冲区
              autoCleanupSourceBuffer: true, //自动清除缓存
              lazyLoad: false,
            }
          )
          this.player.attachMediaElement(videoElement) //放到dom中去
          this.player.load() //准备完成
          //!!!!!!这里需要注意，有的时候load加载完成不一定可以播放，要是播放不成功，用settimeout 给下面的this.player.play() 延时几百毫秒再播放
          setTimeout(() => {
            this.player.play()
          }, 500) // Delay to ensure the player is ready
        }
      }, 1000)
    },
    timeStrToTimestamp(str) {
      let date = new Date(str)
      return date.getTime()
    },
    openHistoryVideo(item) {
      console.log('=====================')
      console.log('item', item)
      this.getQxToken()
      this.selectVideoLoginInfo()
      let time = item.currentTime || 0
      this.$refs.videosmallone.item = item
      let durationSecond = this.timeStrToTimestamp(parseInt(item.end)) - this.timeStrToTimestamp(parseInt(item.begin))
      let url =
        this.qxInfo.q2Url +
        'SG/VODFile.flv?path=' +
        '' +
        item.path +
        item.name +
        '' +
        '&idx=0&puid=' +
        item.puid +
        '&durationSecond=' +
        durationSecond +
        '&startTime=' +
        time +
        '&stream=0&token=' +
        this.qxToken
      if (flvjs.isSupported()) {
        var videoElement = this.$refs.videosmallone // 获取到html中的video标签
        if (videoElement) {
          this.player = flvjs.createPlayer(
            {
              type: 'flv', // => 媒体类型 flv 或 mp4，m3u8
              isLive: true, // => 是否为直播流
              hasAudio: false, // => 是否开启声音
              url: url, // => 视频流地址
              stashInitialSize: 128, // 减少首桢显示等待时长
            },
            {
              enableWorker: false, //不启用分离线程
              enableStashBuffer: false, //关闭IO隐藏缓冲区
              reuseRedirectedURL: true, //重用301/302重定向url，用于随后的请求，如查找、重新连接等。
              autoCleanupSourceBuffer: true, //自动清除缓存
              fixAudioTimestampGap: false, //false才会音视频同步
            }
          )
          this.player.attachMediaElement(videoElement)
          this.player.load()
          setTimeout(() => {
            this.player.play()
            this.$emit('startVideo', time)
          }, 500)
        }
      } else {
        console.log('flvjs.isSupported() false')
      }
    },
    closeVideo() {
      try {
        this.player.pause()
        this.player.unload()
        this.player.detachMediaElement()
        this.player.destroy()
        this.player = null
      } catch (e) {
        console.log('closeVideo', e)
        this.player = null
      }
      this.$emit('clearTime', this.title)
    },
  },
}
</script>

<style scoped lang="scss">
.player {
  background-color: black;
  height: 100%;
  border: 1px solid grey;
  color: white;
  text-align: center;
}

.selected {
  background-color: black;
  height: 100%;
  border: 2px solid green;
  color: white;
  text-align: center;
}

.cell-player-1 {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.jessibuca {
  height: 100%;
  & > #container {
    width: 100%;
    height: 20%;
    object-fit: fill;
    background-color: black;
    margin-top: 30px;
  }
}
</style>
