// src/components/admin/node-configurations/NodeConfigCreateWizardModal.tsx 'use client'; import React, { useState, useEffect } from 'react'; import { toast } from 'react-hot-toast'; import { NodeConfigEntryType, ProviderItem, AppointmentTypeItem, PluginConfig, NodeConfigurationItem, } from '@/types'; import { providerService } from '@/lib/services/providerService'; import { nodeConfigService } from '@/lib/services/nodeConfigService'; import { accountService } from '@/lib/services/accountService'; import { proxyService } from '@/lib/services/proxyService'; import AppointmentTypeEditor from './AppointmentTypeEditor'; import RegisteredNodeSelect from '@/components/admin/node-configurations/RegisteredNodeSelect'; import { LOCAL_PROXY_POOLS, COMMON_WEBSITES } from './nodeConfigConstants'; interface NodeConfigCreateWizardModalProps { isOpen: boolean; onClose: () => void; entryType: NodeConfigEntryType; onSuccess: () => void; } export default function NodeConfigCreateWizardModal({ isOpen, onClose, entryType, onSuccess, }: NodeConfigCreateWizardModalProps) { const [step, setStep] = useState<1 | 2 | 3>(1); const [providers, setProviders] = useState([]); const [selectedProviderName, setSelectedProviderName] = useState(''); const [loadingProviders, setLoadingProviders] = useState(false); const [submitting, setSubmitting] = useState(false); // 数据库获取的账号池与代理池 const [accountPools, setAccountPools] = useState<{ pool_name: string; total_count?: number }[]>([]); const [cloudProxyPools, setCloudProxyPools] = useState<{ pool_name: string; total_count?: number }[]>([]); const [customBookerAccountPool, setCustomBookerAccountPool] = useState(false); const [customSentinelAccountPool, setCustomSentinelAccountPool] = useState(false); // Step 1: Base & Identity const [nodeId, setNodeId] = useState('node01'); const [identifier, setIdentifier] = useState(''); const [website, setWebsite] = useState(''); const [needAccount, setNeedAccount] = useState(1); const [needProxy, setNeedProxy] = useState(1); const [proxyPoolStr, setProxyPoolStr] = useState('cloud:proxy-cheap'); const [proxyCd, setProxyCd] = useState(300); const [sessionMaxLife, setSessionMaxLife] = useState(1800); const [activeTimeStart, setActiveTimeStart] = useState('00:00'); const [activeTimeEnd, setActiveTimeEnd] = useState('23:59'); // Standalone specifics const [orderId, setOrderId] = useState(''); const [accountUsername, setAccountUsername] = useState(''); const [accountPassword, setAccountPassword] = useState(''); const [supportPta, setSupportPta] = useState(false); const [expectedStartDate, setExpectedStartDate] = useState(''); const [expectedEndDate, setExpectedEndDate] = useState(''); const [loginInterval, setLoginInterval] = useState(1800); // Booker specifics const [bookerAccountSource, setBookerAccountSource] = useState('built-in'); const [bookerAccountPoolId, setBookerAccountPoolId] = useState(''); const [bookerTargetInstances, setBookerTargetInstances] = useState(1); const [bookerAccountCd, setBookerAccountCd] = useState(10800); const [bookerCooldown, setBookerCooldown] = useState(30); const [bookerMaxBookings, setBookerMaxBookings] = useState(8); // Sentinel specifics const [sentinelAccountSource, setSentinelAccountSource] = useState('built-in'); const [sentinelAccountPoolId, setSentinelAccountPoolId] = useState(''); const [sentinelTargetInstances, setSentinelTargetInstances] = useState(1); const [sentinelSignalTtl, setSentinelSignalTtl] = useState(30); // Query Wait const [queryWaitMode, setQueryWaitMode] = useState<'Random' | 'Fixed'>('Random'); const [fixedWait, setFixedWait] = useState(10); const [randomMin, setRandomMin] = useState(60); const [randomMax, setRandomMax] = useState(300); // Plugin config const [pluginConfig, setPluginConfig] = useState({ lib_path: 'plugins', plugin_name: '', plugin_bin: '', plugin_class: '', plugin_proto: 'IPlugin', }); // Appointment types & free config const [appointmentTypes, setAppointmentTypes] = useState([]); const [freeConfigStr, setFreeConfigStr] = useState('{}'); useEffect(() => { if (isOpen) { setStep(1); fetchEnabledProviders(); fetchDbPools(); resetForm(); } }, [isOpen, entryType]); const fetchDbPools = async () => { try { const [accRes, proxyRes] = await Promise.allSettled([ accountService.getPools(), proxyService.getPools(), ]); if (accRes.status === 'fulfilled' && accRes.value?.data) { setAccountPools(Array.isArray(accRes.value.data) ? accRes.value.data : []); } if (proxyRes.status === 'fulfilled' && proxyRes.value?.data) { setCloudProxyPools(Array.isArray(proxyRes.value.data) ? proxyRes.value.data : []); } } catch (err) { console.error('Failed to fetch pools from DB:', err); } }; const addProxyPoolTag = (tagToAdd: string) => { if (!tagToAdd) return; const current = proxyPoolStr.split(',').map((s) => s.trim()).filter(Boolean); if (!current.includes(tagToAdd)) { current.push(tagToAdd); setProxyPoolStr(current.join(', ')); } }; const removeProxyPoolTag = (tagToRemove: string) => { const current = proxyPoolStr.split(',').map((s) => s.trim()).filter(Boolean); const updated = current.filter((t) => t !== tagToRemove); setProxyPoolStr(updated.join(', ')); }; // 仅筛选出支持当前 entryType 角色的服务商模板 const eligibleProviders = providers.filter( (p) => p.role_templates && Boolean(p.role_templates[entryType]) ); const fetchEnabledProviders = async () => { setLoadingProviders(true); try { const res = await providerService.getList({ enabled_only: true }); if (res.code === 0 && res.data) { const list = Array.isArray(res.data) ? res.data : []; setProviders(list); const matching = list.filter( (p) => p.role_templates && Boolean(p.role_templates[entryType]) ); if (matching.length > 0 && !selectedProviderName) { handleProviderSelect(matching[0].name, list, false); } } } catch (e) { console.error('Failed to fetch providers:', e); } finally { setLoadingProviders(false); } }; const resetForm = () => { setSelectedProviderName(''); setNodeId(''); setIdentifier(''); setWebsite(''); setNeedAccount(1); setNeedProxy(1); setProxyPoolStr(''); setProxyCd(300); setSessionMaxLife(1800); setActiveTimeStart('00:00'); setActiveTimeEnd('23:59'); setOrderId(''); setAccountUsername(''); setAccountPassword(''); setSupportPta(false); setExpectedStartDate(''); setExpectedEndDate(''); setLoginInterval(1800); setBookerAccountSource('built-in'); setBookerAccountPoolId(''); setBookerTargetInstances(1); setBookerAccountCd(10800); setBookerCooldown(300); setBookerMaxBookings(8); setCustomBookerAccountPool(false); setSentinelAccountSource('built-in'); setSentinelAccountPoolId(''); setSentinelTargetInstances(1); setSentinelSignalTtl(30); setCustomSentinelAccountPool(false); setQueryWaitMode('Random'); setFixedWait(10); setRandomMin(60); setRandomMax(300); setPluginConfig({ lib_path: 'plugins', plugin_name: '', plugin_bin: '', plugin_proto: 'IPlugin', }); setAppointmentTypes([]); setFreeConfigStr('{}'); }; const handleProviderSelect = (providerName: string, providerList = providers, showToast = true) => { setSelectedProviderName(providerName); const p = providerList.find((item) => item.name === providerName); if (!p) return; if (p.plugin_config) { setPluginConfig({ lib_path: p.plugin_config.lib_path || 'plugins', plugin_name: p.plugin_config.plugin_name || '', plugin_bin: p.plugin_config.plugin_bin || '', plugin_class: p.plugin_config.plugin_class || '', plugin_proto: p.plugin_config.plugin_proto || 'IPlugin', }); } const roleTpl = p.role_templates?.[entryType]; if (roleTpl) { if (roleTpl.proxy_cd !== undefined) setProxyCd(Number(roleTpl.proxy_cd)); if (roleTpl.session_max_life !== undefined) setSessionMaxLife(Number(roleTpl.session_max_life)); if (roleTpl.login_interval !== undefined) setLoginInterval(Number(roleTpl.login_interval)); if (entryType === 'booker') { if (roleTpl['booker.account_source'] !== undefined) setBookerAccountSource(roleTpl['booker.account_source']); if (roleTpl['booker.account_pool_id'] !== undefined) setBookerAccountPoolId(roleTpl['booker.account_pool_id']); if (roleTpl['booker.account_cd'] !== undefined) setBookerAccountCd(Number(roleTpl['booker.account_cd'])); if (roleTpl['booker.target_instances'] !== undefined) setBookerTargetInstances(Number(roleTpl['booker.target_instances'])); if (roleTpl['booker.booking_cooldown'] !== undefined) setBookerCooldown(Number(roleTpl['booker.booking_cooldown'])); if (roleTpl['booker.max_bookings_per_account'] !== undefined) setBookerMaxBookings(Number(roleTpl['booker.max_bookings_per_account'])); } else if (entryType === 'sentinel') { if (roleTpl['sentinel.account_source'] !== undefined) setSentinelAccountSource(roleTpl['sentinel.account_source']); if (roleTpl['sentinel.account_pool_id'] !== undefined) setSentinelAccountPoolId(roleTpl['sentinel.account_pool_id']); if (roleTpl['sentinel.target_instances'] !== undefined) setSentinelTargetInstances(Number(roleTpl['sentinel.target_instances'])); if (roleTpl['sentinel.signal_ttl'] !== undefined) setSentinelSignalTtl(Number(roleTpl['sentinel.signal_ttl'])); if (roleTpl['sentinel.query_wait.mode'] !== undefined) setQueryWaitMode(roleTpl['sentinel.query_wait.mode']); } } if (showToast) { toast.success(`已从服务商模板 [${providerName}] 继承参数与插件驱动`); } }; const buildPayload = (): Partial => { const proxyList = proxyPoolStr .split(',') .map((s) => s.trim()) .filter(Boolean); let parsedFreeConfig = {}; try { if (freeConfigStr.trim()) parsedFreeConfig = JSON.parse(freeConfigStr); } catch {} const base: any = { node_id: nodeId.trim(), identifier: identifier.trim(), website: website.trim(), plugin_config: pluginConfig, appointment_types: appointmentTypes, free_config: parsedFreeConfig, }; if (entryType === 'booker') { base.need_account = needAccount; base.need_proxy = needProxy; base.proxy_pool = proxyList; base.proxy_cd = proxyCd; base.session_max_life = sessionMaxLife; base.active_time_start = activeTimeStart; base.active_time_end = activeTimeEnd; base.booker = { account_source: bookerAccountSource, account_pool_id: bookerAccountPoolId.trim(), target_instances: Number(bookerTargetInstances), account_cd: Number(bookerAccountCd), booking_cooldown: Number(bookerCooldown), max_bookings_per_account: Number(bookerMaxBookings), }; } else if (entryType === 'sentinel') { base.sentinel = { account_source: sentinelAccountSource, account_pool_id: sentinelAccountPoolId.trim(), target_instances: Number(sentinelTargetInstances), signal_ttl: Number(sentinelSignalTtl), query_wait: { mode: queryWaitMode, ...(queryWaitMode === 'Fixed' ? { fixed_wait: Number(fixedWait) } : { random_min: Number(randomMin), random_max: Number(randomMax) }), }, }; } else if (entryType === 'standalone') { base.order_id = orderId.trim(); base.account = { username: accountUsername.trim(), password: accountPassword, }; base.proxy_pool = proxyList; base.login_interval = Number(loginInterval); base.session_max_life = Number(sessionMaxLife); base.query_wait = { mode: queryWaitMode, ...(queryWaitMode === 'Fixed' ? { fixed_wait: Number(fixedWait) } : { random_min: Number(randomMin), random_max: Number(randomMax) }), }; base.user_preferences = { support_pta: supportPta, expected_start_date: expectedStartDate, expected_end_date: expectedEndDate, }; } return base; }; const handleNext = () => { if (step === 1) { if (!selectedProviderName) { toast.error('新建任务必须选择一个服务商模板以继承配置与插件'); return; } if (!nodeId.trim()) { toast.error('请选择已注册的目标集群节点 (node_id)'); return; } if (!identifier.trim()) { toast.error('任务标识 (identifier) 不能为空'); return; } setStep(2); } else if (step === 2) { try { if (freeConfigStr.trim()) JSON.parse(freeConfigStr); } catch { toast.error('自定义 Free Config JSON 格式错误'); return; } setStep(3); } }; const handleSubmit = async () => { const payload = buildPayload(); setSubmitting(true); try { const res = await nodeConfigService.create(entryType, payload); if (res.code === 0) { toast.success(`[${entryType.toUpperCase()}] 节点任务配置创建成功 (默认已停用)`); onSuccess(); onClose(); } else { toast.error(res.message || '创建失败'); } } catch (err: any) { console.error('Create node config error:', err); const msg = err?.response?.data?.message || err.message || '创建异常'; toast.error(msg); } finally { setSubmitting(false); } }; if (!isOpen) return null; return (
{/* Header */}

