<template>
  <div
    class="swiper-container"
    :style="'z-index:'+(ifShow?11:-99)+';'"
  >
    <video
      class="ad_item"
      v-if="contentData.length==1&&contentData[0].type=='video'"
      :src="contentData[0].path"
      loop
      autoplay
      muted
    />
    <div
      v-else
      class="swiper-wrapper"
    >
      <div
        class="swiper-slide"
        v-for="(item, index) in contentData"
        :key="index"
      >
        <img
          v-if="item.type=='img'"
          class="ad_item"
          :src="item.path"
        />
        <video
          :id="'ad_item'+index"
          class="ad_item"
          v-else
          :src="item.path"
          preload
          muted
        />
      </div>
    </div>
  </div>
</template>

<script>
import Swiper from "swiper";
import "swiper/dist/css/swiper.min.css";
export default {
  name: "SwiperCarousel",
  watch: {
    contentList(data) {
      this.contentData = this.dataFormat(data);
      this.$nextTick(() => {
        this.initSwiper();
      });
    }
  },
  props: {
    //播放内容
    contentList: {
      type: Array,
      default: () => []
    },
    // 停留时间秒
    sleepTime: {
      type: Number,
      default: 3
    },
    ifShow: {
      type: Boolean,
      default: false
    },
    swiperOptions: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  methods: {
    /**
     * 轮播数据格式处理
     */
    dataFormat(data) {
      let result = [];
      let $this = this;
      if (data.length > 0) {
        data.forEach((item, index) => {
          let ob = {};
          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";
            result.push(ob);
          } else if (videoRegex.test(fileName)) {
            ob.type = "video";
            result.push(ob);
          } else {
            if (ktLog && ktLog.e) {
              ktLog.e(`${JSON.stringify(item)} 广告文件`);
            }
          }
        });
      }
      if (ktLog && ktLog.i) {
        ktLog.i(`播放广告数据：${JSON.stringify(result)}`);
      }
      return result;
    },
    initSwiper() {
      if (this.swiper) {
        this.swiper.destroy(true, true);
      }
      let options = {
        loop: true,
        autoplay: {
          delay: this.sleepTime * 1000,
          disableOnInteraction: false
        },
        slidesPerView: "auto",
        spaceBetween: 0,
        centeredSlides: true,
        on: {
          slideChange: () => {
            const currentSlide = this.swiper.slides[this.swiper.activeIndex];
            const currentSlideItem = this.contentData[
              this.swiper.activeIndex % this.contentData.length
            ];

            if (currentSlideItem.type === "video") {
              const videoElement = currentSlide.querySelector("video");
              console.log(
                "视频播放开始",
                this.swiper.activeIndex,
                videoElement.duration
              );
              videoElement.play();
              this.swiper.autoplay.stop();
              if (this.videoTimeOut) {
                clearTimeout(this.videoTimeOut);
                this.videoTimeOut = null;
              }
              this.videoTimeOut = setTimeout(() => {
                console.log("视频播放结束setTimeout");
                this.swiper.slideNext();
                this.swiper.autoplay.start();
              }, videoElement.duration * 1000);
            }
          }
        }
      };
      options = { ...options, ...this.swiperOptions };
      this.swiper = new Swiper(".swiper-container", options);
    }
  },
  data() {
    return {
      contentData: [],
      swiper: null,
      videoTimeOut: null
    };
  },
  mounted() {
    this.contentData = this.dataFormat(this.contentList);
    this.$nextTick(() => {
      this.initSwiper();
    });
  },
  beforeDestroy() {
    if (this.swiper) {
      this.swiper.destroy(true, true);
    }
  }
};
</script>

<style scoped>
.swiper-container {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
  overflow: hidden;
}
.swiper-slide {
  text-align: center;
  font-size: 18px;
  background: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  border: none; /* 去掉边框 */
  overflow: hidden;
}

.ad_item {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 图片填充整个容器 */
  overflow: hidden;
}
</style>