<template>
  <div class="video-content-wrapper">
    <div class="videoLoading" v-loading="!isVideoLoadingFailed" :element-loading-text="loadingText">
    </div>

    <div class="loadingError" v-if="isVideoLoadingFailed">视频加载失败</div>

    <video v-loading="true" id="video" autoplay muted loop class="video-js video-content">
      <source :src="props.url" />
    </video>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, onBeforeUnmount, watch, ref, computed } from 'vue';
  import mpegts from 'mpegts.js';

  const restartNum = ref(0);

  const MAX_RESTART_NUM = 20;
  let isVideoLoadingFailed = ref(false);

  const props = defineProps<{
    url: string;
  }>();

  let player: mpegts.Player | null;

  const loadingText = computed(() => {
    if (restartNum.value === 0) return '视频加载中...';
    return `正在尝试第${restartNum.value}次重连...`;
  });

  const initPlay = () => {
    const videoElement = document.getElementById('video') as HTMLMediaElement;
    player = mpegts.createPlayer(
      {
        type: 'flv',
        isLive: true,
        hasAudio: false,
        url: props.url,
      },
      {
        liveBufferLatencyChasing: true,
      },
    );
    player.attachMediaElement(videoElement);
    player.load();
    player.on(mpegts.Events.MEDIA_INFO, () => {
      // testStore.setVideoReady(true);
    });
    player.on(mpegts.Events.ERROR, (e) => {
      // testStore.setVideoReady(true);
      console.log('video error', e);
      if (restartNum.value >= MAX_RESTART_NUM) {
        isVideoLoadingFailed.value = true;
        return;
      }
      if (player) {
        player.pause();
        player.unload();
        player.detachMediaElement();
        player.destroy();
        player = null;
        restartNum.value += 1;
        initPlay();
      }
    });
    // player.play();
    setTimeout(() => {
      player?.play();
    }, 50);
  };

  const destroyPlayer = () => {
    // testStore.setVideoReady(false);
    if (player) {
      player.pause();
      player.unload();
      player.detachMediaElement();
      player.destroy();
      player = null;
    }
  };

  onMounted(() => {
    initPlay();
  });

  //切换播放url
  watch(
    () => props.url,
    () => {
      destroyPlayer();
      if (props.url) {
        initPlay();
      }
    },
    {
      deep: true,
    },
  );

  onBeforeUnmount(() => {
    destroyPlayer();
  });
</script>

<style scoped>
  .video-content {
    width: 100%;
    height: 100%;
    position: relative;
    z-index: 10;
    background-color: transparent !important;
  }

  .video-content-wrapper {
    height: 100%;
    position: relative;
  }
  .videoLoading {
    position: absolute;
    z-index: 1;
    width: 100%;
    height: 100%;
  }

  .loadingError {
    font-size: 20px;
    text-align: center;
    margin-top: 200px;
  }
</style>
