<template>
  <div
      class="relative rounded-2xl overflow-hidden shadow-xl"
      @touchstart="startDrag"
      @touchmove="onDrag"
      @touchend="endDrag"
      @mousedown="startDrag"
      @mousemove="onDrag"
      @mouseup="endDrag"
      @mouseleave="endDrag"
  >
    <!-- 公司实景轮播图 -->
    <div class="relative h-96 overflow-hidden">
      <div
          v-for="(slide, index) in companySlides"
          :key="index"
          class="absolute inset-0 transition-transform duration-500 ease-in-out"
          :style="{
            transform: getSlideTransform(index),
            zIndex: getSlideZIndex(index)
          }"
      >
        <div
            class="absolute inset-0"
            :class="{
              'animate-kenburns': currentSlide === index
            }"
        >
          <!-- 使用img标签确保图片正常显示 -->
          <img :src="slide.src" :alt="slide.alt" class="w-full h-full object-cover"></img>
        </div>
      </div>
    </div>

    <!-- 轮播控制按钮 - 小圆点指示器（始终显示） -->
    <div class="absolute bottom-4 left-1/2 transform -translate-x-1/2 flex space-x-2 z-50">
      <button
          v-for="(slide, index) in companySlides"
          :key="index"
          class="w-3 h-3 rounded-full bg-white/50 hover:bg-white transition-colors cursor-pointer"
          :class="{ '!bg-white': currentSlide === index }"
          @click="goToSlide(index)"
      ></button>
    </div>

    <!-- 左右切换按钮 - 只在PC端显示 -->
    <button
        @click="goToSlide(currentSlide - 1)"
        class="hidden md:flex absolute left-4 top-1/2 transform -translate-y-1/2 w-10 h-10 rounded-full bg-white/20 hover:bg-white/40 items-center justify-center transition-colors cursor-pointer z-50"
    >
      <svg width="14" height="24" viewBox="0 0 14 24" xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-white">
        <polyline fill="none" stroke="currentColor" stroke-width="1.4" points="12.775,1 1.225,12 12.775,23"></polyline>
      </svg>
    </button>
    <button
        @click="goToSlide(currentSlide + 1)"
        class="hidden md:flex absolute right-4 top-1/2 transform -translate-y-1/2 w-10 h-10 rounded-full bg-white/20 hover:bg-white/40 items-center justify-center transition-colors cursor-pointer z-50"
    >
      <svg width="14" height="24" viewBox="0 0 14 24" xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-white">
        <polyline fill="none" stroke="currentColor" stroke-width="1.4" points="1.225,23 12.775,12 1.225,1"></polyline>
      </svg>
    </button>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
// 请确保这些图片路径正确
import img1 from '@/assets/images/company0002.jpeg'
import img2 from '@/assets/images/company0003.jpeg'
import img3 from '@/assets/images/company0004.jpeg'
import img4 from '@/assets/images/company0005.jpeg'
import img5 from '@/assets/images/company0006.png'

const currentSlide = ref(0)
const prevSlide = ref(null)
const isDragging = ref(false)
const dragStartX = ref(0)
const dragCurrentX = ref(0)
const dragDelta = ref(0)
const direction = ref('right') // 添加方向状态

const companySlides = ref([
  { src: img1, alt: '公司环境实景1' },
  { src: img2, alt: '公司环境实景2' },
  { src: img3, alt: '公司环境实景3' },
  { src: img4, alt: '公司环境实景4' },
  { src: img5, alt: '公司环境实景5' }
])

let slideInterval = null

// 轮播图控制函数
const goToSlide = (index) => {
  const slidesCount = companySlides.value.length;

  // 计算正确的索引
  if (index < 0) index = slidesCount - 1;
  else if (index >= slidesCount) index = 0;

  // 确定切换方向
  direction.value = index > currentSlide.value ? 'right' : 'left';

  // 更新幻灯片索引
  prevSlide.value = currentSlide.value;
  currentSlide.value = index;

  resetInterval();
}

