'use client' import { useState, useEffect } from 'react' import Link from 'next/link' import { useRouter } from 'next/navigation' import { ArrowLeft, Package, Calendar, DollarSign, User, MapPin, Phone, Mail, Truck, CheckCircle, XCircle, Clock } from 'lucide-react' interface OrderItem { id: string quantity: number price: number component: { id: string name: string brand: string model: string imageUrl?: string componentType: { name: string } } } interface Order { id: string orderNumber: string totalAmount: number status: string createdAt: string updatedAt: string orderItems: OrderItem[] user: { username: string email: string } } const statusMap: { [key: string]: { text: string; color: string; icon: any } } = { PENDING: { text: '待确认', color: 'bg-yellow-100 text-yellow-800 border-yellow-200', icon: Clock }, CONFIRMED: { text: '已确认', color: 'bg-blue-100 text-blue-800 border-blue-200', icon: CheckCircle }, PROCESSING: { text: '处理中', color: 'bg-purple-100 text-purple-800 border-purple-200', icon: Package }, SHIPPED: { text: '已发货', color: 'bg-green-100 text-green-800 border-green-200', icon: Truck }, DELIVERED: { text: '已送达', color: 'bg-green-100 text-green-800 border-green-200', icon: CheckCircle }, CANCELLED: { text: '已取消', color: 'bg-red-100 text-red-800 border-red-200', icon: XCircle }, } export default function OrderDetailPage({ params }: { params: Promise<{ id: string }> }) { const [order, setOrder] = useState(null) const [isLoading, setIsLoading] = useState(true) const [isCancelling, setIsCancelling] = useState(false) const [orderId, setOrderId] = useState('') const router = useRouter() useEffect(() => { const getParams = async () => { const { id } = await params setOrderId(id) } getParams() }, [params]) useEffect(() => { if (orderId) { loadOrderDetail() } }, [orderId]) const loadOrderDetail = async () => { try { const token = localStorage.getItem('token') if (!token) { router.push('/login') return } const response = await fetch(`/api/orders/${(await params).id}`, { headers: { 'Authorization': `Bearer ${token}` } }) if (response.ok) { const data = await response.json() setOrder(data) } else if (response.status === 401) { localStorage.removeItem('token') localStorage.removeItem('user') router.push('/login') } else if (response.status === 404) { router.push('/orders') } } catch (error) { console.error('加载订单详情失败:', error) } finally { setIsLoading(false) } } const handleCancelOrder = async () => { if (!order || order.status !== 'PENDING') { alert('当前订单状态不允许取消') return } if (!confirm('确定要取消这个订单吗?取消后将恢复商品库存。')) { return } setIsCancelling(true) 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) { const updatedOrder = await response.json() setOrder(updatedOrder) alert('订单已成功取消') } else { const error = await response.json() alert(error.message || '取消订单失败') } } catch (error) { console.error('取消订单失败:', error) alert('取消订单失败,请重试') } finally { setIsCancelling(false) } } const handleReorder = async () => { if (!order) return 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('商品已添加到购物车!') router.push('/cart') } catch (error) { console.error('添加到购物车失败:', error) alert('添加失败,请重试') } } if (isLoading) { return (

加载中...

) } if (!order) { return (

订单不存在

返回订单列表
) } const statusConfig = statusMap[order.status] || { text: order.status, color: 'bg-gray-100 text-gray-800 border-gray-200', icon: Package } const StatusIcon = statusConfig.icon return (
{/* Header */}

订单详情

订单号: {order.orderNumber}

{/* Order Status */}

订单状态

{statusConfig.text}

下单时间

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

{order.updatedAt !== order.createdAt && ( <>

更新时间

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

)}
{/* Order Items */}

订单商品

{order.orderItems.map((item, index) => (
0 ? 'pt-6 border-t border-gray-200' : ''}`}>
{item.component?.imageUrl ? ( {item.component?.name ) : ( )}

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

品牌: {item.component?.brand || '未知品牌'}

型号: {item.component?.model || '未知型号'}

类型: {item.component?.componentType?.name || '未知类型'}

¥{item.price}

数量: {item.quantity}

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

))}
{/* Order Summary */}

订单汇总

商品数量: {order.orderItems.length} 件
商品总价: ¥{order.totalAmount}
运费: 免费
实付款: ¥{order.totalAmount}
{/* User Info */}

用户信息

用户名

{order.user.username}

邮箱

{order.user.email}

{/* Actions */}
订单创建于 {new Date(order.createdAt).toLocaleDateString('zh-CN')}
{order.status === 'PENDING' && ( )} {order.status === 'DELIVERED' && ( )} 返回订单列表
) }