<template>
  <div class="fullscreen-carousel" :style="style">
    <!-- 进度指示器 -->
    <div class="progress-indicator" :style="{width: progressWidth}"></div>

    <!-- 控制按钮 -->
<!--    <div class="controls">-->
<!--      <button class="control-btn" @click="prevSlide">-->
<!--        <i class="el-icon-arrow-left"></i>-->
<!--      </button>-->
<!--      <button class="control-btn" @click="nextSlide">-->
<!--        <i class="fas el-icon-arrow-right"></i>-->
<!--      </button>-->
<!--    </div>-->

    <el-carousel
      :direction="carouselStyle.direction"
      :indicator-position="carouselStyle.indicatorPosition"
      :type="carouselStyle.type"

      :interval="intervalTime"
      :autoplay="autoPlay"
      :loop="true"
      @change="handleSlideChange"
      @mouseenter.native="handleMouseEnter"
      arrow="always"
      :hover="false"
      ref="carousel">
      <el-carousel-item v-for="(slide, index) in slides" :key="index">
        <div class="slide">
          <div class="content-container">
            <!-- 当前和下一个幻灯片预加载 -->
            <template v-if="index === currentSlide || index === nextSlideIndex">
              <!-- 尝试使用object标签作为备用方案 -->
              <object v-if="slide.useObject"
                      :data="slide.url"
                      type="text/html"
                      @load="onContentLoad(index)"
                      @error="onContentError(index)"
                      :class="{loaded: !slide.loading && !slide.error}">
                <div class="fallback-content">
                  <i class="fas fa-exclamation-triangle"></i>
                  <h4>内容加载失败</h4>
                  <p>无法加载报表内容，请检查网络连接</p>
                </div>
              </object>

              <!-- 主要使用iframe -->
              <iframe v-else
                      :src="slide.url"
                      frameborder="0"
                      allowfullscreen
                      @load="onContentLoad(index)"
                      @error="onContentError(index)"
                      referrerpolicy="no-referrer"
                      :class="{loaded: !slide.loading && !slide.error}"
              ></iframe>
            </template>

            <div class="loading" v-if="slide.loading">
              <div class="spinner"></div>
              <p>报表加载中...</p>
            </div>

            <div class="error" v-if="slide.error && !slide.loading">
              <i class="fas fa-exclamation-triangle"></i>
              <p>报表加载失败</p>
            </div>
          </div>
        </div>
      </el-carousel-item>
    </el-carousel>

    <!-- 圆圈页码指示器 -->
    <div class="circle-indicator">
      <div
        v-for="(slide, index) in slides"
        :key="index"
        :class="['circle', { active: currentSlide === index }]"
        @click="goToSlide(index)"
      >
      </div>
    </div>

  </div>

</template>
<script>

