// src/components/admin/node-configurations/NodeConfigEditModal.tsx 'use client'; import React, { useState, useEffect } from 'react'; import { toast } from 'react-hot-toast'; import { NodeConfigEntryType, NodeConfigurationItem, SparseUpdatePayload, AppointmentTypeItem, PluginConfig, } from '@/types'; import { nodeConfigService } from '@/lib/services/nodeConfigService'; import AppointmentTypeEditor from './AppointmentTypeEditor'; interface NodeConfigEditModalProps { isOpen: boolean; onClose: () => void; entryType: NodeConfigEntryType; config: NodeConfigurationItem | null; onSuccess: () => void; } export default function NodeConfigEditModal({ isOpen, onClose, entryType, config, onSuccess, }: NodeConfigEditModalProps) { const [mode, setMode] = useState<'visual' | 'json'>('visual'); const [saving, setSaving] = useState(false); // Visual mode form fields const [nodeId, setNodeId] = useState(''); const [website, setWebsite] = useState(''); const [proxyCd, setProxyCd] = useState(''); const [sessionMaxLife, setSessionMaxLife] = useState(''); const [activeTimeStart, setActiveTimeStart] = useState(''); const [activeTimeEnd, setActiveTimeEnd] = useState(''); const [proxyPoolStr, setProxyPoolStr] = useState(''); // Standalone specifics const [orderId, setOrderId] = useState(''); const [accountUsername, setAccountUsername] = useState(''); const [accountPassword, setAccountPassword] = useState(''); const [loginInterval, setLoginInterval] = useState(''); const [userPreferencesStr, setUserPreferencesStr] = useState('{}'); // Booker specifics const [bookerAccountSource, setBookerAccountSource] = useState(''); const [bookerAccountPoolId, setBookerAccountPoolId] = useState(''); const [bookerTargetInstances, setBookerTargetInstances] = useState(''); const [bookerAccountCd, setBookerAccountCd] = useState(''); const [bookerCooldown, setBookerCooldown] = useState(''); const [bookerMaxBookings, setBookerMaxBookings] = useState(''); // Sentinel specifics const [sentinelAccountSource, setSentinelAccountSource] = useState(''); const [sentinelAccountPoolId, setSentinelAccountPoolId] = useState(''); const [sentinelTargetInstances, setSentinelTargetInstances] = useState(''); const [sentinelSignalTtl, setSentinelSignalTtl] = useState(''); const [queryWaitMode, setQueryWaitMode] = useState<'Random' | 'Fixed'>('Random'); const [fixedWait, setFixedWait] = useState(''); const [randomMin, setRandomMin] = useState(''); const [randomMax, setRandomMax] = useState(''); // Plugin & Free config & Appointment types const [pluginConfig, setPluginConfig] = useState({}); const [appointmentTypes, setAppointmentTypes] = useState([]); const [freeConfigStr, setFreeConfigStr] = useState('{}'); // JSON mode payload const [rawJsonStr, setRawJsonStr] = useState('{\n "set": {},\n "clear": []\n}'); useEffect(() => { if (config) { setNodeId(config.node_id || ''); setWebsite(config.website || ''); setProxyCd(config.proxy_cd !== undefined ? config.proxy_cd : ''); setSessionMaxLife(config.session_max_life !== undefined ? config.session_max_life : ''); setActiveTimeStart(config.active_time_start || ''); setActiveTimeEnd(config.active_time_end || ''); setProxyPoolStr(config.proxy_pool ? config.proxy_pool.join(', ') : ''); setOrderId(config.order_id || ''); setAccountUsername(config.account?.username || ''); setAccountPassword(config.account?.password || ''); setLoginInterval(config.login_interval !== undefined ? config.login_interval : ''); setUserPreferencesStr( config.user_preferences ? JSON.stringify(config.user_preferences, null, 2) : '{}' ); setBookerAccountSource(config.booker?.account_source || 'built-in'); setBookerAccountPoolId(config.booker?.account_pool_id || ''); setBookerTargetInstances(config.booker?.target_instances !== undefined ? config.booker.target_instances : 1); setBookerAccountCd(config.booker?.account_cd !== undefined ? config.booker.account_cd : ''); setBookerCooldown(config.booker?.booking_cooldown !== undefined ? config.booker.booking_cooldown : ''); setBookerMaxBookings(config.booker?.max_bookings_per_account !== undefined ? config.booker.max_bookings_per_account : ''); setSentinelAccountSource(config.sentinel?.account_source || 'built-in'); setSentinelAccountPoolId(config.sentinel?.account_pool_id || ''); setSentinelTargetInstances(config.sentinel?.target_instances !== undefined ? config.sentinel.target_instances : 1); setSentinelSignalTtl(config.sentinel?.signal_ttl !== undefined ? config.sentinel.signal_ttl : ''); const qw = config.sentinel?.query_wait || config.query_wait; if (qw) { setQueryWaitMode((qw.mode as any) || 'Random'); setFixedWait(qw.fixed_wait !== undefined ? qw.fixed_wait : ''); setRandomMin(qw.random_min !== undefined ? qw.random_min : ''); setRandomMax(qw.random_max !== undefined ? qw.random_max : ''); } else { setQueryWaitMode('Random'); setFixedWait(''); setRandomMin(''); setRandomMax(''); } setPluginConfig(config.plugin_config || {}); setAppointmentTypes(config.appointment_types || []); setFreeConfigStr(config.free_config ? JSON.stringify(config.free_config, null, 2) : '{}'); setRawJsonStr( JSON.stringify( { set: {}, clear: [], }, null, 2 ) ); } }, [config, isOpen]); if (!isOpen || !config) return null; const calculateSparsePayload = (): SparseUpdatePayload => { const setObj: Record = {}; const clearArr: string[] = []; if (nodeId.trim() && nodeId.trim() !== (config.node_id || '')) { setObj['node_id'] = nodeId.trim(); } if (website !== (config.website || '')) { if (website === '') clearArr.push('website'); else setObj['website'] = website; } if (proxyCd !== '' && proxyCd !== config.proxy_cd) { setObj['proxy_cd'] = Number(proxyCd); } if (sessionMaxLife !== '' && sessionMaxLife !== config.session_max_life) { setObj['session_max_life'] = Number(sessionMaxLife); } if (activeTimeStart !== (config.active_time_start || '')) setObj['active_time_start'] = activeTimeStart; if (activeTimeEnd !== (config.active_time_end || '')) setObj['active_time_end'] = activeTimeEnd; const newProxyList = proxyPoolStr.split(',').map((s) => s.trim()).filter(Boolean); const oldProxyList = config.proxy_pool || []; if (JSON.stringify(newProxyList) !== JSON.stringify(oldProxyList)) { setObj['proxy_pool'] = newProxyList; } if (entryType === 'booker') { if (bookerAccountSource !== (config.booker?.account_source || '')) setObj['booker.account_source'] = bookerAccountSource; if (bookerAccountPoolId !== (config.booker?.account_pool_id || '')) setObj['booker.account_pool_id'] = bookerAccountPoolId; if (bookerTargetInstances !== '' && bookerTargetInstances !== config.booker?.target_instances) { setObj['booker.target_instances'] = Number(bookerTargetInstances); } if (bookerAccountCd !== '' && bookerAccountCd !== config.booker?.account_cd) { setObj['booker.account_cd'] = Number(bookerAccountCd); } if (bookerCooldown !== '' && bookerCooldown !== config.booker?.booking_cooldown) { setObj['booker.booking_cooldown'] = Number(bookerCooldown); } if (bookerMaxBookings !== '' && bookerMaxBookings !== config.booker?.max_bookings_per_account) { setObj['booker.max_bookings_per_account'] = Number(bookerMaxBookings); } } if (entryType === 'sentinel') { if (sentinelAccountSource !== (config.sentinel?.account_source || '')) setObj['sentinel.account_source'] = sentinelAccountSource; if (sentinelAccountPoolId !== (config.sentinel?.account_pool_id || '')) setObj['sentinel.account_pool_id'] = sentinelAccountPoolId; if (sentinelTargetInstances !== '' && sentinelTargetInstances !== config.sentinel?.target_instances) { setObj['sentinel.target_instances'] = Number(sentinelTargetInstances); } if (sentinelSignalTtl !== '' && sentinelSignalTtl !== config.sentinel?.signal_ttl) { setObj['sentinel.signal_ttl'] = Number(sentinelSignalTtl); } if (queryWaitMode !== (config.sentinel?.query_wait?.mode || 'Random')) { setObj['sentinel.query_wait.mode'] = queryWaitMode; } if (queryWaitMode === 'Fixed' && fixedWait !== '' && fixedWait !== config.sentinel?.query_wait?.fixed_wait) { setObj['sentinel.query_wait.fixed_wait'] = Number(fixedWait); } if (queryWaitMode === 'Random') { if (randomMin !== '' && randomMin !== config.sentinel?.query_wait?.random_min) { setObj['sentinel.query_wait.random_min'] = Number(randomMin); } if (randomMax !== '' && randomMax !== config.sentinel?.query_wait?.random_max) { setObj['sentinel.query_wait.random_max'] = Number(randomMax); } } } if (entryType === 'standalone') { if (orderId !== (config.order_id || '')) setObj['order_id'] = orderId; if (accountUsername !== (config.account?.username || '')) setObj['account.username'] = accountUsername; if (accountPassword !== (config.account?.password || '')) setObj['account.password'] = accountPassword; if (loginInterval !== '' && loginInterval !== config.login_interval) setObj['login_interval'] = Number(loginInterval); try { const parsedUserPref = userPreferencesStr.trim() ? JSON.parse(userPreferencesStr) : {}; if (JSON.stringify(parsedUserPref) !== JSON.stringify(config.user_preferences || {})) { setObj['user_preferences'] = parsedUserPref; } } catch {} } if (JSON.stringify(pluginConfig) !== JSON.stringify(config.plugin_config || {})) { setObj['plugin_config'] = pluginConfig; } if (JSON.stringify(appointmentTypes) !== JSON.stringify(config.appointment_types || [])) { setObj['appointment_types'] = appointmentTypes; } try { const parsedFree = freeConfigStr.trim() ? JSON.parse(freeConfigStr) : {}; if (JSON.stringify(parsedFree) !== JSON.stringify(config.free_config || {})) { setObj['free_config'] = parsedFree; } } catch {} return { set: Object.keys(setObj).length > 0 ? setObj : undefined, clear: clearArr.length > 0 ? clearArr : undefined, }; }; const handleFormatJson = () => { try { const parsed = JSON.parse(rawJsonStr); setRawJsonStr(JSON.stringify(parsed, null, 2)); toast.success('JSON 已格式化'); } catch { toast.error('JSON 语法错误,无法格式化'); } }; const handleCopyJson = () => { navigator.clipboard.writeText(rawJsonStr); toast.success('已复制到剪贴板'); }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setSaving(true); try { let payload: SparseUpdatePayload; if (mode === 'json') { try { payload = JSON.parse(rawJsonStr); } catch { toast.error('JSON 格式错误,请检查语法'); setSaving(false); return; } } else { if (entryType === 'standalone') { try { if (userPreferencesStr.trim()) { JSON.parse(userPreferencesStr); } } catch { toast.error('用户偏好 (user_preferences) JSON 格式错误,请检查语法'); setSaving(false); return; } } payload = calculateSparsePayload(); if (!payload.set && (!payload.clear || payload.clear.length === 0)) { toast('未检测到任何字段变更', { icon: 'ℹ️' }); onClose(); setSaving(false); return; } } const res = await nodeConfigService.sparseUpdate(entryType, config.id, payload); if (res.code === 0) { toast.success(`配置更新成功 (版本已升至 v${res.data?.version || config.version + 1})`); onSuccess(); onClose(); } else { toast.error(res.message || '更新失败'); } } catch (err: any) { console.error('Update config error:', err); toast.error(err?.response?.data?.message || err.message || '更新异常'); } finally { setSaving(false); } }; return (
{/* Header */}

