<template>
  <view class="favorites-page">
    <view class="product-grid">
      <view v-if="favorites.length === 0" class="empty-state">
        <text class="empty-icon">❤️</text>
        <text class="empty-text">暂无收藏商品</text>
        <button class="go-shopping-btn" @click="goShopping">去逛逛</button>
      </view>
      
      <view v-else v-for="(product, index) in favorites" :key="index" class="product-item" @click="goToDetail(product.id)">
        <image :src="product.image" class="product-image" mode="aspectFill" />
        <view class="product-info">
          <text class="product-name">{{ product.name }}</text>
          <text class="product-price">¥{{ product.price }}</text>
          <view class="product-footer">
            <text class="product-sales">已售 {{ product.sales }}</text>
            <view class="action-btns">
              <view class="cart-btn" @click.stop="addToCart(product)">
                <text class="cart-icon">🛒</text>
              </view>
              <view class="remove-btn" @click.stop="removeFavorite(product.id)">
                <text class="remove-icon">🗑️</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="uts">
import { ref, onMounted } from 'vue'

type Product = {
  id: string
  name: string
  price: number
  image: string
  sales: number
  shopId?: string
  shopName?: string
}

const favorites = ref<Product[]>([])

onMounted(() => {
  loadFavorites()
})

const addToCart = (product: Product) => {
  // 获取现有购物车数据
  const cartData = uni.getStorageSync('cart')
  let cartItems: any[] = []
  
  if (cartData) {
    try {
      cartItems = JSON.parse(cartData as string) as any[]
    } catch (e) {
      console.error('解析购物车数据失败', e)
    }
  }
  
  // 检查商品是否已存在
  const existingItem = cartItems.find((item: any) => item.id === product.id)
  
  if (existingItem) {
    existingItem.quantity++
  } else {
    // 添加新商品
    cartItems.push({
      id: product.id,
      shopId: product.shopId || 'shop_favorite_default',
      shopName: product.shopName || '收藏店铺',
      name: product.name,
      price: product.price,
      image: product.image,
      spec: '默认规格',
      quantity: 1,
      selected: true
    })
  }
  
  // 保存回存储
  uni.setStorageSync('cart', JSON.stringify(cartItems))
  
  uni.showToast({
    title: '已添加到购物车',
    icon: 'success'
  })
}

const loadFavorites = () => {
  // 从本地存储获取收藏列表
  const storedFavorites = uni.getStorageSync('favorites')
  if (storedFavorites) {
    try {
      favorites.value = JSON.parse(storedFavorites as string) as Product[]
    } catch (e) {
      console.error('Failed to parse favorites', e)
      favorites.value = []
    }
  } else {
    favorites.value = []
  }
}

const goShopping = () => {
  uni.switchTab({
    url: '/pages/mall/consumer/index'
  })
}

const goToDetail = (product: Product) => {
  uni.navigateTo({
    url: `/pages/mall/consumer/product-detail?productId=${product.id}&price=${product.price}&originalPrice=${product.original_price || ''}`
  })
}

const removeFavorite = (id: string) => {
  uni.showModal({
    title: '取消收藏',
    content: '确定要取消收藏该商品吗？',
    success: (res) => {
      if (res.confirm) {
        const index = favorites.value.findIndex(item => item.id === id)
        if (index !== -1) {
          favorites.value.splice(index, 1)
          uni.setStorageSync('favorites', JSON.stringify(favorites.value))
          uni.showToast({
            title: '已取消收藏',
            icon: 'none'
          })
        }
      }
    }
  })
}
</script>

<style>
.favorites-page {
  padding: 15px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.product-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.empty-state {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 100px;
}

.empty-icon {
  font-size: 60px;
  margin-bottom: 20px;
  color: #ddd;
}

.empty-text {
  font-size: 16px;
  color: #999;
  margin-bottom: 20px;
}

.go-shopping-btn {
  background-color: #ff5000;
  color: white;
  padding: 8px 24px;
  border-radius: 20px;
  font-size: 14px;
  border: none;
}

.product-item {
  width: calc(50% - 8px);
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.product-image {
  width: 100%;
  height: 170px;
  background-color: #f5f5f5;
}

.product-info {
  padding: 10px;
  display: flex;
  flex-direction: column;
  flex: 1;
}

.product-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 6px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 40px;
  line-height: 20px;
}

.product-price {
  font-size: 16px;
  color: #ff5000;
  font-weight: bold;
  margin-bottom: 6px;
}

.product-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.product-sales {
  font-size: 12px;
  color: #999;
}

.action-btns {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 8px;
}

.cart-btn, .remove-btn {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cart-btn {
  background-color: #ff5000;
}

.cart-icon {
  font-size: 14px;
  color: white;
}

.remove-btn {
  background-color: #f0f0f0;
}

.remove-icon {
  font-size: 14px;
}
</style>