// 重置自动轮播计时器
const resetInterval = () => {
  clearInterval(slideInterval)
  slideInterval = setInterval(() => {
    direction.value = 'right';
    goToSlide(currentSlide.value + 1)
  }, 5000)
}

// 触摸/鼠标拖动功能
const startDrag = (e) => {
  // 阻止鼠标事件在按钮上触发拖动
  if (e.target.closest('button')) return;

  isDragging.value = true;
  dragStartX.value = getClientX(e);
  dragCurrentX.value = dragStartX.value;
  dragDelta.value = 0;
  clearInterval(slideInterval);

  // 添加拖动样式，提高性能
  document.body.classList.add('dragging');

  // PC端添加额外处理
  if (e.type === 'mousedown') {
    e.preventDefault();
  }
}

const onDrag = (e) => {
  if (!isDragging.value) return;

  const clientX = getClientX(e);
  dragDelta.value = clientX - dragStartX.value;
  dragCurrentX.value = clientX;

  // PC端添加额外处理
  if (e.type === 'mousemove') {
    e.preventDefault();
  }
}

const endDrag = () => {
  if (!isDragging.value) return;

  isDragging.value = false;
  document.body.classList.remove('dragging');

  // 根据拖动距离判断是否切换幻灯片
  const threshold = window.innerWidth / 5; // 调整为屏幕宽度的1/5

  if (Math.abs(dragDelta.value) > threshold) {
    if (dragDelta.value > 0) {
      direction.value = 'left';
      goToSlide(currentSlide.value - 1); // 向右拖动，切换到上一张
    } else {
      direction.value = 'right';
      goToSlide(currentSlide.value + 1); // 向左拖动，切换到下一张
    }
  } else {
    // 如果拖动距离不够，回到当前位置
    dragDelta.value = 0;
  }

  resetInterval();
}

// 获取客户端X坐标（兼容触摸和鼠标事件）
const getClientX = (e) => {
  if (e.type.includes('touch')) {
    return e.touches[0] ? e.touches[0].clientX : e.changedTouches[0].clientX;
  }
  return e.clientX;
}

// 获取幻灯片变换值
const getSlideTransform = (index) => {
  if (isDragging.value) {
    // 拖动状态：当前幻灯片跟随拖动位置
    if (index === currentSlide.value) {
      return `translateX(${dragDelta.value}px)`;
    }
    // 其他幻灯片保持原位
    return `translateX(${index > currentSlide.value ? '100%' : '-100%'})`;
  }

  // 非拖动状态
  if (index === currentSlide.value) {
    return 'translateX(0)';
  }

  // 根据方向确定位置
  if (direction.value === 'right') {
    return `translateX(${index > currentSlide.value ? '100%' : '-100%'})`;
  } else {
    return `translateX(${index > currentSlide.value ? '100%' : '-100%'})`;
  }
}

// 获取幻灯片层级
const getSlideZIndex = (index) => {
  // 当前幻灯片最高层级
  if (index === currentSlide.value) return 30;

  // 下一张幻灯片次高
  const nextIndex = direction.value === 'right'
      ? (currentSlide.value + 1) % companySlides.value.length
      : (currentSlide.value - 1 + companySlides.value.length) % companySlides.value.length;

  if (index === nextIndex) return 20;

  // 其他幻灯片最低
  return 10;
}

onMounted(() => {
  resetInterval()
})

onUnmounted(() => {
  clearInterval(slideInterval)
})
</script>

<style scoped>
/* 定义Ken Burns效果动画 */
@keyframes kenburns {
  0% {
    transform: scale(1.05);
    transform-origin: 50% 50%;
  }
  100% {
    transform: scale(1);
    transform-origin: 50% 50%;
  }
}

.animate-kenburns {
  animation: kenburns 5s linear forwards;
}

/* 定义滑动动画效果 */
.transition-transform {
  transition: transform 0.5s ease-in-out;
}

/* 拖动时的性能优化 */
.dragging * {
  user-select: none;
  pointer-events: none;
}

/* 确保图片填充容器 */
.object-cover {
  object-fit: cover;
  width: 100%;
  height: 100%;
}
</style>