<script lang="ts" setup>
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Tag } from 'ant-design-vue';

import { getProductInfoApi } from '#/views/my-gen/product/api';

// 定义商品类型
interface Product {
  id?: string;
  title?: string;
  introduction?: string;
  price?: number;
  originalPrice?: number;
  discount?: number;
  cover?: string;
  images?: string[];
  isNew?: boolean;
  isFavorite?: boolean;
  viewCount?: number;
  favoriteCount?: number;
  soldCount?: number;
  returnCount?: number;
  [key: string]: any;
}

const props = defineProps({
  // 可选的默认商品数据
  defaultProduct: {
    type: Object as () => Product,
    default: () => ({}),
  },
});

const emits = defineEmits(['addToCart', 'buyNow', 'favoriteChanged']);

const product = ref<Product>(props.defaultProduct || {});
const previewTitle = ref('商品详情');

// 轮播图状态
const currentSlideIndex = ref(0);
let autoplayTimer: null | ReturnType<typeof setInterval> = null;

// 缩略图容器引用
const thumbnailContainer = ref<HTMLDivElement | null>(null);

// 缩略图滚动状态
const canScrollLeft = ref(false);
const canScrollRight = ref(false);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    modalApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { values } = modalApi.getData<Record<string, any>>();
      if (values) {
        getProductInfoApi(values).then((res: Product) => {
          product.value = res;
          previewTitle.value = `${res.title || '商品'}详情`;
          currentSlideIndex.value = 0; // 重置轮播图索引
          startAutoplay(); // 启动自动轮播

          // 等待DOM更新后滚动到第一个缩略图
          nextTick(() => {
            updateScrollState();
            scrollToActiveThumbnail();
          });
        });
      }
    } else {
      stopAutoplay(); // 关闭时停止自动轮播
    }
  },
});

// 监听外部props变化更新商品数据
watch(
  () => props.defaultProduct,
  (newVal: Product) => {
    if (newVal && JSON.stringify(newVal) !== JSON.stringify(product.value)) {
      product.value = { ...newVal };
      currentSlideIndex.value = 0; // 重置轮播图索引

      // 等待DOM更新后滚动到第一个缩略图
      nextTick(() => {
        updateScrollState();
        scrollToActiveThumbnail();
      });
    }
  },
  { deep: true },
);

// 轮播图控制方法
const nextSlide = () => {
  const imageCount = product.value.images?.length || 0;
  if (imageCount > 0) {
    currentSlideIndex.value = (currentSlideIndex.value + 1) % imageCount;
    resetAutoplay();
  }
};

const prevSlide = () => {
  const imageCount = product.value.images?.length || 0;
  if (imageCount > 0) {
    currentSlideIndex.value =
      (currentSlideIndex.value - 1 + imageCount) % imageCount;
    resetAutoplay();
  }
};

// 自动轮播控制
const startAutoplay = () => {
  stopAutoplay();
  const imageCount = product.value.images?.length || 0;
  if (imageCount > 1) {
    autoplayTimer = setInterval(() => {
      nextSlide();
    }, 5000);
  }
};

const stopAutoplay = () => {
  if (autoplayTimer) {
    clearInterval(autoplayTimer);
    autoplayTimer = null;
  }
};

const resetAutoplay = () => {
  stopAutoplay();
  startAutoplay();
};

// 图片加载错误处理
const handleImageError = (e: Event) => {
  (e.target as HTMLImageElement).src =
    'https://picsum.photos/800/600?random=error';
};

// 缩略图滚动控制
const scrollThumbnails = (direction: number) => {
  if (!thumbnailContainer.value) return;

  const container = thumbnailContainer.value;
  const scrollAmount = container.clientWidth * 0.7; // 每次滚动70%的容器宽度

  container.scrollBy({
    left: direction * scrollAmount,
    behavior: 'smooth',
  });

  // 更新滚动状态
  setTimeout(updateScrollState, 300);
};

// 滚动到当前选中的缩略图
const scrollToActiveThumbnail = () => {
  if (
    !thumbnailContainer.value ||
    !product.value.images ||
    product.value.images.length === 0
  )
    return;

  const container = thumbnailContainer.value;
  const thumbnails = container.querySelectorAll('img');
  const activeThumbnail = thumbnails[currentSlideIndex.value];

  if (activeThumbnail) {
    // 计算将当前缩略图居中所需的滚动位置
    const thumbnailRect = activeThumbnail.getBoundingClientRect();
    const containerRect = container.getBoundingClientRect();
    const scrollPosition =
      activeThumbnail.offsetLeft -
      (container.clientWidth - thumbnailRect.width) / 2;

    // 平滑滚动到计算的位置
    container.scrollTo({
      left: scrollPosition,
      behavior: 'smooth',
    });

    // 更新滚动状态
    setTimeout(updateScrollState, 300);
  }
};

// 更新滚动按钮状态
const updateScrollState = () => {
  if (!thumbnailContainer.value) return;

  const container = thumbnailContainer.value;
  canScrollLeft.value = container.scrollLeft > 10;
  canScrollRight.value =
    container.scrollLeft < container.scrollWidth - container.clientWidth - 10;
};

