<template>
    <div class="video-box">
      <div class="right-control" v-show="showControl">
        <i class="screenshot" title="截图" @click="screenShotsFn" v-show="screenshot"></i>
        <i
          class="change"
          title="切换视频"
          v-show="showOtherVideo"
          @click="changeVideoFn"
        ></i>
        <i class="close" title="关闭视频" @click="closeVideo"></i>
      </div>
      <video
        poster="./imgs/TSL_logo.png"
        :id="videoId"
        :muted="muted"
        :src="currentSrc"
        :controls="showControl"
        loop
        autoplay="autoplay"
        class="video-element"
        ref="ref_video"
      ></video>
    </div>
</template>

<script>
import flvjs from "flv.js";
import guid from "../../public_js/guid";
export default {
  name: "TslVideoPlayer",
  componentName: "TslVideoPlayer",
  props: {
    // 是否在视频调阅平台使用
    isControlItem: {
      type: Boolean,
      default: false,
    },
    // 主地址
    mainSrc: {
      type: String,
      default: "",
    },
    // 其它视频播放连接，有切换视频功能时需要传入该字段
    otherSrc: {
      type: String,
      default: "",
    },
    // 是否显示控制信息
    showControl: {
      type: Boolean,
      default: true,
    },
    // 是否显示截图
    screenshot: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      showOtherVideo: false, // 是否显示上传的其它视频
      videoId: "videoElement_" + guid(),
      muted: true, // 是否静音
      currentSrc: "",
      videoType: "", // 视频类型
      flvPlayer: null,
      videoElement: null,
      currentVideoStatu: "play", // 当时视频播放状态
      isMainSrc: true, // 当前播放的是否主视频
    };
  },
  watch: {
    mainSrc: {
      handler(val) {
        this.initVideoUrl(val);
      },
      deep: true,
      immediate: false,
    },
    otherSrc: {
      handler(val) {
        if (val.length) {
          this.showOtherVideo = true;
        }
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    this.videoElement = this.$refs.ref_video;
    this.initVideoUrl(this.mainSrc);
  },
  methods: {
    initVideoUrl(srcUrl) {
      if (srcUrl == null || srcUrl == "") {
        return;
      }

      this.currentSrc = srcUrl;
      this.init();
    },
    /**
     * ==============
     *   初始化视频
     * ==============
     *
     * 1. 用正则判断是否正确的视频格式
     * 2. 用正则判断是否Flv格式的视频
     * 3. 用switch做不同视频格式的处理
     *
     * 注：flv格式视频需保留setTimeout
     */
    init() {
      const regIsVideo = /\.(webm|ogg|flv|mp4)$/i;
      if (regIsVideo.test(this.currentSrc)) {
        this.videoType = /\.(flv)$/i.test(this.currentSrc) ? "flv" : "mp4";
        this.currentVideoStatu = "play";
        switch (this.videoType) {
          case "flv":
            setTimeout(() => {
              this.initVideoFlv();
            }, 100);
            break;
          case "mp4":
            break;

          default:
            break;
        }
      } else {
        console.log("请确保您提交的格式是正确的视频格式！");
      }
    },
    // 初始化Flv视频的方法
    async initVideoFlv() {
      this.muted = true;
      if (flvjs.isSupported() && this.currentSrc) {
        this.flvPlayer = null;
        this.flvPlayer = flvjs.createPlayer({
          type: "flv",
          isLive: false,
          url: this.currentSrc,
          hasAudio: false,
        });
        this.openFlvFN();
        this.flvPlayer.on("error", (err) => {
          return;
        });
      }
    },
    // 打开Flv视频的方法
    openFlvFN() {
      this.$nextTick(() => {
        this.flvPlayer.attachMediaElement(this.videoElement);
        this.flvPlayer.load();
        this.flvPlayer.play();
      });
    },
    // 关闭Flv视频的方法
    closeFlvFN() {
      if (this.flvPlayer) {
        this.flvPlayer.unload();
        this.flvPlayer.pause();
        this.flvPlayer.detachMediaElement();
        this.flvPlayer.destroy();
        this.currentVideoStatu = "pause";
      }
    },
    // 关闭视频
    closeVideo(type) {
      if (type !== "auto") {
        return this.$emit("closeItemVideo");
      } else {
        switch (this.videoType) {
          case "flv":
            if (this.currentVideoStatu === "play") {
              this.closeFlvFN();
            }
            break;
          case "mp4":
            if (this.currentVideoStatu === "play") {
              this.currentSrc = "";
              this.currentVideoStatu = "pause";
            }
            break;

          default:
            break;
        }
      }
    },
    /**
     * 更换视频
     * 1. 先关闭正在播放的视频
     * 2. 再更换视频
     */
    changeVideoFn() {
      this.closeVideo("auto");
      this.isMainSrc = !this.isMainSrc;
      this.currentSrc = !this.isMainSrc ? this.otherSrc : this.mainSrc;
      this.init();
    },
    // 生成截图
    screenShotsFn() {
      const video = this.$refs.ref_video;
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      ctx.drawImage(video, 0, 0);

      // download picture
      const a = document.createElement("a");
      a.href = canvas.toDataURL("image/png");
      a.download = `${Date.now()}`;
      a.click();
    },
  },
  beforeDestroy() {
    this.closeFlvFN();
  },
};
</script>

<style lang="scss" scoped>
.video-box {
  width: 99.9%;
  height: 100%;
  background-color: #333;
  position: relative;
  color: #fff;
  list-style: none;
  .right-control {
    position: absolute;
    right: 0;
    top: 0;
    width: 100%;
    height: 40px;
    z-index: 2;
    display: flex;
    justify-content: flex-end;
    background: linear-gradient(to bottom, #000, transparent);
    i {
      display: inline-block;
      width: 20px;
      height: 20px;
      margin: 20px 20px 0 0;
      transition: all 0.5s;
      cursor: pointer;
      &:hover {
        width: 25px;
        height: 25px;
        margin: 17px 17px 0 0;
      }
      &.screenshot {
        background: url("./imgs/icon-screenshot.png") no-repeat;
        background-size: 100% 100%;
      }
      &.close {
        background: url("./imgs/icon-close.png") no-repeat;
        background-size: 100% 100%;
      }
      &.change {
        background: url("./imgs/icon-change.png") no-repeat;
        background-size: 100% 100%;
      }
    }
  }
}
.video-element {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}
</style>
