'use client' import { useState, useEffect } from 'react' import Link from 'next/link' import { Package, Calendar, DollarSign, Eye, Filter } from 'lucide-react' interface OrderItem { id: string quantity: number price: number component: { id: string name: string brand: string imageUrl?: string componentType: { name: string } } } interface Order { id: string orderNumber: string totalAmount: number status: string createdAt: string orderItems: OrderItem[] } const statusMap: { [key: string]: { text: string; color: string } } = { PENDING: { text: '待确认', color: 'bg-yellow-100 text-yellow-800' }, CONFIRMED: { text: '已确认', color: 'bg-blue-100 text-blue-800' }, PROCESSING: { text: '处理中', color: 'bg-purple-100 text-purple-800' }, SHIPPED: { text: '已发货', color: 'bg-green-100 text-green-800' }, DELIVERED: { text: '已送达', color: 'bg-green-100 text-green-800' }, CANCELLED: { text: '已取消', color: 'bg-red-100 text-red-800' }, } export default function OrdersPage() { const [orders, setOrders] = useState([]) const [isLoading, setIsLoading] = useState(true) const [selectedStatus, setSelectedStatus] = useState('ALL') const [cancellingOrderId, setCancellingOrderId] = useState(null) useEffect(() => { loadOrders() }, []) const loadOrders = async () => { try { const token = localStorage.getItem('token') if (!token) { window.location.href = '/login' return } const response = await fetch('/api/orders', { headers: { 'Authorization': `Bearer ${token}` } }) if (response.ok) { const data = await response.json() setOrders(data) } else if (response.status === 401) { localStorage.removeItem('token') localStorage.removeItem('user') window.location.href = '/login' } } catch (error) { console.error('加载订单失败:', error) } finally { setIsLoading(false) } } const filteredOrders = selectedStatus === 'ALL' ? orders : orders.filter(order => order.status === selectedStatus) const handleCancelOrder = async (orderId: string) => { if (!confirm('确定要取消这个订单吗?取消后将恢复商品库存。')) { return } setCancellingOrderId(orderId) try { const token = localStorage.getItem('token') const response = await fetch(`/api/orders/${orderId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify({ action: 'cancel' }) }) if (response.ok) { // 重新加载订单列表 await loadOrders() alert('订单已成功取消') } else { const error = await response.json() alert(error.message || '取消订单失败') } } catch (error) { console.error('取消订单失败:', error) alert('取消订单失败,请重试') } finally { setCancellingOrderId(null) } } const handleReorder = async (order: Order) => { const token = localStorage.getItem('token') if (!token) { alert('请先登录') return } try { // 批量添加订单商品到购物车 for (const item of order.orderItems) { await fetch('/api/cart', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify({ componentId: item.component.id, quantity: item.quantity }) }) } window.dispatchEvent(new Event('cart-updated')) alert('商品已添加到购物车!') window.location.href = '/cart' } catch (error) { console.error('添加到购物车失败:', error) alert('添加失败,请重试') } } if (isLoading) { return (

加载中...

) } return (
{/* Header */}

我的订单

继续购物
{/* Status Filter */}
筛选:
{Object.entries(statusMap).map(([status, config]) => ( ))}
{/* Orders List */} {filteredOrders.length === 0 ? (

{selectedStatus === 'ALL' ? '暂无订单' : '暂无该状态的订单'}

{selectedStatus === 'ALL' ? '还没有任何订单,去看看有什么好东西吧!' : '可以试试其他状态筛选' }

去购物
) : (
{filteredOrders.map((order) => (
{/* Order Header */}

订单号

{order.orderNumber}

下单时间

{new Date(order.createdAt).toLocaleString('zh-CN')}

订单状态

{statusMap[order.status]?.text || order.status}

订单金额

¥{order.totalAmount.toFixed(2)}

{/* Order Items */}
{order.orderItems.map((item) => (
{item.component?.imageUrl ? ( {item.component?.name ) : ( )}

{item.component?.name || '未知商品'}

{item.component?.brand || '未知品牌'} | {item.component?.componentType?.name || '未知类型'}

数量: {item.quantity}

¥{item.price}

小计: ¥{(item.price * item.quantity).toFixed(2)}

))}
{/* Order Actions */}
共 {order.orderItems.length} 件商品 实付款: ¥{order.totalAmount}
查看详情 {order.status === 'PENDING' && ( )} {order.status === 'DELIVERED' && ( )}
))}
)}
) }