[ EDIT {entryType.toUpperCase()} CONFIG // 稀疏编辑: {config.node_id} / {config.identifier} (v{config.version}) ]

{/* Mode Switcher */}
{/* Body */}
{mode === 'visual' ? (
{/* Base & Network */}
[ 01 // 节点与网络参数 ]
setNodeId(e.target.value)} placeholder="default, node01, node02..." 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]" />
setWebsite(e.target.value)} placeholder="https://visa.vfsglobal.com/..." 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]" />
setProxyCd(e.target.value === '' ? '' : 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]" />
setSessionMaxLife(e.target.value === '' ? '' : 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]" />
setProxyPoolStr(e.target.value)} placeholder="proxy-cheap, proxy-fast" 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]" />
{/* Booker fields */} {entryType === 'booker' && (
[ 02 // Booker 调度与池参数 ]
setBookerAccountPoolId(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]" />
setBookerTargetInstances(e.target.value === '' ? '' : 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]" />
setBookerAccountCd(e.target.value === '' ? '' : 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]" />
setBookerCooldown(e.target.value === '' ? '' : 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]" />
setBookerMaxBookings(e.target.value === '' ? '' : 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]" />
)} {/* Sentinel fields */} {entryType === 'sentinel' && (
[ 02 // Sentinel 扫位与信号策略 ]
setSentinelAccountPoolId(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]" />
setSentinelTargetInstances(e.target.value === '' ? '' : 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]" />
setSentinelSignalTtl(e.target.value === '' ? '' : 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]" />
{queryWaitMode === 'Fixed' ? (
setFixedWait(e.target.value === '' ? '' : 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]" />
) : ( <>
setRandomMin(e.target.value === '' ? '' : 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]" />
setRandomMax(e.target.value === '' ? '' : 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]" />
)}
)} {/* Standalone fields */} {entryType === 'standalone' && (
[ 02 // Standalone 偏好与凭证 ]
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]" />
setLoginInterval(e.target.value === '' ? '' : 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]" />
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]" />
支持自定义键值与可变结构