'use client' import { useState } from 'react' import { ShoppingCart, Plus, Minus } from 'lucide-react' interface AddToCartButtonProps { componentId: string disabled?: boolean className?: string } export function AddToCartButton({ componentId, disabled = false, className = '' }: AddToCartButtonProps) { const [quantity, setQuantity] = useState(1) const [isLoading, setIsLoading] = useState(false) const handleAddToCart = async () => { const token = localStorage.getItem('token') if (!token) { alert('请先登录') return } setIsLoading(true) try { const response = await fetch('/api/cart', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify({ componentId, quantity }) }) if (response.ok) { // 触发购物车更新事件 window.dispatchEvent(new Event('cart-updated')) alert('已添加到购物车!') } else if (response.status === 401) { localStorage.removeItem('token') localStorage.removeItem('user') alert('登录已过期,请重新登录') window.location.href = '/login' } else { const data = await response.json() alert(data.message || '添加失败') } } catch (error) { console.error('添加到购物车失败:', error) alert('添加失败,请重试') } finally { setIsLoading(false) } } return (
{/* Quantity Selector */}
数量:
{quantity}
{/* Add to Cart Button */}
) }