<script setup lang="ts">
/**
 * 商品详情页
 *
 * 布局（桌面双栏）：
 *   左侧：图片画廊（主图 + 缩略图列表）
 *   右侧：商品信息（名称/品牌/价格/SKU 选择/数量/加购按钮）
 *   底部：商品详情富文本 + 参数表格
 */
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ShoppingCart, Plus, Minus } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/modules/user'
import { getProductDetailApi } from '@/api/product'
import { addToCartApi } from '@/api/cart'
import type { ProductDetail, ProductSku } from '@/types/product'
import AppHeader from '@/components/layout/AppHeader.vue'
import AppFooter from '@/components/layout/AppFooter.vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// ==================== 数据 ====================
const product = ref<ProductDetail | null>(null)
const loading = ref(true)

const activeImageIndex = ref(0)
const selectedSku = ref<ProductSku | null>(null)
const quantity = ref(1)
const addingToCart = ref(false)

// ==================== 计算 ====================
const allImages = computed(() => {
  if (!product.value) return []
  const imgs: string[] = []
  if (product.value.mainImage) imgs.push(product.value.mainImage)
  if (product.value.subImages?.length) imgs.push(...product.value.subImages)
  return imgs
})

const currentImage = computed(() => {
  return allImages.value[activeImageIndex.value] || ''
})

const priceLabel = computed(() => {
  if (selectedSku.value) {
    return `¥${Number(selectedSku.value.price).toFixed(2)}`
  }
  if (!product.value) return ''
  const min = Number(product.value.minPrice)
  if (min > 0) return `¥${min.toFixed(2)} 起`
  return ''
})

const originPriceLabel = computed(() => {
  if (selectedSku.value && product.value?.originPrice) {
    const op = Number(product.value.originPrice)
    const sp = Number(selectedSku.value.price)
    if (op > sp) return `¥${op.toFixed(2)}`
  }
  return ''
})

const canAddToCart = computed(() => {
  return selectedSku.value !== null && quantity.value > 0
})

// ==================== 方法 ====================
function selectSku(sku: ProductSku) {
  selectedSku.value = sku
  // 如果 SKU 有独立图片，切换主图
  if (sku.image && allImages.value.includes(sku.image)) {
    activeImageIndex.value = allImages.value.indexOf(sku.image)
  }
}

function increaseQty() {
  const max = selectedSku.value?.stock ?? 1
  if (quantity.value < max) {
    quantity.value++
  }
}

function decreaseQty() {
  if (quantity.value > 1) {
    quantity.value--
  }
}

async function handleAddToCart() {
  if (!canAddToCart.value || !product.value || !selectedSku.value) return

  // 需要登录
  if (!userStore.isLoggedIn) {
    router.push(`/login?redirect=${encodeURIComponent(route.fullPath)}`)
    return
  }

  addingToCart.value = true
  try {
    await addToCartApi({
      productId: product.value.id,
      skuId: selectedSku.value.id,
      quantity: quantity.value
    })
    ElMessage.success('已添加到购物车')
  } catch {
    /* 拦截器已提示 */
  } finally {
    addingToCart.value = false
  }
}

// ==================== 加载 ====================
onMounted(async () => {
  const id = Number(route.params.id)
  if (!id || Number.isNaN(id)) {
    router.replace('/404')
    return
  }
  try {
    product.value = await getProductDetailApi(id)
    document.title = product.value?.name ? `${product.value.name} - 零食商城` : '商品详情'
    // 默认选中第一个 SKU
    if (product.value?.skuList?.length) {
      selectedSku.value = product.value.skuList[0]
    }
  } catch {
    ElMessage.error('商品不存在或已下架')
  } finally {
    loading.value = false
  }
})
</script>

