'use client'; import { useState, useEffect } from 'react'; import { useRouter } from 'next/navigation'; import { ArrowLeft, Users, Building2, Globe, DollarSign, Clock, CheckCircle2, ShieldCheck, Smartphone, Banknote } from 'lucide-react'; import { productService, orderService, settlementService } from '@/lib/services'; import { getCurrentUser } from '@/lib/auth'; import ProductSearchSelector from '@/components/admin/orders/ProductSearchSelector'; import AiDataParserPanel from '@/components/admin/orders/AiDataParserPanel'; import DynamicOrderSchemaForm from '@/components/admin/orders/DynamicOrderSchemaForm'; import AdminUserSelect from '@/components/common/AdminUserSelect'; import { ImageUploadField } from '@/components/common/ImageUploadField'; import { SchemaProperty, VasAgency } from '@/types'; import { toast } from 'react-hot-toast'; import { SUPPORTED_CURRENCIES, getCurrencySymbol } from '@/lib/currency'; export default function AdminCreateOrderPage() { const router = useRouter(); const [loading, setLoading] = useState(false); // 1. 商品状态 const [selectedProduct, setSelectedProduct] = useState(null); // 2. 渠道与分润归属状态 const [channelType, setChannelType] = useState<'direct' | 'agency' | 'website'>('direct'); const [handlerId, setHandlerId] = useState(''); const [agencies, setAgencies] = useState([]); const [selectedAgencyId, setSelectedAgencyId] = useState(''); const [customPrice, setCustomPrice] = useState(''); // 单位: 元/欧/刀 const [currency, setCurrency] = useState('CNY'); // 结算币种代码 // 2.5 收款时机与收款登记状态 const [paymentTiming, setPaymentTiming] = useState<'pay_later' | 'paid_now'>('pay_later'); const [paymentMethod, setPaymentMethod] = useState('wechat'); const [externalTradeNo, setExternalTradeNo] = useState(''); const [voucherUrl, setVoucherUrl] = useState(''); const [paymentNote, setPaymentNote] = useState(''); // 3. 表单与 Schema 状态 const [formSchema, setFormSchema] = useState(null); const [formValues, setFormValues] = useState>({}); const [sortedFields, setSortedFields] = useState([]); // 加载中介列表与当前用户信息 useEffect(() => { const user = getCurrentUser(); if (user?.nickname || user?.id) { setHandlerId(user.nickname || user.id); } async function loadAgencies() { try { const res = await settlementService.listAgencies({ active_only: true }); const list = res?.data?.items || res?.data || []; setAgencies(Array.isArray(list) ? list : []); } catch { setAgencies([]); } } loadAgencies(); }, []); // 选中中介时自动锁定 handler_id const handleAgencySelect = (agencyId: string) => { setSelectedAgencyId(agencyId); const agency = agencies.find((a) => a.id === agencyId); if (agency) { setHandlerId(agency.owner_id); } }; const selectedAgency = agencies.find((a) => a.id === selectedAgencyId); // 加载商品默认价与 Schema useEffect(() => { if (!selectedProduct) { setFormSchema(null); setSortedFields([]); setFormValues({}); setCustomPrice(''); return; } // 默认价格与币种填充: 优先取 price_amount,兼顾 base_price const prodCurrency = (selectedProduct.price_currency || selectedProduct.currency || 'CNY').toUpperCase(); setCurrency(prodCurrency); if (selectedProduct.price_amount !== undefined) { setCustomPrice((selectedProduct.price_amount / 100).toFixed(2)); } else if (selectedProduct.base_price !== undefined) { setCustomPrice((selectedProduct.base_price / 100).toFixed(2)); } if (!selectedProduct.schema_id) { setFormSchema(null); setSortedFields([]); setFormValues({}); return; } async function loadSchema() { try { const res = await productService.getSchemaDetail(selectedProduct.schema_id); const data = res?.data || res; const schemaJson = typeof data?.schema_json === 'string' ? JSON.parse(data.schema_json) : data?.schema_json; setFormSchema(schemaJson); setFormValues({}); if (schemaJson?.properties) { const keys = Object.keys(schemaJson.properties); if (Array.isArray(schemaJson['ui:order'])) { setSortedFields(schemaJson['ui:order']); } else { const sorted = keys.sort((a, b) => { const propA = schemaJson.properties[a] as SchemaProperty; const propB = schemaJson.properties[b] as SchemaProperty; const orderA = propA['x-order'] ?? propA.order ?? 999; const orderB = propB['x-order'] ?? propB.order ?? 999; return orderA - orderB; }); setSortedFields(sorted); } } } catch { toast.error('表单定义加载失败'); } } loadSchema(); }, [selectedProduct]); // AI 解析结果回填 const handleAiFieldsParsed = (fields: Record) => { setFormValues((prev) => ({ ...prev, ...fields, })); }; // 单个字段修改 const handleInputChange = (key: string, value: any) => { setFormValues((prev) => ({ ...prev, [key]: value })); }; // 提交订单 const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!selectedProduct) return toast.error('请先搜索并选择商品'); // 价格校验 let finalAmountCents: number | undefined = undefined; if (customPrice && !isNaN(Number(customPrice))) { finalAmountCents = Math.round(Number(customPrice) * 100); } if (finalAmountCents === undefined || finalAmountCents <= 0) { return toast.error('请输入有效的金额 (必须大于 0)'); } if (channelType === 'agency') { if (!selectedAgencyId) { return toast.error('请选择合作中介机构'); } if (selectedAgency && finalAmountCents !== undefined && finalAmountCents < selectedAgency.min_floor_price) { const sym = getCurrencySymbol(currency); return toast.error( `录入价格 ${sym}${(finalAmountCents / 100).toFixed(2)} 低于该中介协议最低结算底价 ${sym}${(selectedAgency.min_floor_price / 100).toFixed(2)}!` ); } } if (channelType === 'direct' && !handlerId.trim()) { return toast.error('社交自收直客单必须填写40%提成归属人ID/姓名'); } setLoading(true); try { const payload = { product_id: selectedProduct.id, user_inputs: formValues, channel_type: channelType, agency_id: channelType === 'agency' ? selectedAgencyId : undefined, handler_id: channelType === 'website' ? undefined : handlerId.trim(), final_amount: finalAmountCents, currency: currency, payment_timing: paymentTiming, payment_method: paymentTiming === 'paid_now' ? paymentMethod : undefined, external_trade_no: paymentTiming === 'paid_now' ? (externalTradeNo.trim() || undefined) : undefined, voucher_url: paymentTiming === 'paid_now' ? (voucherUrl.trim() || undefined) : undefined, payment_note: paymentTiming === 'paid_now' ? (paymentNote.trim() || undefined) : undefined, }; const res = await orderService.createByAdmin(payload); const orderId = res?.data?.id || res?.id || res?.data?.order_id || res?.order_id; if (paymentTiming === 'pay_later') { toast.success(`代客下单成功!任务已入队调度 [待出签/收款] 订单号: ${orderId}`); } else { toast.success(`代下单并收款核销成功!订单号: ${orderId}`); } router.push('/admin/orders'); } catch (error: any) { console.error(error); toast.error('下单失败: ' + (error.response?.data?.message || error.message)); } finally { setLoading(false); } }; return (
{/* 头部导航 */}

[ DISPATCH // 管理员代客下单 ]

手工为客户创建订单并即时下发抢单机器人调度队列

{/* Step 1: 搜索选择商品 */} {/* Step 1.5: 渠道来源与合伙分润设置 */} {selectedProduct && (
1.5
40% 销售包干提成归属判定
{/* 渠道类型选择 */}
{/* Direct */}
{ setChannelType('direct'); const u = getCurrentUser(); if (u?.nickname || u?.id) setHandlerId(u.nickname || u.id); }} className={`p-3.5 border-2 cursor-pointer transition ${ channelType === 'direct' ? 'border-black bg-amber-100 shadow-[3px_3px_0px_#000]' : 'border-neutral-300 bg-neutral-50 hover:border-black' }`} >
[ 社交自收直客 ]

小红书/微信自引流直客,拿该单 40% 销售包干提成,对录错承担全额赔偿。

{/* Agency */}
setChannelType('agency')} className={`p-3.5 border-2 cursor-pointer transition ${ channelType === 'agency' ? 'border-black bg-purple-100 shadow-[3px_3px_0px_#000]' : 'border-neutral-300 bg-neutral-50 hover:border-black' }`} >
[ 中介同行渠道 ]

旅行社或同行转介绍,受专属底价保护,40%提成自动锁定归属该中介拓展人。

{/* Website */}
{ setChannelType('website'); setHandlerId(''); }} className={`p-3.5 border-2 cursor-pointer transition ${ channelType === 'website' ? 'border-black bg-neutral-200 shadow-[3px_3px_0px_#000]' : 'border-neutral-300 bg-neutral-50 hover:border-black' }`} >
[ 官网自主下单 ]

公海自然流量,无专属对接人,40%销售提成由合伙双方(各20%)平分。

{/* 细化字段配置 */}
{/* Direct: 接单客服 */} {channelType === 'direct' && (
)} {/* Agency: 选择中介 */} {channelType === 'agency' && (
{selectedAgency && (
专属拓展维系人: {selectedAgency.owner_id} (自动绑定拿40%提成)
协议最低底价: ¥{(selectedAgency.min_floor_price / 100).toFixed(2)} 低于此底价系统将阻断提交
)}
)} {/* Website */} {channelType === 'website' && (
公海单利润流转:

该单无专属对接人。40% 销售提成与 40% 合伙分红合并,由合伙人甲乙双方各按 50%(每人到手40%净利)平分;技术版权费 20% 归脚本开发者。

)}
)} {/* Step 1.6: 收款时机与金额登记 */} {selectedProduct && (
1.6
先办后付 vs 现结核销
{/* 收款时机选择 */}
{/* Pay later */}
setPaymentTiming('pay_later')} className={`p-3.5 border-2 cursor-pointer transition ${ paymentTiming === 'pay_later' ? 'border-black bg-amber-100 shadow-[3px_3px_0px_#000]' : 'border-neutral-300 bg-neutral-50 hover:border-black' }`} >
[ 先办后付 // 稍后收款 ]
业务推荐

先替客户下单,任务立即下发队列调度。待出签办妥或客户打款后,在后台随时一键[ 登记收款 ]生成流水。

{/* Paid now */}
setPaymentTiming('paid_now')} className={`p-3.5 border-2 cursor-pointer transition ${ paymentTiming === 'paid_now' ? 'border-black bg-emerald-100 shadow-[3px_3px_0px_#000]' : 'border-neutral-300 bg-neutral-50 hover:border-black' }`} >
[ 当场全款已收 // 现结录入 ]

客户已通过微信/支付宝/公户全款转账,现场直接核销入账,立即在数据库生成已支付流水凭据。

{/* 金额输入及差额提示 */}
币种:
{getCurrencySymbol(currency)} setCustomPrice(e.target.value)} placeholder="商品指导价" className="w-full pl-8 pr-3 py-2 border-2 border-black bg-neutral-50 text-xs font-mono font-black focus:bg-white outline-none shadow-[2px_2px_0px_#000] text-black" />
商品指导标价: {getCurrencySymbol(selectedProduct.price_currency || 'CNY')}{((selectedProduct.price_amount || selectedProduct.base_price || 0) / 100).toFixed(2)} ({selectedProduct.price_currency || 'CNY'}) {customPrice && !isNaN(Number(customPrice)) && ( (selectedProduct.price_amount || 0) ? 'text-emerald-700' : 'text-neutral-500' }`}> 差额: {Number(customPrice) * 100 >= (selectedProduct.price_amount || 0) ? '+' : ''}{getCurrencySymbol(currency)}{((Number(customPrice) * 100 - (selectedProduct.price_amount || 0)) / 100).toFixed(2)} )}
{paymentTiming === 'pay_later' ? (
先办后付调度保障:

订单创建后将自动标记为 [ 待收款 (先办后付) ],抢单机器人将以最高优先级即刻开始抓取办理。后续款项到手后,在订单列表点击 [ 💰 登记收款 ] 即可补录流水。

) : (
{[ { id: 'wechat', label: '微信私域转账' }, { id: 'alipay', label: '支付宝转账' }, { id: 'bank_transfer', label: '银行公户/私户' }, { id: 'cash', label: '现金收款' }, ].map((m) => ( ))}
)}
{/* 当场结清时的补充凭据 */} {paymentTiming === 'paid_now' && (
setExternalTradeNo(e.target.value)} placeholder="微信单号 / 银行流水号" className="w-full px-2.5 py-1.5 border-2 border-black bg-neutral-50 text-xs font-mono font-bold focus:bg-white outline-none shadow-[2px_2px_0px_#000] text-black" />
setPaymentNote(e.target.value)} placeholder="例如: 客户微信当面付清" className="w-full px-2.5 py-1.5 border-2 border-black bg-neutral-50 text-xs font-mono font-bold focus:bg-white outline-none shadow-[2px_2px_0px_#000] text-black" />
)}
)} {/* Step 2: 填写表单 (含 AI) */} {selectedProduct && (
02
{/* AI 智能填充面板 */} {formSchema && ( )} {/* 动态表单项及底部提交按钮 */}
)}
); }