import React, { useEffect, useState } from 'react'; import { createPortal } from 'react-dom'; import { AccountDetail, AIReplySettings } from '../types'; import { getAccountDetails, getAccountRuntimeStatuses, addAccount, updateAccountStatus, deleteAccount, generateQRLogin, checkQRLoginStatus, completeQRVerification, updateAccountRemark, updateAccountAutoConfirm, updateAccountPauseDuration, updateAccountCookie, refreshAccountProfile, updateAccountLoginInfo, updateAccountAISettings, getAllAISettings, getAccountAISettings } from '../services/api'; import { Plus, Power, Edit2, Trash2, QrCode, X, Check, Loader2, RefreshCw, Save, User, Clock, MessageCircle, Upload, Key, Eye, EyeOff, Bot, Settings, AlertCircle, ExternalLink } from 'lucide-react'; type ModalType = 'edit' | 'ai-settings' | null; const AccountList: React.FC = () => { const [accounts, setAccounts] = useState([]); const [loading, setLoading] = useState(true); const [accountSearch, setAccountSearch] = useState(''); const [refreshingProfileId, setRefreshingProfileId] = useState(''); const [showQRModal, setShowQRModal] = useState(false); const [qrCodeUrl, setQrCodeUrl] = useState(''); const [qrStatus, setQrStatus] = useState('pending'); const [verificationUrl, setVerificationUrl] = useState(''); const [verificationScreenshot, setVerificationScreenshot] = useState(''); const [qrSessionId, setQrSessionId] = useState(''); const [qrReauthTarget, setQrReauthTarget] = useState(null); const [activeModal, setActiveModal] = useState(null); const [editingAccount, setEditingAccount] = useState(null); // 编辑表单状态 const [editForm, setEditForm] = useState({ remark: '', cookie: '', auto_confirm: false, pause_duration: 0, username: '', login_password: '', show_browser: false, showLoginPassword: false, }); // AI设置表单状态 const [aiSettings, setAiSettings] = useState({ ai_enabled: false, max_discount_percent: 10, max_discount_amount: 100, max_bargain_rounds: 3, custom_prompts: '', }); const [saving, setSaving] = useState(false); const refreshRuntimeStatuses = async () => { try { const statuses = await getAccountRuntimeStatuses(); setAccounts(current => current.map(account => { const status = statuses[account.id]; if (!status) return account; return { ...account, runtime_state: status.state, runtime_message: status.message || '', runtime_connected: status.connected, runtime_updated_at: status.updated_at, }; })); } catch (error) { console.error('Failed to load account runtime statuses:', error); } }; const loadAccounts = async () => { setLoading(true); try { const data = await getAccountDetails(); // 获取所有账号的AI设置 let allAISettings: Record = {}; try { allAISettings = await getAllAISettings(); } catch (e) { console.error('Failed to load AI settings:', e); } // 合并AI设置到账号数据 const accountsWithAI = data.map(account => ({ ...account, ai_enabled: allAISettings[account.id]?.ai_enabled ?? false, max_discount_percent: allAISettings[account.id]?.max_discount_percent ?? 10, max_discount_amount: allAISettings[account.id]?.max_discount_amount ?? 100, max_bargain_rounds: allAISettings[account.id]?.max_bargain_rounds ?? 3, custom_prompts: allAISettings[account.id]?.custom_prompts ?? '', })); setAccounts(accountsWithAI); window.setTimeout(refreshRuntimeStatuses, 0); } catch (error) { console.error('Failed to load accounts:', error); } finally { setLoading(false); } }; useEffect(() => { loadAccounts(); const timer = window.setInterval(refreshRuntimeStatuses, 10_000); return () => window.clearInterval(timer); }, []); const runtimePresentation = (account: AccountDetail) => { if (!account.enabled || account.runtime_state === 'disabled') { return { label: '已停用', badge: 'bg-gray-100 text-gray-500', dot: 'bg-gray-300' }; } switch (account.runtime_state) { case 'online': return { label: '在线', badge: 'bg-green-100 text-green-700', dot: 'bg-green-500' }; case 'starting': case 'connecting': return { label: '连接中', badge: 'bg-blue-100 text-blue-700', dot: 'bg-blue-500' }; case 'reconnecting': return { label: '重连中', badge: 'bg-amber-100 text-amber-700', dot: 'bg-amber-500' }; case 'auth_expired': return { label: '登录已失效', badge: 'bg-red-100 text-red-700', dot: 'bg-red-500' }; case 'verification_required': return { label: '需要验证', badge: 'bg-orange-100 text-orange-700', dot: 'bg-orange-500' }; case 'error': case 'stopped': return { label: '运行异常', badge: 'bg-red-100 text-red-700', dot: 'bg-red-500' }; default: return { label: '状态检测中', badge: 'bg-gray-100 text-gray-600', dot: 'bg-gray-400' }; } }; const handleToggle = async (id: string, currentStatus: boolean) => { await updateAccountStatus(id, !currentStatus); loadAccounts(); }; const handleDelete = async (id: string) => { if (confirm('确认删除该账号吗?')) { await deleteAccount(id); loadAccounts(); } }; const handleRefreshProfile = async (account: AccountDetail) => { setRefreshingProfileId(account.id); try { const res = await refreshAccountProfile(account.id); if (res?.profile_error) { alert('资料刷新失败:' + res.profile_error); } await loadAccounts(); } catch (error: any) { console.error('刷新账号资料失败:', error); alert(error?.message || '刷新账号资料失败,请先重新授权该账号'); } finally { setRefreshingProfileId(''); } }; const openEditModal = (account: AccountDetail) => { setEditingAccount(account); setEditForm({ remark: account.remark || account.note || '', cookie: account.cookie || account.value || '', auto_confirm: account.auto_confirm || false, pause_duration: account.pause_duration || 0, username: account.username || '', login_password: account.login_password || '', show_browser: account.show_browser || false, showLoginPassword: false, }); setActiveModal('edit'); }; const openAIModal = async (account: AccountDetail) => { setEditingAccount(account); setSaving(true); try { const settings = await getAccountAISettings(account.id); setAiSettings({ ai_enabled: settings.ai_enabled ?? false, max_discount_percent: settings.max_discount_percent ?? 10, max_discount_amount: settings.max_discount_amount ?? 100, max_bargain_rounds: settings.max_bargain_rounds ?? 3, custom_prompts: settings.custom_prompts ?? '', }); } catch (e) { console.error('Failed to load AI settings:', e); } finally { setSaving(false); } setActiveModal('ai-settings'); }; const handleSaveEdit = async () => { if (!editingAccount) return; setSaving(true); try { const promises: Promise[] = []; // 更新备注 if (editForm.remark !== (editingAccount.remark || editingAccount.note || '')) { promises.push(updateAccountRemark(editingAccount.id, editForm.remark)); } // 更新Cookie if (editForm.cookie && editForm.cookie !== (editingAccount.cookie || editingAccount.value || '')) { promises.push(updateAccountCookie(editingAccount.id, editForm.cookie)); } // 更新自动确认 if (editForm.auto_confirm !== editingAccount.auto_confirm) { promises.push(updateAccountAutoConfirm(editingAccount.id, editForm.auto_confirm)); } // 更新暂停时长 if (editForm.pause_duration !== (editingAccount.pause_duration || 0)) { promises.push(updateAccountPauseDuration(editingAccount.id, editForm.pause_duration)); } // 更新登录信息 if ( editForm.username !== (editingAccount.username || '') || editForm.login_password !== (editingAccount.login_password || '') || editForm.show_browser !== (editingAccount.show_browser || false) ) { promises.push(updateAccountLoginInfo(editingAccount.id, { username: editForm.username, login_password: editForm.login_password, show_browser: editForm.show_browser, })); } await Promise.all(promises); setActiveModal(null); loadAccounts(); } catch (error) { console.error('更新账号失败:', error); alert('更新失败,请重试'); } finally { setSaving(false); } }; const handleSaveAISettings = async () => { if (!editingAccount) return; setSaving(true); try { await updateAccountAISettings(editingAccount.id, aiSettings); setActiveModal(null); loadAccounts(); } catch (error) { console.error('更新AI设置失败:', error); alert('更新失败,请重试'); } finally { setSaving(false); } }; const persistQRLoginResult = async (cookies: string, unb?: string, target?: AccountDetail | null) => { if (target) { if (unb && unb !== target.id) { const ok = confirm(`扫码返回的账号ID是 ${unb},当前要重新授权的是 ${target.id}。确认用本次扫码结果覆盖当前账号授权吗?`); if (!ok) { throw new Error('已取消覆盖当前账号授权'); } } await updateAccountCookie(target.id, cookies); return target.id; } if (!unb) { throw new Error('扫码结果缺少账号ID,无法添加账号'); } await addAccount(unb, cookies); return unb; }; const startQRLogin = async (target?: AccountDetail) => { const targetAccount = target || null; setQrReauthTarget(targetAccount); setShowQRModal(true); setQrStatus('loading'); setQrCodeUrl(''); setQrSessionId(''); setVerificationUrl(''); setVerificationScreenshot(''); try { const res = await generateQRLogin(); if (res.success && res.qr_code_url && res.session_id) { setQrCodeUrl(res.qr_code_url); setQrSessionId(res.session_id); setQrStatus('waiting'); const interval = setInterval(async () => { const statusRes = await checkQRLoginStatus(res.session_id!); if (statusRes.status === 'success') { clearInterval(interval); setQrStatus('success'); if (statusRes.cookies && statusRes.unb) { try { await persistQRLoginResult(statusRes.cookies, statusRes.unb, targetAccount); } catch (e) { console.error('保存扫码授权失败', e); setQrStatus('error'); } } setTimeout(() => { setShowQRModal(false); loadAccounts(); }, 1000); } else if (statusRes.status === 'scanned') { setQrStatus('waiting'); // 已扫描,继续等待确认 } else if (statusRes.status === 'expired' || statusRes.status === 'cancelled' || statusRes.status === 'error' || statusRes.status === 'not_found') { clearInterval(interval); setQrStatus('error'); } else if (statusRes.status === 'verification_required') { setQrStatus('verification'); setVerificationUrl(statusRes.verification_url || ''); if (statusRes.verification_screenshot) { setVerificationScreenshot(statusRes.verification_screenshot); } } }, 2000); } } catch (e) { setQrStatus('error'); } }; // 用户完成风控验证后,点"我已完成验证"调用后端提取真实 cookie。 const handleCompleteVerification = async () => { if (!qrSessionId) return; setQrStatus('loading'); try { const res = await completeQRVerification(qrSessionId); if (res.success && res.cookies && res.unb) { await persistQRLoginResult(res.cookies, res.unb, qrReauthTarget); setQrStatus('success'); setTimeout(() => { setShowQRModal(false); loadAccounts(); }, 1000); } else { setQrStatus('verification'); alert('验证未完成:' + (res.message || '可能验证尚未通过,请先在验证页面完成验证')); } } catch (e) { setQrStatus('verification'); alert('处理失败:' + (e instanceof Error ? e.message : String(e))); } }; if (loading) return
; const filteredAccounts = accounts.filter(account => { const keyword = accountSearch.trim().toLowerCase(); if (!keyword) return true; return [ account.id, account.nickname, account.remark, account.note, account.username, account.runtime_message, ].some(value => (value || '').toLowerCase().includes(keyword)); }); return (

账号管理

管理您的闲鱼授权账号及设置。建议给账号填写备注,便于多账号区分。

setAccountSearch(event.target.value)} placeholder="搜索昵称 / 备注 / 账号ID" className="ios-input px-4 py-3 rounded-2xl text-sm w-full sm:w-72" />
当前显示 {filteredAccounts.length} / {accounts.length} 个账号
如果某个账号只显示 ID,点该账号右侧“刷新资料”;若刷新失败,先点二维码重新授权。
{/* Account Grid */}
{filteredAccounts.map((account) => { const runtime = runtimePresentation(account); const requiresLogin = account.runtime_state === 'auth_expired' || account.runtime_state === 'verification_required'; return (
{account.avatar_url ? ( {account.nickname ) : (
)}
{account.runtime_state === 'online' && }

{account.nickname || account.remark || `账号 ${account.id.substring(0,6)}...`}

{runtime.label} {account.ai_enabled && ( AI )} {account.profile_error && ( 资料未同步 )}

{account.remark || account.note || '暂无备注'}

ID: {account.id}

{account.runtime_message && account.runtime_state !== 'online' && account.runtime_state !== 'disabled' && (
{account.runtime_message} {requiresLogin && ( )}
)}
{account.auto_confirm && 自动确认发货} {account.pause_duration > 0 && 暂停{account.pause_duration}分钟}
)})} {accounts.length === 0 && (

暂无账号

请点击右上角扫码添加您的闲鱼账号

)} {accounts.length > 0 && filteredAccounts.length === 0 && (

没有匹配的账号

换一个关键词搜索昵称、备注或账号ID。

)}
{/* QR Code Modal */} {showQRModal && createPortal(

{qrReauthTarget ? '重新授权账号' : '扫码添加账号'}

{qrReauthTarget ? `请用闲鱼APP扫码,为「${qrReauthTarget.nickname || qrReauthTarget.remark || qrReauthTarget.id}」刷新授权` : '请打开闲鱼APP扫描下方二维码'}

{qrStatus === 'loading' && } {qrStatus === 'waiting' && QR Code} {qrStatus === 'success' && (
登录成功
)} {qrStatus === 'error' && (
获取失败
)} {qrStatus === 'verification' && (
需要安全验证 程序已在后台打开验证页面,请用手机完成验证,验证通过后将自动登录。 {verificationScreenshot ? ( 验证页面 ) : (
)} 等待手机验证完成,无需手动操作...
)}

二维码有效期为5分钟,请尽快扫码。

, document.body )} {/* 编辑账号弹窗 */} {activeModal === 'edit' && editingAccount && createPortal(

编辑账号

{editingAccount.nickname || editingAccount.remark || editingAccount.id}

{/* 账号ID */}
{/* 备注 */}
setEditForm({ ...editForm, remark: e.target.value })} placeholder="为账号添加备注" className="w-full ios-input px-4 py-3 rounded-xl" />
{/* Cookie */}