<template>
  <div class="player-box">
    <video ref="videoRef" :autoplay="autoPlay" :controls="controls" :muted="muted" />
    <div v-show="isLoading" class="loader" />
  </div>
</template>

<script lang="ts" setup name="FlvVideo">
import flvjs from 'flv.js';

const props = defineProps({
  videoUrl: {
    require: true,
    default: () => ''
  },
  autoPlay: {
    type: Boolean,
    default: false
  },
  muted: {
    type: Boolean,
    default: true
  },
  controls: {
    type: Boolean,
    default: false
  }
});
const emits = defineEmits(['onPlaying', 'onPlayError']);
const videoRef = ref();
let flvPlayer = ref();
let isLoading = ref(false);
// 播放视频
const handleVideoPlay = () => {
  if (flvjs.isSupported()) {
    isLoading.value = true;
    if (flvPlayer.value) {
      flvPlayer.value.pause();
      flvPlayer.value.unload();
      flvPlayer.value.detachMediaElement();
      flvPlayer.value.destroy();
    }
    flvPlayer.value = flvjs.createPlayer(
      {
        type: 'flv',
        url: props.videoUrl
      },
      {
        cors: true, //是否跨域
        enableWorker: true, //是否多线程工作
        anableStashBuffer: false, //是否启用缓存
        autoCleanupSourceBuffer: true //是否自动缓存
      }
    );
    flvPlayer.value.attachMediaElement(videoRef.value);
    flvPlayer.value.load();
    flvPlayer.value.play();
    videoRef.value.addEventListener('playing', () => {
      isLoading.value = false; // 视频开始播放时关闭加载状态
      emits('onPlaying');
    });
    //报错重连
    flvPlayer.value.on(flvjs.Events.ERROR, (errType, errDetail) => {
      if (flvPlayer.value) {
        destoryVideo();
      }
      isLoading.value = false;
      emits('onPlayError');
    });
  }
};

const destoryVideo = () => {
  if (flvPlayer.value) {
    flvPlayer.value.pause();
    flvPlayer.value.unload();
    flvPlayer.value.detachMediaElement();
    flvPlayer.value.destroy();
    flvPlayer.value = null;
  }
};

onMounted(() => {
  if (props.autoPlay) {
    handleVideoPlay();
  }
});
defineExpose({
  handleVideoPlay,
  destoryVideo
});
</script>

<style lang="scss" scoped>
.player-box {
  position: relative;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  background-color: #000;
  video {
    width: 100%;
    height: 100%;
  }
  .playWnd {
    z-index: 10;
    width: 100%;
    height: 100%;
  }
  .video-enlarge {
    width: 34px;
    height: 34px;
    position: absolute;
    top: 20px;
    right: 20px;
    z-index: 10;
  }

  .loader {
    position: absolute;
    z-index: 10;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 32px;
    height: 32px;
    background: url('@/assets/images/video/ajax-loader.gif');
  }
}
</style>
