'use client' import { useState, useEffect } from 'react' import Link from 'next/link' import { Check, Plus, Package, ShoppingCart, Cpu, HardDrive, MemoryStick, Zap, Monitor, Box, Search, X } from 'lucide-react' interface ComponentType { id: string name: string description?: string } interface Component { id: string name: string brand: string price: number imageUrl?: string componentType: ComponentType } interface BuildConfiguration { [key: string]: Component | null } const componentIcons: { [key: string]: any } = { 'CPU': Cpu, '内存': MemoryStick, '硬盘': HardDrive, '主板': Zap, '显卡': Monitor, '机箱': Box, } export default function BuildPage() { const [componentTypes, setComponentTypes] = useState([]) const [availableComponents, setAvailableComponents] = useState<{ [key: string]: Component[] }>({}) const [buildConfig, setBuildConfig] = useState({}) const [isLoading, setIsLoading] = useState(true) const [selectedType, setSelectedType] = useState(null) const [searchTerm, setSearchTerm] = useState('') useEffect(() => { loadData() }, []) const loadData = async () => { try { // 加载配件类型 const typesResponse = await fetch('/api/component-types') if (typesResponse.ok) { const types = await typesResponse.json() setComponentTypes(types) // 为每种类型加载组件 const componentsData: { [key: string]: Component[] } = {} for (const type of types) { const componentsResponse = await fetch(`/api/components?type=${encodeURIComponent(type.id)}&limit=1000`) if (componentsResponse.ok) { const components = await componentsResponse.json() componentsData[type.name] = components.components || [] } } setAvailableComponents(componentsData) } } catch (error) { console.error('加载数据失败:', error) } finally { setIsLoading(false) } } const selectComponent = (typeName: string, component: Component) => { setBuildConfig(prev => ({ ...prev, [typeName]: component })) setSelectedType(null) setSearchTerm('') } const removeComponent = (typeName: string) => { setBuildConfig(prev => ({ ...prev, [typeName]: null })) } const getTotalPrice = () => { return Object.values(buildConfig).reduce((total, component) => { return total + (component?.price || 0) }, 0) } const getCompletionRate = () => { const totalTypes = componentTypes.length const selectedTypes = Object.values(buildConfig).filter(Boolean).length return totalTypes > 0 ? Math.round((selectedTypes / totalTypes) * 100) : 0 } const addAllToCart = async () => { const selectedComponents = Object.values(buildConfig).filter(Boolean) if (selectedComponents.length === 0) { alert('请先选择配件') return } const token = localStorage.getItem('token') if (!token) { alert('请先登录') return } try { // 批量添加到购物车 for (const component of selectedComponents) { await fetch('/api/cart', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify({ componentId: component!.id, quantity: 1 }) }) } window.dispatchEvent(new Event('cart-updated')) alert('配置已添加到购物车!') } catch (error) { console.error('添加到购物车失败:', error) alert('添加失败,请重试') } } const createOrder = async () => { const selectedComponents = Object.values(buildConfig).filter(Boolean) if (selectedComponents.length !== componentTypes.length) { alert('请完成所有配件的选择后再下单') return } try { const user = JSON.parse(localStorage.getItem('user') || 'null') if (!user) { alert('请先登录') window.location.href = '/login' return } const orderItems = selectedComponents.map(component => ({ componentId: component!.id, quantity: 1, price: 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) { alert('订单创建成功!') setBuildConfig({}) window.location.href = '/orders' } else { alert('订单创建失败,请重试') } } catch (error) { console.error('创建订单失败:', error) alert('订单创建失败,请重试') } } const getFilteredComponents = (typeName: string) => { console.log(availableComponents,typeName); const components = availableComponents[typeName] || [] if (!searchTerm) return components return components.filter(component => component.name.toLowerCase().includes(searchTerm.toLowerCase()) || component.brand.toLowerCase().includes(searchTerm.toLowerCase()) ) } if (isLoading) { return (

加载中...

) } return (
{/* Header */}

PC装机配置

选择每种配件,组装您的专属电脑

{/* Progress */}
配置进度 {getCompletionRate()}%
{/* Components Selection */}
{componentTypes.map((type) => { const Icon = componentIcons[type.name] || Package const selectedComponent = buildConfig[type.name] return (

{type.name}

{type.description}

{selectedComponent && ( )}
{selectedComponent ? (
{selectedComponent.imageUrl ? ( {selectedComponent.name} ) : ( )}

{selectedComponent.name}

{selectedComponent.brand}

¥{selectedComponent.price}

) : ( )}
) })}
{/* Summary */}

配置总览

{componentTypes.map((type) => { const component = buildConfig[type.name] return (
{type.name}: {component ? `¥${component.price}` : '未选择'}
) })}
总价: ¥{getTotalPrice().toFixed(2)}

完成度: {getCompletionRate()}% ({Object.values(buildConfig).filter(Boolean).length}/{componentTypes.length})

{/* Component Selection Modal */} {selectedType && (

选择 {selectedType}

{/* Search Box */}
setSearchTerm(e.target.value)} className="block w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg leading-5 bg-white placeholder-gray-500 focus:outline-none focus:placeholder-gray-400 focus:ring-1 focus:ring-blue-500 focus:border-blue-500 transition-colors" /> {searchTerm && ( )}
{/* Results count */}
找到 {getFilteredComponents(selectedType).length} 个配件 {searchTerm && ` (搜索: "${searchTerm}")`}
{getFilteredComponents(selectedType).length > 0 ? (
{getFilteredComponents(selectedType).map((component) => (
selectComponent(selectedType, component)} >
{component.imageUrl ? ( {component.name} ) : ( )}

{component.name}

{component.brand}

¥{component.price}

))}
) : (

{searchTerm ? '没有找到匹配的配件' : '暂无配件'}

{searchTerm ? '尝试调整搜索关键词' : '此类型暂无可用配件'}

{searchTerm && ( )}
)}
)}
) }