<template>
  <div class="detail-page">
    <AppHeader />

    <main class="detail-main">
      <div class="container">
        <!-- 加载骨架 -->
        <el-skeleton :loading="loading" animated :count="1">
          <template #template>
            <div class="detail-skeleton">
              <div class="skeleton-gallery">
                <div class="skeleton-main" />
                <div class="skeleton-thumbs">
                  <div v-for="i in 4" :key="i" class="skeleton-thumb" />
                </div>
              </div>
              <div class="skeleton-info">
                <div class="skeleton-line skeleton-title" />
                <div class="skeleton-line skeleton-brand" />
                <div class="skeleton-line skeleton-price" />
                <div class="skeleton-line" />
                <div class="skeleton-line skeleton-btn" />
              </div>
            </div>
          </template>

          <!-- 实际内容 -->
          <template v-if="product" #default>
            <div class="detail-layout">
              <!-- ====== 左侧：图片画廊 ====== -->
              <div class="detail-gallery">
                <div class="gallery-main">
                  <el-image
                    :src="currentImage"
                    fit="cover"
                    class="main-image"
                  >
                    <template #error>
                      <div class="image-placeholder">🍪</div>
                    </template>
                  </el-image>
                </div>
                <div v-if="allImages.length > 1" class="gallery-thumbs">
                  <div
                    v-for="(img, idx) in allImages"
                    :key="idx"
                    class="thumb-item"
                    :class="{ active: idx === activeImageIndex }"
                    @click="activeImageIndex = idx"
                  >
                    <el-image :src="img" fit="cover" class="thumb-image">
                      <template #error>
                        <span class="thumb-placeholder">🍪</span>
                      </template>
                    </el-image>
                  </div>
                </div>
              </div>

              <!-- ====== 右侧：商品信息 ====== -->
              <div class="detail-info">
                <!-- 标题 -->
                <h1 class="product-name">{{ product.name }}</h1>
                <p v-if="product.brand" class="product-brand">{{ product.brand }}</p>

                <!-- 基础数据 -->
                <div class="product-meta">
                  <span>销量 {{ product.sales }}</span>
                  <span class="meta-divider">|</span>
                  <span>{{ product.viewCount }} 次浏览</span>
                  <span class="meta-divider">|</span>
                  <span>分类：{{ product.categoryName }}</span>
                </div>

                <!-- 价格区 -->
                <div class="price-box">
                  <span class="current-price">{{ priceLabel }}</span>
                  <span v-if="originPriceLabel" class="origin-price">{{ originPriceLabel }}</span>
                  <span v-if="selectedSku" class="price-tip">
                    <template v-if="selectedSku.stock <= 10 && selectedSku.stock > 0">
                      仅剩 {{ selectedSku.stock }} 件
                    </template>
                    <template v-else-if="selectedSku.stock === 0">
                      暂时缺货
                    </template>
                  </span>
                </div>

                <!-- SKU 选择 -->
                <div class="sku-section">
                  <div class="sku-label">规格</div>
                  <div class="sku-list">
                    <span
                      v-for="sku in product.skuList"
                      :key="sku.id"
                      class="sku-item"
                      :class="{
                        active: selectedSku?.id === sku.id,
                        disabled: sku.stock <= 0
                      }"
                      @click="sku.stock > 0 && selectSku(sku)"
                    >
                      {{ sku.skuName }}
                    </span>
                  </div>
                </div>

                <!-- 已选 SKU 详情 -->
                <div v-if="selectedSku" class="sku-detail">
                  <span class="sku-detail-item">
                    价格：<strong>¥{{ Number(selectedSku.price).toFixed(2) }}</strong>
                  </span>
                  <span class="sku-detail-item">
                    库存：{{ selectedSku.stock }}
                  </span>
                  <span v-if="selectedSku.weight" class="sku-detail-item">
                    重量：{{ selectedSku.weight }}g
                  </span>
                </div>

                <!-- 数量选择 -->
                <div class="qty-section">
                  <span class="qty-label">数量</span>
                  <div class="qty-control">
                    <button class="qty-btn" :disabled="quantity <= 1" @click="decreaseQty">
                      <el-icon><Minus /></el-icon>
                    </button>
                    <input
                      v-model.number="quantity"
                      type="number"
                      class="qty-input"
                      :min="1"
                      :max="selectedSku?.stock ?? 1"
                    />
                    <button
                      class="qty-btn"
                      :disabled="quantity >= (selectedSku?.stock ?? 1)"
                      @click="increaseQty"
                    >
                      <el-icon><Plus /></el-icon>
                    </button>
                  </div>
                </div>

                <!-- 操作按钮 -->
                <div class="action-section">
                  <el-button
                    type="primary"
                    size="large"
                    :icon="ShoppingCart"
                    :loading="addingToCart"
                    :disabled="!canAddToCart"
                    class="add-cart-btn"
                    @click="handleAddToCart"
                  >
                    加入购物车
                  </el-button>
                </div>
              </div>
            </div>

            <!-- ====== 底部：商品详情（富文本） ====== -->
            <div class="detail-bottom">
              <div class="detail-tabs">
                <h2 class="tab-title active">商品详情</h2>
              </div>
              <div v-if="product.detail" class="detail-content" v-html="product.detail" />
              <div v-else class="detail-empty">
                <p>暂无详细描述</p>
              </div>
            </div>
          </template>

          <!-- 商品不存在（loading 结束后且 product 为 null） -->
          <template v-if="!loading && !product">
            <div class="detail-error">
              <div class="error-icon">😢</div>
              <h2>商品不存在或已下架</h2>
              <el-button type="primary" round @click="router.push('/')">返回首页</el-button>
            </div>
          </template>
        </el-skeleton>
      </div>
    </main>

    <AppFooter />
  </div>
