<template>
  <!--   id：用于获取video对象
   class：video-js vjs-default-skin为video内置的样式名称，样式可根据具体项目进行调整
   autoplay：自动播放
   muted：设置静音。在最新版的Chrome浏览器（以及所有以Chromium为内核的浏览器）中，已不再允许自动播放音频和视频，设置静音是一种hack手段，参考：https://www.mzwu.com/article.asp?id=4411
   preload：提前加载 -->
  <video
    :id="videoIds"
    class="video-js vjs-default-skin video_item"
    autoplay
    muted
    preload="auto"
  >
   <source :src="props.src" style="width: 100%; height: 100%" />
  </video>
</template>

<script setup>
// 引入videojs以及样式文件
import videojs from "video.js/dist/video.min";
import "video.js/dist/video-js.min.css";
import emitter from "@/utils/eventBus.js";
import {
  defineProps,
  onMounted,
  onBeforeUnmount,
  ref,
  watch,
  nextTick,
} from "vue";
const myPlayer = ref(null); //视频对象
const videoIds = ref(0); //视频对象ID
// 在onMounted阶段进行初始化
onMounted(() => {
  //设置视频对象ID
  let videoCount = window.localStorage.getItem("videoCount");
  if (videoCount) {
    videoCount++;
    window.localStorage.setItem("videoCount", videoCount);
    videoIds.value = `video_${videoCount}`;
  } else {
    window.localStorage.setItem("videoCount", 1);
    videoIds.value = `video_${window.localStorage.getItem("videoCount")}`;
  }
  nextTick(() => {
    initVideoSourc();
  });

});

onBeforeUnmount(() => {
  //销毁视频对象
  myPlayer.value.dispose();
});

//参数
const props = defineProps({
  //视频地址
  src: String
});
// 监听视频地址变化
watch(
  () => props.src,
  (n) => {
    changeVideoSource(n);
  }
);
//初始化视频
function initVideoSourc() {
  myPlayer.value = videojs(
    videoIds.value,
    {
      bigPlayButton: false, //播放悬浮大按钮
      textTrackDisplay: false, //文本轨道
      posterImage: false, //封面
      errorDisplay: false,
      controls: true //显示控件
      // ...其他配置参数
    },
    function () {
      this.play();
    }
  );
}
// 视频地址发生变化时的处理
function changeVideoSource(src) {
  if (!src) return;
  myPlayer.value.src([
    {
      src: src,
      type: "application/x-mpegURL"
    }
  ]);
  myPlayer.value.play();
}
</script>
<style lang="scss" scoped>
.video_item {
  width: 100%;
  height: 100%;
}
</style>