<script setup lang="ts">
import type { Product } from '@/pinia/stores/product'
import { useCartStore } from "@/pinia/stores/cart"
import { storeToRefs } from "pinia"

// 状态管理
const cartStore = useCartStore()
const { cartItems, totalPrice, totalQuantity } = storeToRefs(cartStore) // 新增购物车状态

// 定义组件接收的属性
const { product } = defineProps<{ product: Product }>();

// 定义组件事件：关闭详情
const emit = defineEmits(["detailClose"])
// 购物车控制
const showAddCart = ref(false)
const quantity = ref(1)

const maxQuantity = computed(() => {
  const existingItem = cartItems.value.find(item => item.product.id === product.id)
  if (existingItem) {
    return product.stock !== -1 && existingItem.quantity + quantity.value >= product.stock
  } else {
    return product.stock !== -1 && quantity.value >= product.stock
  } 
})

// 处理关闭按钮点击事件
function handleClose() {
  emit("detailClose")
}
function handleAddToCart(): boolean {
  const existingItem = cartItems.value.find(item => item.product.id === product.id)
  if (product.stock !== -1 && existingItem && existingItem.quantity + quantity.value >= product.stock) {
    // TODO 提示库存不足
    return false;
  }
  quantity.value++
  return true;
}

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

function confirmAddCart() {
  cartStore.addToCart(product, quantity.value)
  // 重置参数
  quantity.value = 1
  showAddCart.value = false
  emit("detailClose")
}
function doShowAddCart(): boolean {
  const existingItem = cartItems.value.find(item => item.product.id === product.id)
    if (product.stock !== -1 && existingItem && existingItem.quantity >= product.stock) {
      // TODO 提示库存不足
      return false;
    }
  showAddCart.value = true;
  return true;
}
watch(() => product, () => {
  // 重置参数
  quantity.value = 1
  showAddCart.value = false
})
</script>

<template>
  <!-- 商品详情容器 -->
  <div class="detail-container">
    <!-- 顶部操作栏 -->
    <div class="header-bar">
      <van-icon name="cross" class="close-icon" @click="handleClose" />
    </div>

    <!-- 商品内容区域（可滚动） -->
    <div class="content-area">
      <!-- 商品主图 -->
      <van-image v-if="product" :src="product.image" class="product-image" fit="cover">
        <div v-if="product.stock === 0" class="sold-out-overlay">
          <span class="sold-out-text">已售罄</span>
        </div>
        <template #error>
          <div class="custom-error">
            图片加载失败
          </div>
        </template>
      </van-image>

      <!-- 商品信息改为列表样式 -->
      <div class="product-info">
        <div class="product-name van-ellipsis">
          {{ product.name }}
        </div>
        <div class="price-row">
          <span class="product-price">¥{{ product.price.toFixed(2) }}</span>
          <span v-if="product.stock > 0" class="stock-count">
            剩余{{ product.stock }}件
          </span>
        </div>
      </div>

      <!-- 商品描述分隔线 -->
      <van-divider style="margin: 5px;" />

      <!-- 商品详细描述 -->
      <div v-if="!showAddCart" class="description">
        {{ product.description }}
      </div>
      <div v-if="showAddCart" class="action-row">
        <div class="product-name van-ellipsis">
          购买数量
        </div>
        <div class="cart-actions">
          <van-button 
          size="mini" 
          icon="minus" 
          :disabled="quantity === 1"
          @click.stop="handleRemoveFromCart()" />
          <span class="cart-count">{{ quantity }}</span>
          <van-button 
          size="mini" 
          type="primary" 
          class="add-cart-btn" 
          icon="plus"
          :disabled="maxQuantity"
          @click.stop="handleAddToCart()"></van-button>
        </div>
      </div>
    </div>

    <!-- 底部操作按钮栏 -->
    <div class="action-bar">
      <van-button 
      v-if="!showAddCart"
      type="primary" 
      block 
      :disabled="product?.stock === 0" 
      class="add-cart-btn"
      @click="doShowAddCart()"
      >
        <!-- 根据库存显示不同按钮文字 -->
        {{ product?.stock === 0 ? '已售罄' : '加入购物车' }}
      </van-button>
      <van-button 
      v-if="showAddCart"
      type="primary" 
      block 
      class="add-cart-btn"
      @click="confirmAddCart()"
      >
        确认
      </van-button>
    </div>
  </div>
</template>

<style scoped>
.detail-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  /* 关键：容器占满视口高度 */
  background: #f7f8fa;
}

.product-image {
  width: 100%;
  height: 275px;
  display: block;
  background: #fff;
}

.price {
  color: #e95d5d;
  font-size: 18px;
  font-weight: bold;
}

.description {
  color: #646566;
  font-size: 14px;
  line-height: 1.6;
  padding: 6px 16px;
}

.action-bar {
  flex-shrink: 0;
  /* 禁止收缩 */
  position: sticky;
  bottom: 0;
  z-index: 10;
  background: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
}

.add-cart-btn {
  border-radius: 20px;
  background-color: #e95d5d;
  border-color: #e95d5d;
}

/* 复用列表页的售罄样式 */
.sold-out-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;

  .sold-out-text {
    color: #969799;
    font-size: 24px;
    font-weight: 500;
    padding: 8px 24px;
    background: rgba(0, 0, 0, 0.04);
    border-radius: 20px;
    transform: rotate(-15deg);
  }
}

.custom-error {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #969799;
  font-size: 16px;
  background: #f7f8fa;
}

.header-bar {
  flex-shrink: 0;
  /* 禁止收缩 */
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  justify-content: flex-end;
  /* 右对齐 */
  align-items: center;
  /* 垂直居中 */
  padding: 10px 16px;
  /* 增加适当间距 */
}

.close-icon {
  font-size: 18px;
  color: #969799;
}

.content-area {
  flex: 1;
  /* 关键：占据剩余空间 */
  overflow-y: auto;
  /* 内容超出时出现滚动条 */
  background-color: #fff;
}

.product-info {
  padding: 6px 16px;
  background: white;
}

.product-name {
  font-size: 16px;
  font-weight: 700;
  color: #333;
  line-height: 1.4;
  margin-bottom: 8px;
}

.price-row {
  display: flex;
  justify-content: start;
  align-items: center;
}

.product-price {
  font-size: 16px;
  color: #e95d5d;
  font-weight: bold;
}

.stock-count {
  font-size: 12px;
  color: #969799;
  margin-left: 8px;
}
.action-row {
  display: flex;
  justify-content: start;
  align-items: flex-end;
  /* 底部对齐 */
  margin-top: auto;
  /* 推到容器底部 */
  padding: 6px 16px;
  .product-name {
    margin: 10px 0;
  }
}
.cart-actions {
  margin-left: 10px;
  align-self: center;
  display: flex;
  align-items: center;
  gap: 4px;
  /* margin-left: 8px; */
  
  .cart-count {
    font-size: 12px;
    min-width: 20px;
    text-align: center;
  }
}
</style>