</template>

<style lang="scss" scoped>
.detail-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: $bg-page;
}

.detail-main {
  flex: 1;
  padding-top: 24px;
}

.container {
  max-width: $container-max;
  margin: 0 auto;
  padding: 0 24px;
}

// ==================== 骨架屏 ====================
.detail-skeleton {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 40px;
}

.skeleton-gallery {
  .skeleton-main {
    width: 100%;
    aspect-ratio: 1 / 1;
    background: $bg-hover;
    border-radius: $radius-md;
  }
  .skeleton-thumbs {
    display: flex;
    gap: 10px;
    margin-top: 12px;
  }
  .skeleton-thumb {
    width: 72px;
    height: 72px;
    background: $bg-hover;
    border-radius: $radius-sm;
  }
}

.skeleton-info {
  display: flex;
  flex-direction: column;
  gap: 16px;

  .skeleton-line {
    height: 20px;
    background: $bg-hover;
    border-radius: 6px;
  }
  .skeleton-title {
    height: 32px;
    width: 80%;
  }
  .skeleton-brand {
    height: 18px;
    width: 40%;
  }
  .skeleton-price {
    height: 40px;
    width: 50%;
  }
  .skeleton-btn {
    height: 52px;
    width: 60%;
    margin-top: 20px;
    border-radius: $radius-full;
  }
}

// ==================== 双栏布局 ====================
.detail-layout {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 48px;
}

// ==================== 图片画廊 ====================
.detail-gallery {
  .gallery-main {
    border-radius: $radius-lg;
    overflow: hidden;
    background: $bg-surface;
    border: 2px solid $color-border;
    box-shadow: $clay-shadow-sm;
    aspect-ratio: 1 / 1;

    .main-image {
      width: 100%;
      height: 100%;
    }
  }

  .image-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 80px;
    background: $bg-page;
  }
}

.gallery-thumbs {
  display: flex;
  gap: 10px;
  margin-top: 12px;

  .thumb-item {
    width: 72px;
    height: 72px;
    border: 2px solid $color-border;
    border-radius: $radius-sm;
    overflow: hidden;
    cursor: pointer;
    transition: border-color 0.2s, box-shadow 0.2s;

    &.active {
      border-color: $color-primary;
      box-shadow: $clay-shadow-focus;
    }

    &:hover {
      border-color: $color-primary;
    }
  }

  .thumb-image {
    width: 100%;
    height: 100%;
  }

  .thumb-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28px;
    background: $bg-page;
  }
}

// ==================== 商品信息 ====================
.product-name {
  margin: 0 0 8px;
  font-size: $font-size-display;
  font-weight: 700;
  color: $color-text-primary;
  line-height: 1.3;
}

.product-brand {
  margin: 0 0 12px;
  font-size: $font-size-md;
  color: $color-primary;
  font-weight: 500;
}

.product-meta {
  font-size: $font-size-xs;
  color: $color-text-secondary;
  margin-bottom: 20px;
  display: flex;
  gap: 8px;
  align-items: center;

  .meta-divider {
    color: $color-border-dark;
  }
}

