<template>
  <video :controls="controls" ref="videoPlayer" class="video-js"></video>
</template>
<script>
import flvjs from "flv.js";
export default {
  name: "VideoPlayer",
  props: {
    controls: {
      type: Boolean,
      default: true,
    },
    src: {
      type: String,
      default: "",
    },
    // https://github.com/bilibili/flv.js/blob/master/docs/api.md
    mediaDataSource: {
      type: Object,
      default: undefined,
    },
    config: {
      type: Object,
      default: undefined,
    },
  },
  data() {
    return {
      $player: null,
    };
  },
  mounted() {
    if (flvjs.isSupported()) {
      try {
        const flvPlayer = flvjs.createPlayer(
          {
            type: "mp4",
            url: this.src,
            ...(this.mediaDataSource || {}),
          },
          this.config
        );
        flvPlayer.attachMediaElement(this.$refs.videoPlayer);
        flvPlayer.load();
        flvPlayer.play();
        this.$player = flvPlayer;
      } catch (err) {
        console.log(err);
      }
    } else {
      this.$message.error("抱歉，您的浏览器不支持flv.js。");
    }
  },
  beforeDestroy() {
    if (this.$player) {
      this.$player.destroy();
    }
  },
};
</script>