[ CREATE {entryType.toUpperCase()} WIZARD // 新建{entryType.toUpperCase()}任务向导 ]

{/* Stepper Tabs */}
{[ { num: 1, label: '01. 模板与标识' }, { num: 2, label: '02. 策略与参数' }, { num: 3, label: '03. 核对与提交' }, ].map((s) => ( s.num ? 'bg-emerald-300 text-black' : 'bg-white text-neutral-500' }`} > {s.label} ))}
{/* Wizard Body */}
{/* STEP 1 */} {step === 1 && (
{/* Provider Selection (Mandatory) */}
[ PROVIDER TEMPLATE // 选择预设服务商模板 (必须继承) ]
* 必须选择服务商模板以继承参数与插件驱动
{selectedProviderName ? (
✓ 已继承 [{selectedProviderName.toUpperCase()}] 模板参数 & 插件驱动 [{pluginConfig.plugin_name || '内置'}]
) : eligibleProviders.length === 0 ? (
⚠️ 暂无支持 [{entryType.toUpperCase()}] 的模板,请在「服务商模板」中开启此角色
) : (
⚠️ 新建 {entryType.toUpperCase()} 任务必须选择一个服务商模板
)}
{/* Node Identity */}
[ IDENTITY // 任务与节点标识 ]
setIdentifier(e.target.value)} className="w-full px-3 py-2 border-2 border-black bg-neutral-50 focus:bg-white text-xs font-mono text-black outline-none shadow-[2px_2px_0px_#000] placeholder:text-neutral-400" />
支持直接输入或点击推荐使馆
setWebsite(e.target.value)} className="w-full px-3 py-2 border-2 border-black bg-neutral-50 focus:bg-white text-xs font-mono text-black outline-none shadow-[2px_2px_0px_#000] placeholder:text-neutral-400" /> {COMMON_WEBSITES.map((item) => ( ))}
推荐使馆: {COMMON_WEBSITES.map((item) => ( ))}
{/* Standalone special */} {entryType === 'standalone' && (
[ STANDALONE CREDENTIALS // 订单与账号凭证 ]
setOrderId(e.target.value)} className="w-full px-3 py-2 border-2 border-black bg-neutral-50 focus:bg-white text-xs font-mono text-black outline-none shadow-[2px_2px_0px_#000]" />
setAccountUsername(e.target.value)} className="w-full px-3 py-2 border-2 border-black bg-neutral-50 focus:bg-white text-xs font-mono text-black outline-none shadow-[2px_2px_0px_#000]" />
setAccountPassword(e.target.value)} className="w-full px-3 py-2 border-2 border-black bg-neutral-50 focus:bg-white text-xs font-mono text-black outline-none shadow-[2px_2px_0px_#000]" />
)}
)} {/* STEP 2 */} {step === 2 && (
{/* Booker fields */} {entryType === 'booker' && (
[ BOOKER PARAMS // 占位调度与池参数 ]
{/* Account Pool ID - dropdown from DB */}
{customBookerAccountPool ? (
setBookerAccountPoolId(e.target.value)} placeholder="输入自定义池 ID" className="flex-1 px-3 py-2 border-2 border-black bg-neutral-50 focus:bg-white text-xs font-mono text-black outline-none shadow-[2px_2px_0px_#000]" />
) : ( )}
{/* Target Instances - preset dropdown */}
{/* Account CD - preset dropdown */}
{/* Booking Cooldown - preset dropdown */}
{/* Max Bookings - preset dropdown */}
{/* Proxy CD - preset dropdown */}
{/* Proxy Pool - tag-based multi-select from DB */}
{/* Selected tags */}
{proxyPoolStr.split(',').map(s => s.trim()).filter(Boolean).length === 0 && ( 尚未选择代理池... )} {proxyPoolStr.split(',').map(s => s.trim()).filter(Boolean).map((tag) => ( {tag.startsWith('cloud:') ? '☁' : '⊙'} {tag} ))}
{/* Add tag dropdown */}
{/* Session Max Life - preset dropdown */}
)} {/* Sentinel fields */} {entryType === 'sentinel' && (
[ SENTINEL PARAMS // 监控与等待策略 ]
{/* Account Pool ID - dropdown from DB */}
{customSentinelAccountPool ? (
setSentinelAccountPoolId(e.target.value)} placeholder="输入自定义池 ID" className="flex-1 px-3 py-2 border-2 border-black bg-neutral-50 focus:bg-white text-xs font-mono text-black outline-none shadow-[2px_2px_0px_#000]" />
) : ( )}
{/* Target Instances - preset dropdown */}
{/* Signal TTL - preset dropdown */}
{/* Query Wait Mode - dropdown */}
{queryWaitMode === 'Fixed' ? (
) : ( <>
)}
)} {/* Standalone fields */} {entryType === 'standalone' && (
[ STANDALONE PARAMS // 偏好与轮询策略 ]
setLoginInterval(Number(e.target.value))} className="w-full px-3 py-2 border-2 border-black bg-neutral-50 focus:bg-white text-xs font-mono text-black outline-none shadow-[2px_2px_0px_#000]" />
setExpectedStartDate(e.target.value)} className="w-full px-3 py-2 border-2 border-black bg-neutral-50 focus:bg-white text-xs font-mono text-black outline-none shadow-[2px_2px_0px_#000]" />
setExpectedEndDate(e.target.value)} className="w-full px-3 py-2 border-2 border-black bg-neutral-50 focus:bg-white text-xs font-mono text-black outline-none shadow-[2px_2px_0px_#000]" />
)} {/* Appointment Types */} {/* Plugin (Inherited from Template, read-only) & Free Config */}
[ PLUGIN DRIVER // 插件运行时 (已由模板绑定) ]
✓ 自动从模板 [{selectedProviderName || '未选'}] 继承,无需手动配置
{/* Readonly info bar */}
绑定插件: {pluginConfig.plugin_name || '默认内置驱动'}
执行脚本: {pluginConfig.plugin_bin || '(内置脚本)'}
接口协议: {pluginConfig.plugin_proto || 'IPlugin'} 加载目录: {pluginConfig.lib_path || 'plugins'} {pluginConfig.plugin_class && ( 入口类: {pluginConfig.plugin_class} )}
{/* Free Config */}