<template>
  <div
    class="loopVideo"
    v-loading="videoLoading"
    element-loading-text="加载中..."
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <video
      :id="`historyVideoComponent${channel}`"
      @canplay="videoCanPlay"
      :autoplay="autoplay"
      muted
      controls
      loop
      class="videoControl"
      ref="loopVideoPlayer"
    >
      <source :src="videoUrl" type="video/mp4" />
      您的浏览器不支持 video 属性。
    </video>
  </div>
</template>

<script>
import { getEventVideo } from "@/dao/track";
export default {
  name: "loopVideo",
  props: {
    channel: String,
    timeModel: Object,
    autoplay: Boolean,
  },
  data() {
    return {
      videoLoading: true,
      videoUrl: null,
    };
  },
  mounted() {
    if (this.channel) {
      console.log(
        "loopVideo start and end",
        this.replaceTimeGap(this.timeModel.startTime),
        this.replaceTimeGap(this.timeModel.endTime)
      );
      this.getVideoStreamUrl();
    }
  },

  methods: {
    startPlay() {
      document.getElementById(`historyVideoComponent${this.channel}`).play();
    },
    videoCanPlay() {
      console.log("loop video canplay");
      this.videoLoading = false;
      this.$emit("videoReady", this.channel);
    },
    replaceTimeGap(time) {
      return time
        .toString()
        .replaceAll("-", "_")
        .replaceAll(" ", "_")
        .replaceAll(":", "_");
    },
    destroy() {},
    async getVideoStreamUrl() {
      if (this.timeModel.startTime && this.timeModel.endTime) {
        try {
          const response = await getEventVideo({
            channel: this.channel,
            subtype: 0,
            starttime: this.replaceTimeGap(this.timeModel.startTime),
            endtime: this.replaceTimeGap(this.timeModel.endTime),
          });
          console.log("response", response);
          this.videoUrl = response.content;
          setTimeout(() => {
            this.$refs.loopVideoPlayer.load();
          }, 200);
        } catch (error) {
          console.error(`Failed to get video stream url: ${error}`);
        }
      } else {
        console.log("no timerange...");
      }
    },
  },
  watch: {},
  beforeDestroy() {
    this.videoLoading = false;
  },
};
</script>

<style lang="less" scoped>
.loopVideo {
  height: 100%;
  width: 100%;

  .videoControl {
    height: 100%;
    width: 100%;
  }
}

.loading-mask {
  // position: absolute;
  width: 100%;
  height: 100%;
  background-color: rgba(8, 22, 35, 0.7);
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  color: #fcfcfc;
}

// ::v-deep .el-icon-loading {
//   position: absolute;
//   left: 30%;
//   top: -14px;
//   transform: translateX(-50%);
// }
</style>
