<template>
  <view class="three-item-swiper">
    <!-- 轮播容器 -->
    <view class="swiper-container" :style="{ height: containerHeight + 'px' }">
      <view class="swiper-wrapper" 
            :style="{ 
              transform: `translateX(${translateX}px)`,
              transition: isAnimating ? 'transform 0.3s ease-out' : 'none'
            }">
        <!-- 轮播项 -->
        <view class="swiper-item" 
              v-for="(item, index) in items" 
              :key="index"
              :style="getItemStyle(index)">
          <image :src="item.imgUrl" mode="cover" class="item-image" :alt="item.title"></image>
          <view class="item-title" v-if="item.title">{{ item.title }}</view>
        </view>
      </view>
    </view>

    <!-- 指示点 -->
    <view class="indicators">
      <view class="indicator"
            v-for="(item, index) in items"
            :key="index"
            :class="{ active: index === currentIndex }"
            @click="switchTo(index)"></view>
    </view>
  </view>
</template>

<script>
export default {
  props: {
    // 轮播数据
    items: {
      type: Array,
      required: true,
      default: () => []
    },
    // 容器高度(px)
    containerHeight: {
      type: Number,
      default: 400
    },
    // 自动轮播间隔(ms)，0为不自动轮播
    autoPlay: {
      type: Number,
      default: 3000
    },
    // 中间项放大比例
    scaleRatio: {
      type: Number,
      default: 1.2
    }
  },
  data() {
    return {
      currentIndex: 0,       // 当前居中索引
      startX: 0,             // 触摸起始X
      moveX: 0,              // 移动X
      translateX: 0,         // 容器偏移量
      itemWidth: 0,          // 项宽度
      isAnimating: false,    // 是否动画中
      isDragging: false,     // 是否拖拽中
      timer: null            // 自动播放定时器
    };
  },
  watch: {
    items() {
      this.currentIndex = 0;
      this.$nextTick(() => {
        this.calculateLayout();
      });
      this.resetAutoPlay();
    },
    currentIndex() {
      this.updatePosition(true);
    },
    autoPlay() {
      this.resetAutoPlay();
    }
  },
  mounted() {
    // 初始化布局
    this.$nextTick(() => {
      this.calculateLayout();
    });
    
    // 监听窗口尺寸变化
    uni.onWindowResize(() => {
      this.$nextTick(() => {
        this.calculateLayout();
      });
    });
    
    // 初始化自动播放
    this.initAutoPlay();
  },
  beforeDestroy() {
    this.clearTimer();
    uni.offWindowResize();
  },
  methods: {
    // 计算布局
    calculateLayout() {
      // 获取容器宽度
      const query = uni.createSelectorQuery().in(this);
      query.select('.swiper-container').boundingClientRect(data => {
        if (data) {
          // 计算每个项的宽度（容器的一半）
          this.itemWidth = data.width / 2;
          this.updatePosition(false);
        }
      }).exec();
    },
    
    // 更新位置
    updatePosition(animate = true) {
      if (!this.itemWidth) return;
      
      this.isAnimating = animate;
      // 计算偏移量，让当前项居中
      this.translateX = this.itemWidth - this.currentIndex * this.itemWidth;
    },
    
    // 获取每个项的样式
    getItemStyle(index) {
      if (!this.itemWidth) return {};
      
      // 计算与当前项的距离
      const distance = Math.abs(index - this.currentIndex);
      let scale = 1;
      let zIndex = 1;
      let opacity = 0.8;
      
      // 中间项放大
      if (distance === 0) {
        scale = this.scaleRatio;
        zIndex = 10;
        opacity = 1;
      }
      
      return {
        width: `${this.itemWidth}px`,
        transform: `scale(${scale})`,
        zIndex,
        opacity,
        transition: this.isAnimating ? 'all 0.3s ease-out' : 'none'
      };
    },
    
    // 触摸开始
    handleTouchStart(e) {
      if (this.items.length <= 1) return;
      
      this.isDragging = true;
      this.isAnimating = false;
      this.startX = e.touches[0].clientX;
      this.clearTimer(); // 停止自动播放
    },
    
    // 触摸移动
    handleTouchMove(e) {
      if (!this.isDragging || this.items.length <= 1) return;
      
      this.moveX = e.touches[0].clientX;
      const diffX = this.moveX - this.startX;
      
      // 计算临时偏移量（增加阻力感）
      this.translateX = (this.itemWidth - this.currentIndex * this.itemWidth) + diffX * 0.8;
    },
    
    // 触摸结束
    handleTouchEnd() {
      if (!this.isDragging || this.items.length <= 1) return;
      
      this.isDragging = false;
      const diffX = this.moveX - this.startX;
      const threshold = this.itemWidth / 3; // 滑动阈值
      
      // 判断滑动方向
      if (diffX > threshold) {
        // 向右滑动，上一项
        this.prev();
      } else if (diffX < -threshold) {
        // 向左滑动，下一项
        this.next();
      } else {
        // 未达到阈值，回弹
        this.updatePosition(true);
      }
      
      this.resetAutoPlay(); // 恢复自动播放
    },
    
    // 下一项
    next() {
      if (this.currentIndex >= this.items.length - 1) {
        this.currentIndex = 0; // 循环到第一项
      } else {
        this.currentIndex++;
      }
    },
    
    // 上一项
    prev() {
      if (this.currentIndex <= 0) {
        this.currentIndex = this.items.length - 1; // 循环到最后一项
      } else {
        this.currentIndex--;
      }
    },
    
    // 切换到指定索引
    switchTo(index) {
      if (index === this.currentIndex) return;
      this.currentIndex = index;
      this.resetAutoPlay();
    },
    
    // 初始化自动播放
    initAutoPlay() {
      if (this.autoPlay > 0 && this.items.length > 1) {
        this.timer = setInterval(() => {
          this.next();
        }, this.autoPlay);
      }
    },
    
    // 重置自动播放
    resetAutoPlay() {
      this.clearTimer();
      this.initAutoPlay();
    },
    
    // 清除定时器
    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    }
  }
};
</script>

<style scoped>
.three-item-swiper {
  position: relative;
  width: 100%;
  overflow: hidden;
}

/* 轮播容器 */
.swiper-container {
  position: relative;
  width: 100%;
  overflow: hidden;
}

/* 轮播轨道 */
.swiper-wrapper {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  display: flex;
}

/* 轮播项 */
.swiper-item {
  height: 100%;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
}

/* 图片样式 */
.item-image {
  width: 100%;
  height: 100%;
  border-radius: 16rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
}

/* 标题样式 */
.item-title {
  position: absolute;
  bottom: 20rpx;
  left: 0;
  right: 0;
  text-align: center;
  color: #fff;
  font-size: 32rpx;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.5);
  padding: 0 20rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 指示点容器 */
.indicators {
  display: flex;
  justify-content: center;
  gap: 12rpx;
  padding: 20rpx 0;
}

/* 指示点样式 */
.indicator {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  background-color: #ddd;
  transition: all 0.3s ease;
}

/* 激活状态指示点 */
.indicator.active {
  width: 40rpx;
  border-radius: 8rpx;
  background-color: #007aff;
}
</style>
