import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { Button, Radio, Select, Card, Col, Input, InputNumber, Popconfirm, Row, Space, Statistic, Switch, Table, Tag, Tooltip, Typography, } from 'antd'; import { message } from '../utils/antdMessage'; import type { TableProps } from 'antd'; import { DownloadOutlined, PlayCircleOutlined, ReloadOutlined, StopOutlined } from '@ant-design/icons'; import { accountApi, accountCheckApi, type AccountCheckBatch, type AccountCheckItem } from '../api/modules'; import { formatTime } from '../utils/time'; import { getErrorMessage } from '../utils/error'; const { TextArea } = Input; const { Text, Title } = Typography; const FORM_STORAGE_KEY = 'douyu_account_check_form'; const BATCH_STORAGE_KEY = 'douyu_account_check_batch_id'; const STATUS_LABELS: Record = { pending: '等待', running: '检测中', account_cancelled: '账号已注销', password_wrong: '账号密码错误', account_unverified: '账号未认证', account_verified: '账号已认证', account_auth_unknown: '认证状态未知', error: '检测失败', stopped: '已停止', }; const STATUS_COLORS: Record = { pending: 'default', running: 'processing', account_cancelled: 'error', password_wrong: 'error', account_unverified: 'warning', account_verified: 'success', account_auth_unknown: 'warning', error: 'error', stopped: 'warning', }; const FINISHED_BATCH_STATUS = new Set(['finished', 'stopped', 'error']); const RUNNING_BATCH_STATUS = new Set(['pending', 'running']); function readStoredText() { try { return localStorage.getItem(FORM_STORAGE_KEY) || ''; } catch { return ''; } } function readStoredBatchId() { try { return localStorage.getItem(BATCH_STORAGE_KEY) || ''; } catch { return ''; } } function readStoredNumber(key: string, fallback: number) { try { const raw = localStorage.getItem(key); if (raw === null) return fallback; const value = Number(raw); return Number.isFinite(value) ? value : fallback; } catch { return fallback; } } function downloadBlob(blob: Blob, filename: string) { const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = filename; link.click(); URL.revokeObjectURL(url); } function fileTimestamp() { const d = new Date(); const pad = (n: number) => String(n).padStart(2, '0'); return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}_${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`; } export default function AccountCheckPage() { // 两种来源:手动粘贴(旧,默认)与按账号选择(新)。 // 旧模式**完全保留** —— 包括它的解析、批次、导出逻辑。 const [sourceMode, setSourceMode] = useState<'text' | 'accounts'>('text'); const [selectedAccountIds, setSelectedAccountIds] = useState([]); const [accountOptions, setAccountOptions] = useState<{ value: number; label: string }[]>([]); // 「选择账号」的筛选:与账号列表同一套条件,避免两处口径不一致 const [pickAllMatching, setPickAllMatching] = useState(false); const [pickTag, setPickTag] = useState(''); const [pickStatus, setPickStatus] = useState(''); const [pickCk, setPickCk] = useState(''); const [tagOptions, setTagOptions] = useState([]); const [text, setText] = useState(readStoredText); const [concurrency, setConcurrency] = useState(() => readStoredNumber('account_check_concurrency', 3)); const [maxTotalTime, setMaxTotalTime] = useState(() => readStoredNumber('account_check_max_total_time', 300)); const [maxLoginRetries, setMaxLoginRetries] = useState(() => readStoredNumber('account_check_max_login_retries', 0)); const [useProxy, setUseProxy] = useState(() => localStorage.getItem('account_check_use_proxy') === 'true'); // 登录接口:与登录任务同款选择。默认 wgapi —— 账号检测原来就是写死 wgapi, // 保持不变;收不到邮箱验证码时可以换成 iframe(旧版,邮箱验证走 iframe 接口)。 const [apiStrategy, setApiStrategy] = useState(() => localStorage.getItem('account_check_api_strategy') || 'wgapi'); const navigate = useNavigate(); const [batch, setBatch] = useState(null); const [starting, setStarting] = useState(false); const [refreshing, setRefreshing] = useState(false); const [stopping, setStopping] = useState(false); const [downloading, setDownloading] = useState(false); const restoredBatchRef = useRef(false); const batchId = batch?.batch_id || ''; const isRunning = !!batch && RUNNING_BATCH_STATUS.has(batch.status); const canDownload = !!batch && FINISHED_BATCH_STATUS.has(batch.status); const loadBatchById = useCallback(async (id: string) => { if (!id) return; setRefreshing(true); try { const data = await accountCheckApi.getBatch(id); setBatch(data); localStorage.setItem(BATCH_STORAGE_KEY, data.batch_id); } catch (e: unknown) { const err = getErrorMessage(e); if (err.includes('批次不存在') || err.includes('服务已重启')) { localStorage.removeItem(BATCH_STORAGE_KEY); setBatch(null); message.warning('上次账号检测批次已不存在,已清除恢复记录'); } else { message.error(err); } } finally { setRefreshing(false); } }, []); const refreshBatch = useCallback(async () => { if (!batchId) return; await loadBatchById(batchId); }, [batchId, loadBatchById]); useEffect(() => { localStorage.setItem(FORM_STORAGE_KEY, text); }, [text]); useEffect(() => { localStorage.setItem('account_check_concurrency', String(concurrency)); }, [concurrency]); useEffect(() => { localStorage.setItem('account_check_max_total_time', String(maxTotalTime)); }, [maxTotalTime]); useEffect(() => { localStorage.setItem('account_check_max_login_retries', String(maxLoginRetries)); }, [maxLoginRetries]); useEffect(() => { localStorage.setItem('account_check_use_proxy', String(useProxy)); }, [useProxy]); useEffect(() => { localStorage.setItem('account_check_api_strategy', apiStrategy); }, [apiStrategy]); useEffect(() => { if (restoredBatchRef.current) return; restoredBatchRef.current = true; const storedBatchId = readStoredBatchId(); if (storedBatchId) { loadBatchById(storedBatchId); } }, [loadBatchById]); useEffect(() => { if (!isRunning || !batchId) return undefined; const timer = window.setInterval(() => { refreshBatch(); }, 2000); return () => window.clearInterval(timer); }, [batchId, isRunning, refreshBatch]); const statusCounts = useMemo(() => batch?.status_counts || {}, [batch?.status_counts]); const categoryStats = useMemo(() => [ { title: '已注销', value: statusCounts.account_cancelled || 0 }, { title: '密码错误', value: statusCounts.password_wrong || 0 }, { title: '未认证', value: statusCounts.account_unverified || 0 }, { title: '已认证', value: statusCounts.account_verified || 0 }, ], [statusCounts]); useEffect(() => { if (sourceMode !== 'accounts') return; let alive = true; void (async () => { try { const data = await accountApi.listPaged({ page: 1, page_size: 200, search: '', tag: pickTag || undefined, status: pickStatus || undefined, ck_status: pickCk || undefined, }); if (!alive) return; setAccountOptions( data.items.map((item) => ({ value: item.id, label: `${item.username}(#${item.id})`, })), ); } catch (e: unknown) { message.error(getErrorMessage(e)); } })(); return () => { alive = false; }; }, [sourceMode, pickTag, pickStatus, pickCk]); useEffect(() => { if (sourceMode !== 'accounts' || tagOptions.length > 0) return; void accountApi .listTags() .then(setTagOptions) .catch(() => { // 标签拉不到不影响检测,退化为无标签筛选 }); }, [sourceMode, tagOptions.length]); const handleStart = async () => { if (sourceMode === 'accounts') { if (!pickAllMatching && selectedAccountIds.length === 0) { message.warning('请先选择要检测的账号,或打开「按筛选全选」'); return; } } else if (!text.trim()) { message.warning('请先导入账号'); return; } setStarting(true); try { const data = await accountCheckApi.start({ // 二选一:账号模式不传 text,文本模式不传 account_ids text: sourceMode === 'text' ? text : '', account_ids: sourceMode === 'accounts' && !pickAllMatching ? selectedAccountIds : [], select_all_matching: sourceMode === 'accounts' && pickAllMatching, tag: pickTag, status: pickStatus, ck_status: pickCk, concurrency, max_total_time: maxTotalTime, max_login_retries: maxLoginRetries, use_proxy: useProxy, api_strategy: apiStrategy, }); setBatch(data); localStorage.setItem(BATCH_STORAGE_KEY, data.batch_id); message.success(`账号检测批次已启动,共 ${data.total} 个账号`); } catch (e: unknown) { message.error(getErrorMessage(e)); } finally { setStarting(false); } }; const handleStop = async () => { if (!batchId) return; setStopping(true); try { const result = await accountCheckApi.stop(batchId); message.success(result.message); refreshBatch(); } catch (e: unknown) { message.error(getErrorMessage(e)); } finally { setStopping(false); } }; const handleDownload = async () => { if (!batchId) return; setDownloading(true); try { const blob = await accountCheckApi.download(batchId); downloadBlob(blob instanceof Blob ? blob : new Blob([blob]), `account-check-${fileTimestamp()}.zip`); message.success('已下载压缩包'); } catch (e: unknown) { message.error(getErrorMessage(e)); } finally { setDownloading(false); } }; const columns: TableProps['columns'] = [ { title: '行', dataIndex: 'line', width: 70 }, { title: '账号', dataIndex: 'username', width: 180, ellipsis: true, // 「按账号选择」模式下条目带 account_id → 回链到账号详情, // 一眼从检测结果跳到该账号(结果也会在那里的时间线上)。 render: (username: string, record: AccountCheckItem) => ( record.account_id ? ( ) : username ), }, { title: '邮箱', dataIndex: 'email', width: 220, ellipsis: true }, { title: '状态', dataIndex: 'status', width: 130, render: (status: string) => ( {STATUS_LABELS[status] || status} ), }, { title: '消息', dataIndex: 'message', ellipsis: true }, { title: '完成时间', dataIndex: 'finished_at', width: 180, render: (value: string | null) => formatTime(value), }, ]; return ( 账号检测 {/* 两种来源并存:手动粘贴是旧逻辑,一条没动; 按账号选择是新增的,凭据从库里取、结果写回账号时间线。 */} setSourceMode(event.target.value)} disabled={isRunning} optionType="button" buttonStyle="solid" options={[ { value: 'text', label: '手动输入' }, { value: 'accounts', label: '选择账号' }, ]} /> {sourceMode === 'text' ? (