export default {
  name: 'WidgetHtmlSlider',
  components: {},
  props: {
    value: Object,
    ispreview: Boolean
  },
  data() {
    return {
      options: {},
      optionsSetUp:{},
      carouselKey: 0, // 重新渲染组件用
      flagInter: null,

      autoPlay: true,
      intervalTime: 5000, // 5秒切换一次
      currentSlide: 0,
      nextSlideIndex: 1,
      progressWidth: '0%',
      progressInterval: null,

      slides: [{
        title: "",
        url: "#",
        loading: true,
        error: false,
        useObject: false
      }]
    };
  },
  computed: {
    transStyle() {
      const obj = this.objToOne(this.options);
      return obj;
    },
    style() {
      //整屏显示
      return {
        position: this.ispreview ? "absolute" : "static",
        width: "100%",
        height: "100%",
        left:"0px",
        top:"0px",
      };
    },
    carouselStyle() {
      this.initData(this.transStyle);
      return {
        direction: !this.transStyle.tabType ? this.transStyle.tabDirection : 'horizontal',
        indicatorPosition: this.transStyle.tabSelector,
        // intervalTime: this.transStyle.tabTime,
        type: this.transStyle.tabType
      }
    }
  },
  watch: {
    value: {
      handler(val) {
        if(!this.ispreview){
          this.options = val;
          this.optionsSetUp = val.setup;
          this.handlerUrlData();
        }
      },
      deep: true,
    },
    carouselStyle: {
      handler(newValue, oldValue) {
        if (JSON.stringify(newValue) !== JSON.stringify(oldValue)
        && !this.ispreview
        ) {
          this.carouselKey++;
        }
      },
    },
  },
  created() {
    this.options = this.value;
  },
  mounted() {
    this.$refs.carousel.handleMouseEnter=()=>{};
    // 初始加载第一个幻灯片
    this.slides[0].loading = true;
    this.startProgressBar();
    // 设置超时检查
    setTimeout(() => {
        // console.log("12313",this.slides);
      for(let index=0;index<this.slides.length;index++){
        let slide = this.slides[index];
        if (slide.loading && !slide.useObject) {
          this.slides[index].useObject = true;
        } else if (slide.loading && slide.useObject) {
          this.slides[index].loading = false;
          this.slides[index].error = true;
        }
      }
      // _this.slides.forEach((slide, index) => {
      //   if (slide.loading && !slide.useObject) {
      //     this.slides[index].useObject = true;
      //   } else if (slide.loading && slide.useObject) {
      //     this.slides[index].loading = false;
      //     this.slides[index].error = true;
      //   }
      // });
    }, this.intervalTime);
  },
  beforeDestroy() {
    clearInterval(this.progressInterval);
  },
  methods: {
    // reload(){
    //   this.isRouterAlive=false;
    //   this.$nextTick(function(){
    //     this.isRouterAlive=true;
    //   })
    // },
    initData(data) {
      let urlUp =[];
      if(this.hasOwn(data,"urls")){
        urlUp =  data['urls'];
      }
      let slides = [];
      if(this.isNotBlankArray(urlUp)){
        for(let i=0;i<urlUp.length;i++){
          const url = urlUp[i].url;
          const slidesOne = {};
          slidesOne.title="";
          slidesOne.url=url;
          slidesOne.loading=true;
          slidesOne.error=false;
          slidesOne.useObject=false;
          slides.push(slidesOne);
        }
      }
      this.slides = slides;
      this.intervalTime = this.isNotBlank(this.transStyle.tabTime)? this.transStyle.tabTime:5000;
      // this.slides={...this.slides};
    },
    handlerUrlData(){
      const data = this.optionsSetUp;
      let urlUp =[];
      if(this.hasOwn(data,"urls")){
        urlUp =  data['urls'];
      }else if(this.hasOwn(data,"dynamicHtmlSlider")){
        urlUp =  data['dynamicHtmlSlider'];
      }
      let slides = [];
      if(this.isNotBlankArray(urlUp)){
        for(let i=0;i<urlUp.length;i++){
          const url = urlUp[i].url;
          const slidesOne = {};
          slidesOne.title="";
          slidesOne.url=url;
          slidesOne.loading=true;
          slidesOne.error=false;
          slidesOne.useObject=false;
          slides.push(slidesOne);
        }
      }
      this.slides = slides;
      // this.slides={...this.slides};
    },

    goToSlide(index) {
      this.$refs.carousel.setActiveItem(index);
    },
    prevSlide() {
      this.$refs.carousel.prev();
    },
    nextSlide() {
      this.$refs.carousel.next();
    },
    onContentLoad(index) {
      this.slides[index].loading = false;
      this.slides[index].error = false;
    },
    onContentError(index) {
      if (!this.slides[index].useObject) {
        // 尝试使用object标签作为备用
        this.slides[index].useObject = true;
        this.slides[index].loading = true;
        this.slides[index].error = false;
      } else {
        this.slides[index].loading = false;
        this.slides[index].error = true;
      }
    },
    handleMouseEnter(){
      this.$refs.carousel.handleMouseEnter=()=>{};
    },

    handleSlideChange(currentIndex, prevIndex) {
      this.currentSlide = currentIndex;
      // 计算下一个幻灯片索引（用于预加载）
      this.nextSlideIndex = (currentIndex + 1) % this.slides.length;

      // 启动当前幻灯片的加载（如果尚未加载）
      if (this.slides[currentIndex].loading === false &&
        this.slides[currentIndex].error === false) {
        // 内容已加载，无需操作
      } else {
        this.slides[currentIndex].loading = true;
        this.slides[currentIndex].error = false;
      }

      // 启动进度条
      this.startProgressBar();
    },
    startProgressBar() {
      clearInterval(this.progressInterval);
      this.progressWidth = '0%';

      if (!this.autoPlay) return;

      const startTime = Date.now();
      const duration = this.intervalTime;

      this.progressInterval = setInterval(() => {
        const elapsed = Date.now() - startTime;
        const percent = Math.min(100, (elapsed / duration) * 100);
        this.progressWidth = percent + '%';

        if (percent >= 100) {
          clearInterval(this.progressInterval);
        }
      }, this.intervalTime);
    }
  },
}
</script>
<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body, html {
  width: 100%;
  height: 100%;
  overflow: hidden;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background: #000;
}

.fullscreen-carousel {
  width: 100%;
  height: 100%;
  position: relative;
  background: #000;
}

.el-carousel {
  width: 100%;
  height: 100%;
}

.el-carousel__container {
  height: 100% !important;
}

.slide {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #000;
}

.content-container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.content-container iframe,
.content-container object {
  width: 100%;
  height: 100%;
  border: none;
  opacity: 0;
  transition: opacity 0.5s ease-in-out;
}

.content-container iframe.loaded,
.content-container object.loaded {
  opacity: 1;
}

.fallback-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #2c3e50, #4ca1af);
  color: white;
  text-align: center;
  padding: 20px;
}

.fallback-content i {
  font-size: 3rem;
  margin-bottom: 20px;
  color: #ffc107;
}

.fallback-content h4 {
  font-size: 1.5rem;
  margin-bottom: 10px;
}

.loading, .error {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  z-index: 20;
}

.loading i, .error i {
  font-size: 2rem;
  margin-bottom: 15px;
}

/* 隐藏轮播指示器 */
.el-carousel__indicators {
  display: none;
}

/* 加载动画 */
.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: #fff;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 圆圈页码指示器 */
.circle-indicator {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 10px;
  z-index: 100;
}

.circle {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.4);
  transition: all 0.3s ease;
  cursor: pointer;
}

.circle.active {
  background: #fff;
  transform: scale(1.2);
  box-shadow: 0 0 5px rgba(255, 255, 255, 0.8);
}

.circle:hover {
  background: rgba(255, 255, 255, 0.7);
}

/* 控制按钮 */
.controls {
  position: fixed;
  top: 50%;
  transform: translateY(-50%);
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  z-index: 100;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.fullscreen-carousel:hover .controls {
  opacity: 0.7;
}

.controls:hover {
  opacity: 1;
}
//el-icon-arrow-left
.control-btn {
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  font-size: 1.5rem;
  transition: all 0.3s ease;
}

.control-btn:hover {
  background: rgba(0, 0, 0, 0.8);
  transform: scale(1.1);
}

/* 进度指示器 */
.progress-indicator {
  position: fixed;
  top: 0;
  left: 0;
  height: 3px;
  background: linear-gradient(90deg, #4ca1af, #2c3e50);
  z-index: 101;
  transition: width 0.3s ease;
}
</style>