// 价格区
.price-box {
  background: linear-gradient(135deg, $color-primary-light, #FFF0EA);
  border: 2px solid $color-border;
  border-radius: $radius-md;
  padding: 20px 24px;
  margin-bottom: 28px;
  display: flex;
  align-items: baseline;
  gap: 12px;
  flex-wrap: wrap;
}

.current-price {
  font-family: 'Fredoka', sans-serif;
  font-size: 32px;
  font-weight: 700;
  color: $color-primary;
}

.origin-price {
  font-size: $font-size-lg;
  color: $color-text-placeholder;
  text-decoration: line-through;
}

.price-tip {
  font-size: $font-size-sm;
  color: $color-primary-dark;
  font-weight: 500;
}

// SKU 选择
.sku-section {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  margin-bottom: 16px;
}

.sku-label {
  width: 48px;
  flex-shrink: 0;
  font-size: $font-size-sm;
  color: $color-text-secondary;
  line-height: 36px;
}

.sku-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.sku-item {
  padding: 8px 20px;
  border: 2px solid $color-border;
  border-radius: $radius-full;
  font-size: $font-size-sm;
  color: $color-text-regular;
  cursor: pointer;
  transition: all 0.2s;
  min-height: 36px;
  display: flex;
  align-items: center;

  &:hover:not(.disabled) {
    border-color: $color-primary;
    color: $color-primary;
  }

  &.active {
    border-color: $color-primary;
    background: $color-primary-light;
    color: $color-primary;
    font-weight: 600;
    box-shadow: $clay-shadow-focus;
  }

  &.disabled {
    opacity: 0.4;
    cursor: not-allowed;
    text-decoration: line-through;
  }
}

// 已选 SKU 详情
.sku-detail {
  display: flex;
  gap: 20px;
  margin-bottom: 24px;
  font-size: $font-size-sm;
  color: $color-text-secondary;

  strong {
    color: $color-text-primary;
  }
}

// 数量选择
.qty-section {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 28px;
}

.qty-label {
  width: 48px;
  flex-shrink: 0;
  font-size: $font-size-sm;
  color: $color-text-secondary;
}

.qty-control {
  display: flex;
  align-items: center;
  border: 2px solid $color-border;
  border-radius: $radius-full;
  overflow: hidden;
  background: $bg-surface;
}

.qty-btn {
  width: 40px;
  height: 40px;
  border: none;
  background: transparent;
  color: $color-text-regular;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: color 0.2s, background-color 0.2s;

  &:hover:not(:disabled) {
    color: $color-primary;
    background-color: $color-primary-light;
  }

  &:disabled {
    opacity: 0.3;
    cursor: not-allowed;
  }
}

.qty-input {
  width: 64px;
  height: 40px;
  border: none;
  border-left: 2px solid $color-border;
  border-right: 2px solid $color-border;
  text-align: center;
  font-size: $font-size-md;
  font-weight: 600;
  color: $color-text-primary;
  -moz-appearance: textfield;

  &::-webkit-outer-spin-button,
  &::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }
}

// 操作按钮
.action-section {
  display: flex;
  gap: 16px;
}

.add-cart-btn {
  min-width: 200px;
  height: 52px;
  font-size: $font-size-lg;
  font-weight: 600;
  border-radius: $radius-full;
  border: 2px solid $color-border-dark;
  background: linear-gradient(135deg, $color-primary, $color-cta);
  box-shadow: 0 4px 0 0 $color-primary-dark;
  transition: transform 0.2s, box-shadow 0.2s, filter 0.2s;

  &:hover:not(:disabled) {
    filter: brightness(1.04);
    transform: translateY(-1px);
  }

  &:active:not(:disabled) {
    box-shadow: 0 1px 0 0 $color-primary-dark;
    transform: translateY(3px);
  }

  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
}

// ==================== 底部详情 ====================
.detail-bottom {
  margin-top: 56px;
  background: $bg-surface;
  border: 2px solid $color-border;
  border-radius: $radius-lg;
  box-shadow: $clay-shadow-sm;
  overflow: hidden;
}

.detail-tabs {
  border-bottom: 2px solid $color-border;
  padding: 0 24px;

  .tab-title {
    display: inline-block;
    margin: 0;
    padding: 18px 24px;
    font-size: $font-size-xl;
    font-weight: 600;
    color: $color-primary;
    border-bottom: 3px solid $color-primary;
  }
}

.detail-content {
  padding: 32px 24px;

  :deep(img) {
    max-width: 100%;
    height: auto;
    border-radius: $radius-sm;
  }

  :deep(table) {
    width: 100%;
    border-collapse: collapse;
    margin: 16px 0;

    td, th {
      border: 1px solid $color-border;
      padding: 8px 12px;
      font-size: $font-size-sm;
    }
  }
}

.detail-empty {
  padding: 48px;
  text-align: center;
  color: $color-text-secondary;
}

// ==================== 错误 ====================
.detail-error {
  text-align: center;
  padding: 80px 20px;

  .error-icon {
    font-size: 64px;
    margin-bottom: 16px;
  }
  h2 {
    margin: 0 0 24px;
    color: $color-text-primary;
  }
}

// ==================== 响应式 ====================
@media (max-width: 900px) {
  .detail-layout {
    grid-template-columns: 1fr;
    gap: 24px;
  }

  .detail-skeleton {
    grid-template-columns: 1fr;
  }

  .product-name {
    font-size: $font-size-xxl;
  }

  .current-price {
    font-size: 26px;
  }
}
</style>
