<template>
  <div class="hls-media">
    <video
      ref="VideoMedia"
      muted
      controls
      controlslist="nodownload"
      disablePictureInPicture
    ></video>
  </div>
</template>

<script>
import Hls from "hls.js";

export default {
  name: "hls-media",
  props: {
    url: {
      type: String,
    },
  },
  data() {
    return {
      player: null,
      hls: null,
    };
  },
  watch: {
    url() {
      this.initVideo();
    },
  },
  mounted() {
    this.initVideo();
  },
  methods: {
    initVideo() {
      if (!this.url) return;
      if (!Hls.isSupported()) return;
      this.destroyPlayer();

      this.hls = new Hls();
      this.hls.loadSource(this.url);
      this.hls.attachMedia(this.$refs.VideoMedia);
      this.player = this.$refs.VideoMedia;
      this.player.play();

      this.player.onloadedmetadata = () => {
        console.log("loaded");
        this.$emit("loaded");
      };
      this.player.onended = () => {
        console.log("ended");
        this.$emit("ended");
      };

      this.hls.on(Hls.Events.ERROR, (event, data) => {
        if (!data.fatal) {
          switch (data.type) {
            case Hls.ErrorTypes.NETWORK_ERROR:
              console.log("网络问题，准备重试！");
              this.hls.startLoad();
              break;
            case Hls.ErrorTypes.MEDIA_ERROR:
              console.log("媒体问题，准备重试！");
              this.hls.recoverMediaError();
              break;
            default:
              console.log("未知问题，无法播放！");
              this.$emit("error");
              this.hls.destroy();
              break;
          }
        }
      });
    },
    playPlayer() {
      this.player.play();
    },
    pausePlayer() {
      this.player.pause();
    },
    destroyPlayer() {
      if (!this.hls) return;
      // this.player.pause();
      this.hls.destroy();
      this.player = null;
      this.hls = null;
    },
  },
  beforeDestroy() {
    this.destroyPlayer();
  },
};
</script>

<style lang="scss" scoped>
.hls-media {
  height: 100%;
  video {
    display: block;
    width: 100%;
    height: 100%;
  }
}
</style>
