<template>
  <!-- 图片视频轮播 -->
  <div
    class="sideshow"
    v-show="ifShow"
  >
    <div
      v-for="(item,index) in contentData"
      :key="index"
      class="ad_border"
      :style="item.borderStyle"
    >
      <img
        class="ad_item"
        v-if="item.type=='img'"
        :src="item.path"
        :style="item.contentStyle"
      />
      <video
        class="ad_item"
        v-else
        :src="item.path"
        :style="item.contentStyle"
        preload
        muted
        @ended="videoEnd"
      />
    </div>
  </div>
</template>
<script>
export default {
  name: "sideshow",
  watch: {
    contentList(data) {
      this.contentData = this.dataFormat(data);
    },
    ifShow(newValue) {
      if (newValue) {
        if (this.slideshowTime) {
          cancelAnimationFrame(this.slideshowTime);
          this.slideshowTime = null;
        }
        this.slideshowTime = requestAnimationFrame(this.circulation);
      } else {
        if (this.slideshowTime) {
          cancelAnimationFrame(this.slideshowTime);
          this.slideshowTime = null;
        }
        if (this.slideOutTime) {
          clearTimeout(this.slideOutTime);
          this.slideOutTime = null;
        }
      }
    }
  },
  props: {
    //播放内容
    contentList: {
      type: Array,
      default: []
    },
    // 停留时间秒
    sleepTime: {
      type: Number,
      default: 3
    },
    ifShow: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // cancelAnimationFrame 的返回值
      slideshowTime: null,
      // setTimeout 的返回值
      slideOutTime: null,
      //   轮播播放数据
      contentData: [],
      //   移动计数(mobileNum==mobileTime 表示一次移动完成)
      mobileNum: 0,
      //移动多少次完成图片移动
      mobileTime: 30,
      //   当前展示的资源下标
      showIndex: 0,
      //   每次移动距离
      distance: 0
      // 占用
      // placeHolder: true,
    };
  },
  methods: {
    // 计算外部菱形长度，和偏移量
    calculate() {
      let x = window.innerWidth;
      let y = window.innerHeight;

      let sideLength = Math.sqrt(x * x + y * y);
      // 宽度偏移量
      let px = (sideLength - x) / 2;
      // 高度偏移量
      let ph = (sideLength - y) / 2;
      // 每次移动距离
      this.distance = (sideLength + px * 2) / this.mobileTime;
      return {
        sideLength,
        px,
        ph
      };
    },
    styleFormat(data, num) {
      let prleft = num * this.distance - data.px;
      let chLeft = data.px - num * this.distance * 0.705;
      let chTop = data.ph + num * this.distance * 0.705;
      let borderStyle = `width:${data.sideLength}px;height:${
          data.sideLength
        }px;left:${prleft}px;top:${-data.ph}px;z-index: ${data.Zindex}`,
        contentStyle = `left:${chLeft}px;top:${chTop}px`;
      return {
        borderStyle,
        contentStyle
      };
    },
    /**
     * 轮播数据格式处理
     */
    dataFormat(data) {
      let result = [];
      let $this = this;
      let calculate = this.calculate();
      if (data.length > 0) {
        data.forEach((item, index) => {
          let styleData = this.styleFormat(
            {
              Zindex: data.length - index,
              ...calculate
            },
            0
          );
          let ob = { ...calculate, ...styleData, Zindex: data.length - index };
          ob.path = item.url ? item.url : item;
          let fileName = ob.path.split("/");
          fileName = fileName[fileName.length - 1];
          let imgRegex = /.(jpg|jpeg|png|gif)/i;
          let videoRegex = /.mp4/i;
          if (imgRegex.test(fileName)) {
            ob.type = "img";
            ob.sleepTime = $this.sleepTime;
            result.push(ob);
          } else if (videoRegex.test(fileName)) {
            ob.type = "video";
            ob.sleepTime = 10;
            result.push(ob);
          } else {
            if (ktLog && ktLog.e) {
              ktLog.e(`${JSON.stringify(item)} 广告文件`);
            }
          }
        });
        if (
          result.length < 2 &&
          result.length > 0 &&
          result[0].type !== "video" &&
          !result[0].path.includes("gif")
        ) {
          result.push(...result);
        }
      }
      if (ktLog&&ktLog.i) {
        ktLog.i(`播放广告数据：${JSON.stringify(result)}`);
      }
   
      return result;
    },
    /**
     * 循环播放
     */
    circulation() {
      if (!this.ifShow) {
        // 隐藏时不处理
        return;
      }
      if (this.contentData.length < 1) {
        //   没有图片就不轮播
        return;
      }
      if (
        this.contentData.length === 1 &&
        this.contentData[0].type === "video"
      ) {
        // 只有一个视频的时候不进行轮播直接重复播放
        this.videoStatus(1);
        return;
      }
      if (
        this.contentData.length === 1 &&
        this.contentData[0].path.includes("gif")
      ) {
        // 只有一个gif的时候不进行轮播直接重复播放
        return;
      }
      //   移动完成
      if (this.mobileNum > this.mobileTime) {
        if (this.contentData[this.showIndex].type == "video") {
          this.videoStatus(0);
        }
        if (this.showIndex >= this.contentData.length - 1) {
          this.showIndex = 0;
        } else {
          this.showIndex++;
        }
        this.contentData.forEach((item, index) => {
          if (index < this.showIndex) {
            item["Zindex"] = this.showIndex - index;
          } else {
            item["Zindex"] = this.contentData.length - (index - this.showIndex);
          }
        });
        this.contentData.forEach((_, index) => {
          this.mobileFunc(index, 0);
        });
        if (this.contentData[this.showIndex].type == "video") {
          //当前展示为视频资源时播放视频
          this.videoStatus(1);
        } else {
          this.slideOutTime = setTimeout(() => {
            this.mobileNum = 0;
            this.animationtimer = requestAnimationFrame(this.circulation);
          }, this.contentData[this.showIndex].sleepTime * 1000);
        }
      } else {
        this.mobileNum++;
        //移动中图片
        this.mobileFunc(this.showIndex, this.mobileNum);
        this.animationtimer = requestAnimationFrame(this.circulation);
      }
    },
    // 移动图片的方法
    mobileFunc(index, mobileNum) {
      let styleData = this.styleFormat(this.contentData[index], mobileNum);
      this.contentData[index].borderStyle = styleData.borderStyle;
      this.contentData[index].contentStyle = styleData.contentStyle;
    },
    /**
     * 视频处理1播放0结束
     */
    videoStatus(status) {
      let souces = document.getElementsByClassName("ad_item");
      if (status == 1) {
        //当前展示为视频资源时播放视频
        souces[this.showIndex].play();
      } else {
        souces[this.showIndex].pause();
        souces[this.showIndex].currentTime = 0;
      }
    },
    resize() {
      let calculate = this.calculate();
      let contentData = [];
      for (let i = 0; i < this.contentData.length; i++) {
        contentData.push({ ...this.contentData[i], ...calculate });
      }
      this.contentData = contentData;
      for (let i = 0; i < this.contentData.length; i++) {
        this.mobileFunc(i, 0);
      }
    },
    /**
     * 视频播放结束
     */
    videoEnd() {
      this.mobileNum = 0;
      this.animationtimer = requestAnimationFrame(this.circulation);
    }
  },
  mounted() {
    let $this = this;
    if (this.slideshowTime) {
      cancelAnimationFrame(this.slideshowTime);
      this.slideshowTime = null;
    }
    this.slideshowTime = requestAnimationFrame($this.circulation);
    this.contentData = this.dataFormat(this.contentList);
    window.addEventListener("resize", $this.resize);
  },
  beforeDestroy() {
    if (this.slideshowTime) {
      cancelAnimationFrame(this.slideshowTime);
      this.slideshowTime = null;
    }
    window.removeEventListener("resize", this.resize);
  }
};
</script>
<style scoped>
.sideshow {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.ad_border {
  overflow: hidden;
  transform: rotate(45deg);
  position: fixed;
}
.ad_item {
  position: relative;
  width: 100vw;
  height: 100vh;
  object-fit: cover;
  overflow: hidden;
  transform: rotate(-45deg);
}
</style>
