'use client' import { useState, useEffect } from 'react' import Link from 'next/link' import { Trash2, Plus, Minus, ShoppingBag, ArrowLeft } from 'lucide-react' interface CartItem { id: string quantity: number component: { id: string name: string brand: string price: number imageUrl?: string | null stock: number componentType: { name: string } } } export default function CartPage() { const [cartItems, setCartItems] = useState([]) const [isLoading, setIsLoading] = useState(true) const [isUpdating, setIsUpdating] = useState(null) useEffect(() => { loadCartItems() }, []) const loadCartItems = async () => { try { const token = localStorage.getItem('token') if (!token) { setIsLoading(false) return } const response = await fetch('/api/cart', { headers: { 'Authorization': `Bearer ${token}` } }) if (response.ok) { const items = await response.json() setCartItems(items) } else if (response.status === 401) { // 登录过期,清除token localStorage.removeItem('token') localStorage.removeItem('user') window.location.href = '/login' } } catch (error) { console.error('加载购物车失败:', error) } finally { setIsLoading(false) } } const updateQuantity = async (cartItemId: string, newQuantity: number) => { if (newQuantity < 1) return setIsUpdating(cartItemId) try { const token = localStorage.getItem('token') const response = await fetch(`/api/cart/${cartItemId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify({ quantity: newQuantity }) }) if (response.ok) { // 重新加载购物车 await loadCartItems() } else { const data = await response.json() alert(data.message || '更新失败') } } catch (error) { console.error('更新数量失败:', error) alert('更新失败') } finally { setIsUpdating(null) } } const removeFromCart = async (cartItemId: string) => { if (!confirm('确定要从购物车中移除这个商品吗?')) return setIsUpdating(cartItemId) try { const token = localStorage.getItem('token') const response = await fetch(`/api/cart/${cartItemId}`, { method: 'DELETE', headers: { 'Authorization': `Bearer ${token}` } }) if (response.ok) { // 重新加载购物车 await loadCartItems() } else { const data = await response.json() alert(data.message || '删除失败') } } catch (error) { console.error('删除失败:', error) alert('删除失败') } finally { setIsUpdating(null) } } const clearCart = async () => { if (!confirm('确定要清空购物车吗?')) return try { const token = localStorage.getItem('token') const response = await fetch('/api/cart', { method: 'DELETE', headers: { 'Authorization': `Bearer ${token}` } }) if (response.ok) { setCartItems([]) } else { const data = await response.json() alert(data.message || '清空失败') } } catch (error) { console.error('清空购物车失败:', error) alert('清空失败') } } const getTotalPrice = () => { return cartItems.reduce((total, item) => { return total + (item.component.price * item.quantity) }, 0) } const getTotalItems = () => { return cartItems.reduce((total, item) => total + item.quantity, 0) } const createOrder = async () => { if (cartItems.length === 0) { alert('购物车为空') return } try { const user = JSON.parse(localStorage.getItem('user') || 'null') if (!user) { alert('请先登录') window.location.href = '/login' return } const orderItems = cartItems.map(item => ({ componentId: item.component.id, quantity: item.quantity, price: item.component.price })) const response = await fetch('/api/orders', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('token')}` }, body: JSON.stringify({ items: orderItems, totalAmount: getTotalPrice() }) }) if (response.ok) { // 清空购物车 await clearCart() alert('订单创建成功!') window.location.href = '/orders' } else { const data = await response.json() alert(data.message || '订单创建失败') } } catch (error) { console.error('创建订单失败:', error) alert('订单创建失败,请重试') } } if (isLoading) { return (

加载中...

) } const user = JSON.parse(localStorage.getItem('user') || 'null') if (!user) { return (

请先登录

登录后即可查看您的购物车

立即登录
) } return (
{/* Header */}
继续购物

购物车

{cartItems.length > 0 && ( )}
{cartItems.length === 0 ? (

购物车为空

还没有添加任何商品到购物车

开始购物
) : (
{/* Cart Items */}

商品列表 ({getTotalItems()} 件商品)

{cartItems.map((item) => (
{item.component.imageUrl ? ( {item.component.name} ) : (
)}

{item.component.name}

{item.component.brand}

{item.component.componentType.name}

¥{item.component.price}

库存: {item.component.stock}

{item.quantity}

¥{(item.component.price * item.quantity).toFixed(2)}

))}
{/* Order Summary */}

订单摘要

商品总数: {getTotalItems()} 件
商品总价: ¥{getTotalPrice().toFixed(2)}
总计: ¥{getTotalPrice().toFixed(2)}

点击结算将创建订单并清空购物车

)}
) }