// 监听当前图片索引变化，滚动到对应缩略图
watch(currentSlideIndex, () => {
  scrollToActiveThumbnail();
});

// 生命周期钩子
onMounted(() => {
  startAutoplay();

  // 监听容器滚动事件，更新滚动按钮状态
  if (thumbnailContainer.value) {
    thumbnailContainer.value.addEventListener('scroll', updateScrollState);
  }
});

onUnmounted(() => {
  stopAutoplay();

  // 移除滚动事件监听器
  if (thumbnailContainer.value) {
    thumbnailContainer.value.removeEventListener('scroll', updateScrollState);
  }
});
</script>

<template>
  <Modal :title="previewTitle" class="w-[50%]">
    <div class="p-6">
      <div class="grid grid-cols-1 gap-8 lg:grid-cols-5">
        <!-- 图片轮播区域（内联实现） -->
        <div class="space-y-4 lg:col-span-2">
          <div
            class="carousel-shadow group relative overflow-hidden rounded-xl"
          >
            <!-- 主图轮播 -->
            <div
              class="flex transition-transform duration-500 ease-in-out"
              :style="{ transform: `translateX(-${currentSlideIndex * 100}%)` }"
            >
              <img
                v-for="(img, index) in product.images || []"
                :key="index"
                :src="img"
                alt="商品图片"
                class="h-auto w-full object-cover"
                height="600"
                @error="handleImageError"
              />
            </div>

            <!-- 轮播控制器 -->
            <button
              @click="prevSlide"
              class="text-primary absolute left-4 top-1/2 z-10 flex h-10 w-10 -translate-y-1/2 items-center justify-center rounded-full bg-white/80 opacity-70 shadow-md transition-all duration-300 hover:bg-white group-hover:opacity-100"
            >
              <span class="icon-[icon-park-outline--left]"></span>
            </button>
            <button
              @click="nextSlide"
              class="text-primary absolute right-4 top-1/2 z-10 flex h-10 w-10 -translate-y-1/2 items-center justify-center rounded-full bg-white/80 opacity-70 shadow-md transition-all duration-300 hover:bg-white group-hover:opacity-100"
            >
              <span class="icon-[icon-park-outline--right]"></span>
            </button>

            <!-- 指示器 -->
            <div
              class="absolute bottom-4 left-1/2 flex -translate-x-1/2 space-x-2"
            >
              <button
                v-for="(img, index) in product.images || []"
                :key="index"
                @click="currentSlideIndex = index"
                class="h-3 w-3 rounded-full transition-all duration-300"
                :class="{
                  'bg-primary': index === currentSlideIndex,
                  'bg-white/50 hover:bg-white/80': index !== currentSlideIndex,
                }"
              ></button>
            </div>

            <!-- 标签和计数器 -->
            <div class="absolute left-4 top-4 z-10" v-if="product.isNew">
              <span
                class="bg-secondary rounded-full px-3 py-1 text-sm font-medium text-white shadow-md"
                >新品</span
              >
            </div>
            <div
              class="absolute right-4 top-4 rounded bg-black/50 px-2 py-1 text-xs font-medium text-white shadow-md"
            >
              {{ currentSlideIndex + 1 }} /
              {{ (product.images && product.images.length) || 0 }}
            </div>
          </div>

          <!-- 缩略图区域 -->
          <div class="relative">
            <!-- 左侧滑动按钮 -->
            <button
              @click="scrollThumbnails(-1)"
              :disabled="!canScrollLeft"
              class="text-primary absolute left-0 top-1/2 z-10 flex h-8 w-8 -translate-y-1/2 cursor-pointer items-center justify-center rounded-full bg-white/90 opacity-80 shadow-md transition-all duration-300 hover:bg-white"
              :class="{ 'cursor-not-allowed opacity-40': !canScrollLeft }"
            >
              <span class="icon-[icon-park-outline--left]"></span>
            </button>

            <!-- 缩略图容器 -->
            <div
              ref="thumbnailContainer"
              class="scrollbar-hide flex space-x-3 overflow-x-auto pb-2 pl-10 pr-10"
            >
              <img
                v-for="(img, index) in product.images || []"
                :key="index"
                :src="img"
                alt="商品缩略图"
                @click="currentSlideIndex = index"
                class="thumbnail-shadow h-20 w-20 cursor-pointer rounded-lg border-2 object-cover transition-all duration-300 sm:h-24 sm:w-24"
                :class="{
                  'border-primary ring-primary/30 ring-2':
                    index === currentSlideIndex,
                  'hover:border-primary/50 border-transparent':
                    index !== currentSlideIndex,
                }"
                @error="handleImageError"
              />
            </div>

            <!-- 右侧滑动按钮 -->
            <button
              @click="scrollThumbnails(1)"
              :disabled="!canScrollRight"
              class="text-primary absolute right-0 top-1/2 z-10 flex h-8 w-8 -translate-y-1/2 cursor-pointer items-center justify-center rounded-full bg-white/90 opacity-80 shadow-md transition-all duration-300 hover:bg-white"
              :class="{ 'cursor-not-allowed opacity-40': !canScrollRight }"
            >
              <span class="icon-[icon-park-outline--right]"></span>
            </button>
          </div>
        </div>

        <!-- 商品信息区域保持不变 -->
        <div class="lg:col-span-3">
          <!-- 保持原有内容不变 -->
          <div class="space-y-6">
            <div>
              <h1
                class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold leading-tight"
              >
                {{ product.title }}
              </h1>
              <p class="mt-2 text-neutral-500">{{ product.introduction }}</p>
            </div>

            <!-- 价格区域 -->
            <div class="rounded-lg p-4">
              <div class="mb-2 flex items-end">
                <span class="text-3xl font-bold">¥{{ product.price }}</span>
                <span
                  v-if="product.originalPrice"
                  class="ml-3 text-lg line-through"
                  >¥{{ product.originalPrice || 0 }}</span>
                <span
                  v-if="product.discount"
                  class="bg-secondary/10 text-secondary ml-2 rounded px-2 py-1 text-sm"
                >
                  省¥{{ product.discount }}
                </span>
              </div>
              <div class="flex flex-wrap gap-x-6 gap-y-2 text-sm">
                <div class="flex items-center">
                  <i class="fa fa-eye mr-1"></i>
                  <span>浏览: {{ product.viewCount || 0 }}</span>
                </div>
                <div class="flex items-center">
                  <i class="fa fa-heart mr-1"></i>
                  <span>收藏: {{ product.favoriteCount || 0 }}</span>
                </div>
                <div class="flex items-center">
                  <i class="fa fa-shopping-bag mr-1"></i>
                  <span>已售: {{ product.soldCount || 0 }}</span>
                </div>
                <div class="flex items-center">
                  <i class="fa fa-exchange mr-1"></i>
                  <span>退货: {{ product.returnCount || 0 }}</span>
                </div>
              </div>
            </div>

            <!-- 商品特性 -->
            <div class="space-y-4">
              <div class="flex items-start">
                <div class="mt-1 w-16 flex-shrink-0 text-neutral-500">配送</div>
                <div class="ml-4">
                  <div class="flex items-center">
                    <span class="text-neutral-800">全国大部分地区包邮</span>
                    <span
                      class="text-primary ml-2 cursor-pointer hover:underline"
                      >配送查询</span
                    >
                  </div>
                  <p class="mt-1 text-sm text-neutral-500">预计2-5天送达</p>
                </div>
              </div>

              <div class="flex items-start">
                <div class="mt-1 w-16 flex-shrink-0 text-neutral-500">服务</div>
                <div class="ml-4 flex flex-wrap gap-4">
                  <div
                    v-for="item in product.labels"
                    :key="item.id"
                    class="flex items-center"
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="28"
                      height="28"
                      viewBox="0 0 24 24"
                    >
                      <g
                        fill="none"
                        stroke="#059669"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="1.5"
                        color="#059669"
                      >
                        <path
                          d="M18.99 19H19m-.01 0c-.622.617-1.75.464-2.542.464c-.972 0-1.44.19-2.133.883C13.725 20.937 12.934 22 12 22s-1.725-1.063-2.315-1.653c-.694-.693-1.162-.883-2.133-.883c-.791 0-1.92.154-2.543-.464c-.627-.622-.473-1.756-.473-2.552c0-1.007-.22-1.47-.937-2.186C2.533 13.196 2 12.662 2 12s.533-1.196 1.6-2.262c.64-.64.936-1.274.936-2.186c0-.791-.154-1.92.464-2.543c.622-.627 1.756-.473 2.552-.473c.912 0 1.546-.297 2.186-.937C10.804 2.533 11.338 2 12 2s1.196.533 2.262 1.6c.64.64 1.274.936 2.186.936c.791 0 1.92-.154 2.543.464c.627.622.473 1.756.473 2.552c0 1.007.22 1.47.937 2.186C21.467 10.804 22 11.338 22 12s-.533 1.196-1.6 2.262c-.716.717-.936 1.18-.936 2.186c0 .796.154 1.93-.473 2.552"
                        />
                        <path
                          d="M9 12.893s1.2.652 1.8 1.607c0 0 1.8-3.75 4.2-5"
                        />
                      </g>
                    </svg>
                    <Tag color="#7166f0">{{ item.name }}</Tag>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Modal>
</template>

<style scoped>
.carousel-shadow {
  box-shadow:
    0 10px 25px -5px rgba(0, 0, 0, 0.1),
    0 8px 10px -6px rgba(0, 0, 0, 0.1);
}
.thumbnail-shadow {
  box-shadow:
    0 4px 6px -1px rgba(0, 0, 0, 0.1),
    0 2px 4px -2px rgba(0, 0, 0, 0.1);
}
.scrollbar-hide {
  -ms-overflow-style: none;
  scrollbar-width: none;
}
.scrollbar-hide::-webkit-scrollbar {
  display: none;
}
.opacity-40 {
  opacity: 0.4;
}
.cursor-not-allowed {
  cursor: not-allowed;
}
</style>
