Files
live-hub-py/web/frontend/src/pages/HuyaElitePage.tsx
T

542 lines
48 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { MouseEvent } from 'react';
import {
Button, Card, Input, InputNumber, Modal, QRCode, Select, Space, Table, Tag, Tooltip, Typography,
} from 'antd';
import type { TableProps } from 'antd';
import {
CheckCircleOutlined, ColumnWidthOutlined, CopyOutlined, GiftOutlined, ImportOutlined, QrcodeOutlined,
ReloadOutlined, SearchOutlined, SettingOutlined, ShoppingOutlined, StopOutlined, ZoomInOutlined,
} from '@ant-design/icons';
import { huyaApi, type HuyaAccountItem, type HuyaConfig, type HuyaGoodsItem, type HuyaRechargeGoodsItem, type HuyaTaskItem } from '../api/modules';
import HuyaExternalCkImportModal from '../components/HuyaExternalCkImportModal';
import RealtimeLogPanel from '../components/RealtimeLogPanel';
import { usePermissions } from '../hooks/usePermissions';
import { useWebSocketLogs } from '../hooks/useWebSocketLogs';
import { getErrorMessage } from '../utils/error';
import { message } from '../utils/antdMessage';
import { formatTime, formatUnixSeconds } from '../utils/time';
const { Text } = Typography;
const SCOPE = 'elite' as const;
const ACT_ID = 25135;
const DEFAULT_SID = '2203';
const LAYOUT_KEY = 'huya_elite_layout_mode';
// 开通/充值:记住上次选的商品与数量(浏览器本地,换台机器不影响)
const RECHARGE_SPU_KEY = 'huya_elite_recharge_spu';
const RECHARGE_COUNT_KEY = 'huya_elite_recharge_count';
const ELITE_SPU_KEY = 'huya_elite_elite_spu';
// 与后端 ELITE_HANDBOOK_SPU_IDS 对齐:精英宝典单独一块,不和其他开通商品混在一个下拉里
const ELITE_HANDBOOK_SPU_IDS = ['hy-8328015', 'hy-5879340', 'hy-3845257', 'hy-2947756'];
const ELITE_HANDBOOK_NAME_KEYWORD = '精英宝典';
// 单个账号一次可开通的份数上限(与后端 clamp 对齐)
const RECHARGE_COUNT_MAX = 10000;
const TASK_LABELS: Record<string, string> = {
query_act_tasks: '读取宝典任务', get_bind_qr: '获取绑定二维码', query_game_name: '查询游戏角色',
confirm_bind: '确认绑定角色', query_points: '查询积分', refresh_goods: '刷新商品',
exchange_goods: '兑换商品', query_exchange_records: '查询兑换记录', create_recharge_order: '生成开通支付码',
refresh_recharge_goods: '刷新开通商品', query_all: '一键查询(宝典+角色+积分)',
};
const TASK_COLORS: Record<string, string> = {
planned: 'default', pending: 'default', running: 'processing', success: 'success',
failed: 'error', error: 'error', stopped: 'warning', timeout: 'warning',
};
const TASK_STATUS_LABELS: Record<string, string> = {
planned: '已计划', pending: '等待中', running: '执行中', success: '成功',
failed: '失败', error: '异常', stopped: '已停止', timeout: '支付超时',
};
const HUYA_QUICK_ACTIONS = [
{ key: 'query_all', icon: <SearchOutlined /> },
{ key: 'get_bind_qr', icon: <QrcodeOutlined /> },
{ key: 'query_game_name', icon: <SearchOutlined /> },
{ key: 'confirm_bind', icon: <CheckCircleOutlined /> },
{ key: 'query_points', icon: <SearchOutlined /> },
{ key: 'query_act_tasks', icon: <SearchOutlined /> },
{ key: 'refresh_goods', icon: <ReloadOutlined /> },
{ key: 'query_exchange_records', icon: <SearchOutlined /> },
];
function savedInterval(): number {
const value = Number(localStorage.getItem('huya_elite_refresh_interval'));
return Number.isInteger(value) && value >= 5 && value <= 60 ? value : 15;
}
/** 上次选的开通商品(列表里已不存在时会自动回落到第一个)。 */
function savedRechargeSpu(): string {
return localStorage.getItem(RECHARGE_SPU_KEY) || '';
}
/** 上次填的开通数量(后端 clamp 1~10000)。 */
function savedRechargeCount(): number {
const value = Number(localStorage.getItem(RECHARGE_COUNT_KEY));
return Number.isInteger(value) && value >= 1 && value <= RECHARGE_COUNT_MAX ? value : 1;
}
/** 上次选的精英宝典商品(就一个时基本用不上)。 */
function savedEliteSpu(): string {
return localStorage.getItem(ELITE_SPU_KEY) || '';
}
/** 精英宝典(含换过 SKU 的历史 spu)走单独入口,其余商品走「其他开通商品」。 */
function isEliteHandbookGood(item: HuyaRechargeGoodsItem): boolean {
return ELITE_HANDBOOK_SPU_IDS.includes(item.spu_id) || (item.name || '').includes(ELITE_HANDBOOK_NAME_KEYWORD);
}
/** 开通商品顺序:跟虎牙页面一致的 raw_order,其次按 id。 */
function byRechargeOrder(a: HuyaRechargeGoodsItem, b: HuyaRechargeGoodsItem): number {
return Number(a.raw?.raw_order ?? 0) - Number(b.raw?.raw_order ?? 0) || a.id - b.id;
}
/** 开通商品的下拉/展示文案:名称 / 单价 / spu。 */
function rechargeGoodsLabel(item: HuyaRechargeGoodsItem): string {
return `${item.name || item.spu_id} / ${item.price ? `${(item.price / 100).toFixed(2)}元` : '价格动态'} / ${item.spu_id}`;
}
function resultText(task: HuyaTaskItem | undefined, key: string): string {
const value = task?.result?.[key];
return value == null ? '' : String(value);
}
/** 开通支付码是否还需要扫码:已支付或已确认开通就不用再展示了 */
function needsScanPay(task: HuyaTaskItem): boolean {
const result = task.result || {};
return !(result.payment_paid === true || result.elite_opened === true);
}
/**
* 列表「二维码」列的占位文案:扫码这件事做完后就别再挂二维码了(真机反馈:
* 支付成功后那一格还挂着码,容易被当成待支付)。返回 null 表示仍要展示二维码。
*
* 只针对「开通支付码」:绑定二维码那类任务 status=success 只代表码生成成功,
* 客户还没扫,必须继续展示。
*/
function qrDoneLabel(task: HuyaTaskItem): string | null {
if (task.task_type !== 'create_recharge_order') return null;
if (needsScanPay(task)) return null;
return task.result?.elite_opened === true ? '已开通' : '已支付';
}
/**
* 二维码里放什么(优先级,见后端 huya_pay_link 模块头):
* 1. `pay_qr_code` —— 收银台页面里真正的扫码内容 `https://qr.alipay.com/xxx`(约 40 字符),
* 支付宝 App 扫它直接进付款,手机相机扫它也会拉起支付宝;
* 2. `pay_cashier_url` —— 收银台直达地址,但那是 **PC 版**页面(真机反馈:有的安卓机
* 扫开只看到左上角一个小二维码,不触发付款),只在拿不到 ① 时兜底;
* 3. `pay_qr_path` —— 本站短链 `/api/huya/pay/<id>?k=<签名>`,要求本页域名手机能访问(localhost 不行);
* 4. `pay_url` —— 原始网关地址 1600+ 字符,二维码太密扫不动,最后兜底。
*/
function payQrValue(task: HuyaTaskItem): string {
const qrCode = resultText(task, 'pay_qr_code');
if (qrCode) return qrCode;
const cashier = resultText(task, 'pay_cashier_url');
if (cashier) return cashier;
const path = resultText(task, 'pay_qr_path');
return path ? `${window.location.origin}${path}` : resultText(task, 'pay_url');
}
/** 二维码内容指向本机时手机一定扫不开(localhost / 127.0.0.1 / 内网回环)。 */
function isLoopbackUrl(url: string): boolean {
return /^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(:|\/|$)/i.test(url);
}
/**
* CK 失效:一键查询里角色走活动通道,外部导入的 CK 过期后这个接口直接没有回包,
* 后端会打 `result.ck_expired` 标记并把账号状态置为 `ck_expired`(见
* backend/services/huya_runner_elite.py 模块头)。这种行必须红色提醒重新登录/重新导入,
* 不能因为积分、宝典查到了就显示绿色「成功」。
*/
function ckExpired(task: HuyaTaskItem | undefined, row: HuyaAccountItem): boolean {
return task?.result?.ck_expired === true || row.status === 'ck_expired';
}
function latestTask(tasks: HuyaTaskItem[], accountId: number): HuyaTaskItem | undefined {
return tasks.filter((task) => task.account_id === accountId).sort((a, b) => b.id - a.id)[0];
}
function taskQrUrl(task: HuyaTaskItem | undefined): string {
if (!task) return '';
if (task.task_type === 'create_recharge_order') return payQrValue(task);
return resultText(task, 'bind_redirect_url') || resultText(task, 'url');
}
export default function HuyaElitePage() {
const { can } = usePermissions();
const canConfig = can('huya:config');
const canImport = can('huya:import');
const [pool, setPool] = useState<HuyaAccountItem[]>([]);
const [accounts, setAccounts] = useState<HuyaAccountItem[]>([]);
const [selectedIds, setSelectedIds] = useState<number[]>([]);
const [tasks, setTasks] = useState<HuyaTaskItem[]>([]);
const [goods, setGoods] = useState<HuyaGoodsItem[]>([]);
const [selectedGoodsId, setSelectedGoodsId] = useState('');
const [rechargeGoods, setRechargeGoods] = useState<HuyaRechargeGoodsItem[]>([]);
const [selectedRechargeSpu, setSelectedRechargeSpu] = useState(savedRechargeSpu);
// 精英宝典单独一块:和自己的商品选择分开记
const [selectedEliteSpu, setSelectedEliteSpu] = useState(savedEliteSpu);
// 开通/充值数量:一个账号按这个份数下单(后端 payload.count,1~10000),记住上次填的值
const [rechargeCount, setRechargeCount] = useState(savedRechargeCount);
const [search, setSearch] = useState('');
const [loading, setLoading] = useState(false);
const [starting, setStarting] = useState(false);
const [concurrency, setConcurrency] = useState(3);
const [refreshInterval, setRefreshInterval] = useState(savedInterval);
const [layoutMode, setLayoutMode] = useState<'split' | 'stack'>(() => localStorage.getItem(LAYOUT_KEY) === 'stack' ? 'stack' : 'split');
const [activeBatches, setActiveBatches] = useState<string[]>([]);
const [importOpen, setImportOpen] = useState(false);
const [importSearch, setImportSearch] = useState('');
const [importTag, setImportTag] = useState('');
const [importTags, setImportTags] = useState<string[]>([]);
const [importSelected, setImportSelected] = useState<number[]>([]);
const [qrTask, setQrTask] = useState<HuyaTaskItem | null>(null);
// 开通支付码:多选账号时可以一次生成多个码,弹窗里逐个展示(按批次收集)
const [payBatchIds, setPayBatchIds] = useState<string[]>([]);
const [payOpen, setPayOpen] = useState(false);
// 放大扫码用(二维码在弹窗里开到底,手机才好扫)
const [zoomPayTask, setZoomPayTask] = useState<HuyaTaskItem | null>(null);
const [ckImportOpen, setCkImportOpen] = useState(false);
const [config, setConfig] = useState<HuyaConfig | null>(null);
const [configDraft, setConfigDraft] = useState<HuyaConfig | null>(null);
const [configOpen, setConfigOpen] = useState(false);
const [configLoading, setConfigLoading] = useState(false);
const [configSaving, setConfigSaving] = useState(false);
const [contextMenu, setContextMenu] = useState<{ x: number; y: number; accountIds: number[] } | null>(null);
const tasksLoading = useRef(false);
const logs = useWebSocketLogs();
const load = useCallback(async () => {
setLoading(true);
try {
const [poolResult, workbenchResult, goodsResult, rechargeGoodsResult, taskResult] = await Promise.all([
huyaApi.listAccounts({ include_cookie: false }), huyaApi.listWorkbenchAccounts(SCOPE),
huyaApi.listGoods(), huyaApi.listRechargeGoods(), huyaApi.listTasks(undefined, SCOPE),
]);
setPool(poolResult);
const byId = new Map(poolResult.map((item) => [item.id, item]));
let storedIds: number[] = workbenchResult.account_ids;
if (!workbenchResult.configured) {
try { storedIds = JSON.parse(localStorage.getItem('huya_elite_workbench_account_ids') || '[]') as number[]; } catch { storedIds = []; }
}
setAccounts(storedIds.map((id) => byId.get(Number(id))).filter((item): item is HuyaAccountItem => Boolean(item)));
setSelectedIds((prev) => prev.filter((id) => storedIds.includes(id)));
setGoods(goodsResult);
setRechargeGoods(rechargeGoodsResult);
setTasks(taskResult);
} catch (error) { message.error(getErrorMessage(error)); } finally { setLoading(false); }
}, []);
const loadTasks = useCallback(async () => {
if (tasksLoading.current) return;
tasksLoading.current = true;
try { setTasks(await huyaApi.listTasks(undefined, SCOPE)); } catch { /* 下一轮刷新 */ } finally { tasksLoading.current = false; }
}, []);
useEffect(() => { void load(); }, [load]);
useEffect(() => { if (importOpen || ckImportOpen) void huyaApi.listTags().then(setImportTags).catch(() => {}); }, [ckImportOpen, importOpen]);
useEffect(() => {
const active = tasks.some((task) => ['planned', 'pending', 'running'].includes(task.status));
const timer = window.setInterval(() => { void loadTasks(); }, (active ? 3 : refreshInterval) * 1000);
return () => window.clearInterval(timer);
}, [loadTasks, refreshInterval, tasks]);
useEffect(() => {
if (!contextMenu) return undefined;
const close = () => setContextMenu(null);
const onKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') close();
};
window.addEventListener('click', close);
window.addEventListener('resize', close);
window.addEventListener('keydown', onKeyDown);
return () => {
window.removeEventListener('click', close);
window.removeEventListener('resize', close);
window.removeEventListener('keydown', onKeyDown);
};
}, [contextMenu]);
const saveAccounts = async (ids: number[]) => {
const saved = await huyaApi.updateWorkbenchAccounts(ids, SCOPE);
localStorage.setItem('huya_elite_workbench_account_ids', JSON.stringify(saved.account_ids));
const next = saved.account_ids.map((id) => pool.find((item) => item.id === id)).filter((item): item is HuyaAccountItem => Boolean(item));
setAccounts(next);
setSelectedIds((prev) => prev.filter((id) => saved.account_ids.includes(id)));
};
// 开通商品分组:精英宝典(限购主商品,单独一块)与其他商品(币/徽章/令…,带数量那一块)
const rechargeGoodsSorted = [...rechargeGoods].sort(byRechargeOrder);
const eliteRechargeGoods = rechargeGoodsSorted.filter(isEliteHandbookGood);
const otherRechargeGoods = rechargeGoodsSorted.filter((item) => !isEliteHandbookGood(item));
const selectedEliteGoods = eliteRechargeGoods.find((item) => item.spu_id === selectedEliteSpu) || eliteRechargeGoods[0];
const rechargeEliteLimit = Math.max(1, Math.min(RECHARGE_COUNT_MAX, selectedEliteGoods?.buy_limit || RECHARGE_COUNT_MAX));
// 其他开通商品的数量:上限取商品的 buy_limit(限购商品只能 1 份),
// 下单时作为后端 payload.count(1~10000,走 createOrder 的 item_count)。
const selectedRechargeGoods = otherRechargeGoods.find((item) => item.spu_id === selectedRechargeSpu);
const rechargeBuyLimit = Math.max(1, Math.min(RECHARGE_COUNT_MAX, selectedRechargeGoods?.buy_limit || RECHARGE_COUNT_MAX));
const rechargeCountValue = Math.max(1, Math.min(rechargeCount, rechargeBuyLimit));
const rechargeAmountText = selectedRechargeGoods?.price
? `单价 ¥${(selectedRechargeGoods.price / 100).toFixed(2)} × ${rechargeCountValue}`
: '';
// 换商品:按新商品的限购把数量压回合法范围,并把这次选择写进浏览器,下次进来还是它
const selectRechargeGoods = (spu: string) => {
const limit = Math.max(1, Math.min(RECHARGE_COUNT_MAX, otherRechargeGoods.find((item) => item.spu_id === spu)?.buy_limit || RECHARGE_COUNT_MAX));
const nextCount = Math.max(1, Math.min(rechargeCount, limit));
setSelectedRechargeSpu(spu);
setRechargeCount(nextCount);
localStorage.setItem(RECHARGE_SPU_KEY, spu);
localStorage.setItem(RECHARGE_COUNT_KEY, String(nextCount));
};
const selectEliteGoods = (spu: string) => {
setSelectedEliteSpu(spu);
localStorage.setItem(ELITE_SPU_KEY, spu);
};
const changeRechargeCount = (value: number | null) => {
const next = Math.max(1, Math.min(rechargeBuyLimit, Number(value) || 1));
setRechargeCount(next);
localStorage.setItem(RECHARGE_COUNT_KEY, String(next));
};
const startTask = async (taskType: string, accountIds: number[] = selectedIds, rechargeOverride?: { spu: string; count: number }) => {
if (!accountIds.length) { message.warning('请先勾选账号'); return; }
if (taskType === 'exchange_goods' && !selectedGoodsId) { message.warning('请先选择兑换商品'); return; }
if (taskType === 'create_recharge_order' && !rechargeOverride && !selectedRechargeSpu) { message.warning('请先选择开通商品'); return; }
setStarting(true);
try {
const payload = taskType === 'exchange_goods'
? { sid: Number(config?.sid || DEFAULT_SID), product_id: Number(selectedGoodsId), act_id: ACT_ID }
: taskType === 'query_act_tasks' ? { act_id: ACT_ID }
: taskType === 'create_recharge_order' ? (() => {
// 精英宝典那块用 override 传自己的 spu(限购 1 份);其他商品用下拉选的 spu + 数量
const spu = rechargeOverride?.spu || selectedRechargeSpu;
const count = rechargeOverride?.count ?? rechargeCountValue;
const selected = rechargeGoods.find((item) => item.spu_id === spu);
return { spu_id: spu, sku_id: Number(selected?.sku_id || 0), product_name: selected?.name || '精英宝典', count };
})() : {};
// 支付码要「同时弹出多个二维码」:并发必须 >= 账号数,否则排在后面的码要等前面的码付完/超时才开始生成
const batchConcurrency = taskType === 'create_recharge_order'
? Math.min(10, Math.max(concurrency, accountIds.length))
: concurrency;
const created = await huyaApi.createTasks({ account_ids: accountIds, task_type: taskType, handbook_scope: SCOPE, concurrency: batchConcurrency, payload });
setActiveBatches((prev) => [...new Set([...prev, created.batch_id])]);
if (taskType === 'create_recharge_order') {
// 多选账号时每个账号一个支付码:收进同一列表,弹窗里一起展示
setPayBatchIds((prev) => [...new Set([...prev, created.batch_id])]);
setPayOpen(true);
}
logs.connectBatch(created.batch_id, `/api/huya/ws/${created.batch_id}`, {
clear: false,
onTask: (raw) => {
const next = raw as unknown as HuyaTaskItem;
setTasks((prev) => [next, ...prev.filter((item) => item.id !== next.id)].slice(0, 300));
const result = next.result || {};
// 支付弹窗只在「生成开通支付码」和点账号行时打开:多选时每个码都会回包,
// 这里再自动弹会把用户刚关掉的弹窗反复顶出来(码会在弹窗里自动补齐)。
if (next.task_type === 'get_bind_qr' && (result.mini_qrcode_image || result.bind_redirect_url)) setQrTask(next);
},
onResult: () => { setActiveBatches((prev) => prev.filter((id) => id !== created.batch_id)); void load(); },
});
message.success(`已创建 ${created.count} 个任务`);
window.setTimeout(() => { void loadTasks(); }, 400);
} catch (error) { message.error(getErrorMessage(error)); } finally { setStarting(false); }
};
const openSettings = async () => {
if (!canConfig) return;
setConfigOpen(true);
if (config) { setConfigDraft({ ...config }); return; }
setConfigLoading(true);
try { const current = await huyaApi.getConfig(); setConfig(current); setConfigDraft({ ...current }); }
catch (error) { setConfigOpen(false); message.error(getErrorMessage(error)); }
finally { setConfigLoading(false); }
};
const saveConfig = async () => {
if (!configDraft) return;
setConfigSaving(true);
try { const saved = await huyaApi.updateConfig(configDraft); setConfig(saved); setConfigDraft({ ...saved }); setConfigOpen(false); message.success('配置已保存'); }
catch (error) { message.error(getErrorMessage(error)); } finally { setConfigSaving(false); }
};
const stop = async () => {
try { await Promise.all(activeBatches.map((batchId) => huyaApi.stopBatch(batchId))); setActiveBatches([]); message.success('已停止当前批次'); }
catch (error) { message.error(getErrorMessage(error)); }
};
const handleRowContextMenu = (row: HuyaAccountItem, event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
const accountIds = selectedIds.includes(row.id) && selectedIds.length > 1
? selectedIds
: [row.id];
setSelectedIds(accountIds);
setContextMenu({ x: event.clientX, y: event.clientY, accountIds });
};
const runContextAction = (taskType: string) => {
if (!contextMenu) return;
const ids = contextMenu.accountIds;
setContextMenu(null);
void startTask(taskType, ids);
};
const openQrTask = async (task: HuyaTaskItem) => {
setQrTask(task);
try { setQrTask(await huyaApi.getTask(task.id)); } catch { /* 使用列表结果 */ }
};
const filteredAccounts = useMemo(() => {
const value = search.trim().toLowerCase();
return accounts.filter((item) => !value || [item.uid, item.nickname, item.username, item.tag, item.game_name, item.game_phone].some((v) => String(v || '').toLowerCase().includes(value)));
}, [accounts, search]);
const filteredGoods = useMemo(() => goods.map((item) => ({ ...item, label: `${item.name} / ${item.price ?? '-'}分 / ${item.remain_text || '动态库存'}` })), [goods]);
// 精英宝典:通常只有一个商品;换过 SKU 或已下线时回落到当前的第一个(并记住回落结果)
useEffect(() => {
const list = [...rechargeGoods].sort(byRechargeOrder).filter(isEliteHandbookGood);
if (!list.length) return;
if (!list.some((item) => item.spu_id === selectedEliteSpu)) {
setSelectedEliteSpu(list[0].spu_id);
localStorage.setItem(ELITE_SPU_KEY, list[0].spu_id);
}
}, [rechargeGoods, selectedEliteSpu]);
// 其他开通商品:已选商品从列表消失时回落到第一个(并记住回落结果)
useEffect(() => {
const list = [...rechargeGoods].sort(byRechargeOrder).filter((item) => !isEliteHandbookGood(item));
if (!list.length) return;
if (!list.some((item) => item.spu_id === selectedRechargeSpu)) {
setSelectedRechargeSpu(list[0].spu_id);
localStorage.setItem(RECHARGE_SPU_KEY, list[0].spu_id);
}
}, [rechargeGoods, selectedRechargeSpu]);
const exchangeCount = tasks.filter((task) => task.task_type === 'exchange_goods').length;
// 开通支付码:同一批次里每个账号一个码,未支付的排前面;已支付/已开通的只留一行状态
const payTasks = useMemo(() => {
const list = tasks.filter((task) => task.task_type === 'create_recharge_order'
&& payBatchIds.includes(task.batch_id)
&& Boolean(resultText(task, 'pay_url') || resultText(task, 'mini_qrcode_image')));
return [...list].sort((a, b) => Number(needsScanPay(b)) - Number(needsScanPay(a)) || a.id - b.id);
}, [tasks, payBatchIds]);
const payPendingTasks = payTasks.filter(needsScanPay);
const payDoneTasks = payTasks.filter((task) => !needsScanPay(task));
// 多选账号时一次生成多个码:个别账号失败(限购、CK 失效…)要单独点名,否则少一个码看不出原因
const payFailedTasks = useMemo(() => tasks.filter((task) => task.task_type === 'create_recharge_order'
&& payBatchIds.includes(task.batch_id)
&& ['failed', 'error', 'stopped'].includes(task.status)), [tasks, payBatchIds]);
// 还在排队/生成中的码(并发不够时,后面的码要等前面的码付完或超时才轮到)
const payQueuedCount = useMemo(() => tasks.filter((task) => task.task_type === 'create_recharge_order'
&& payBatchIds.includes(task.batch_id)
&& ['planned', 'pending', 'running'].includes(task.status)
&& !resultText(task, 'pay_url')).length, [tasks, payBatchIds]);
const openPayTasks = (batchId?: string) => {
if (batchId) setPayBatchIds((prev) => (prev.includes(batchId) ? prev : [...prev, batchId]));
setPayOpen(true);
};
const payTaskLabel = (task: HuyaTaskItem) => task.account_nickname || task.account_uid || `#${task.account_id}`;
const copyPayLink = async (text: string, label: string) => {
if (!text) { message.warning('没有可复制的链接'); return; }
try { await navigator.clipboard.writeText(text); message.success(`${label}已复制`); }
catch { message.error('复制失败,请手动选中复制'); }
};
// 列宽按比例分配(percent),表头与单元格统一居中,避免左右跳着看
const accountColumns: TableProps<HuyaAccountItem>['columns'] = [
{ title: '#', width: '4%', align: 'center', render: (_value, _row, index) => <Text type="secondary">{index + 1}</Text> },
{ title: '账号', width: '15%', align: 'center', ellipsis: true, render: (_value, row) => <Space direction="vertical" align="center" size={0} style={{ width: '100%' }}><Text strong ellipsis title={row.nickname || row.username || row.uid}>{row.nickname || row.username || row.uid}</Text><Text type="secondary" style={{ fontSize: 12 }} ellipsis title={row.username}>UID {row.uid || '-'}</Text></Space> },
{ title: '手机号', width: '10%', align: 'center', ellipsis: true, render: (_value, row) => row.game_phone || <Text type="secondary">-</Text> },
{ title: '游戏名', width: '13%', align: 'center', ellipsis: true, render: (_value, row) => { const expired = ckExpired(latestTask(tasks, row.id), row); return <Space direction="vertical" align="center" size={0} style={{ width: '100%' }}><Text ellipsis title={row.game_name || row.game_channel}>{row.game_name || <Text type={expired ? 'danger' : 'secondary'}>{expired ? '角色未查到' : '未查询'}</Text>}</Text>{row.game_channel && <Text type="secondary" style={{ fontSize: 12 }} ellipsis>{row.game_channel}</Text>}</Space>; } },
{ title: '精英宝典', width: '13%', align: 'center', ellipsis: true, render: (_value, row) => <Space direction="vertical" align="center" size={0} style={{ width: '100%' }}><Tag color={row.elite_opened === true ? 'success' : row.elite_opened === false ? 'default' : undefined}>{row.elite_opened === true ? '已开通' : row.elite_opened === false ? '未开通' : '未查询'}</Tag>{row.elite_opened === true && row.elite_open_time ? <Text type="secondary" style={{ fontSize: 12 }} ellipsis>{`开通 ${formatUnixSeconds(row.elite_open_time)}`}</Text> : null}{row.elite_expire_time ? <Text type="secondary" style={{ fontSize: 12 }} ellipsis>{`有效期至 ${formatUnixSeconds(row.elite_expire_time)}`}</Text> : null}</Space> },
{ title: '积分', dataIndex: 'points', width: '7%', align: 'center', render: (value: number | null) => value ?? <Text type="secondary">-</Text> },
{ title: '最近操作', width: '25%', align: 'center', ellipsis: true, render: (_value, row) => { const task = latestTask(tasks, row.id); const expired = ckExpired(task, row); return task ? <Space direction="vertical" align="center" size={1} style={{ width: '100%' }}><Text strong ellipsis>{TASK_LABELS[task.task_type] || task.task_type}</Text><Text type={expired ? 'danger' : 'secondary'} ellipsis title={task.message}>{task.message || '-'}</Text><Text type="secondary" style={{ fontSize: 12 }}>{formatTime(task.finished_at || task.created_at)}</Text></Space> : <Text type="secondary">暂无操作</Text>; } },
{ title: '二维码', width: '6%', align: 'center', render: (_value, row) => { const task = latestTask(tasks, row.id); if (!task) return <Text type="secondary">-</Text>; const url = taskQrUrl(task); const image = resultText(task, 'mini_qrcode_image'); if (!url && !image) return <Text type="secondary">-</Text>; const doneLabel = qrDoneLabel(task); if (doneLabel) return <Text type="secondary">{doneLabel}</Text>; return <div onClick={(event) => { event.stopPropagation(); if (!task) return; if (task.task_type === 'create_recharge_order') setZoomPayTask(task); else void openQrTask(task); }} style={{ cursor: 'pointer', display: 'inline-block', lineHeight: 0, background: '#fff', padding: 3, borderRadius: 4 }} title="点击放大扫码">{image ? <img src={`data:image/png;base64,${image}`} alt="二维码" style={{ width: 52, height: 52, objectFit: 'contain' }} /> : <QRCode value={url} size={52} type="svg" errorLevel="L" bordered={false} color="#000" bgColor="#fff" />}</div>; } },
{ title: '状态', width: '7%', align: 'center', render: (_value, row) => { const task = latestTask(tasks, row.id); if (ckExpired(task, row)) return <Tooltip title={`${resultText(task, 'ck_expired_reason') || '角色信息查不到'} —— 请重新登录或重新导入 Cookie`}><Tag color="error">CK 失效</Tag></Tooltip>; const status = task?.status || row.status || ''; return <Tag color={TASK_COLORS[status] || 'default'}>{TASK_STATUS_LABELS[status] || status || '待操作'}</Tag>; } },
];
const operationBody = (
<Space direction="vertical" size={10} style={{ width: '100%' }}>
<div className="huya-operation-section"><div className="huya-operation-title"><QrcodeOutlined /><span>绑定与查询</span></div><div className="huya-action-grid">
<Button size="small" type="primary" icon={<SearchOutlined />} onClick={() => void startTask('query_all')} disabled={starting || !selectedIds.length}>一键查询</Button><Button size="small" icon={<QrcodeOutlined />} onClick={() => void startTask('get_bind_qr')} disabled={starting || !selectedIds.length}>绑定二维码</Button><Button size="small" icon={<SearchOutlined />} onClick={() => void startTask('query_game_name')} disabled={starting || !selectedIds.length}>查询角色</Button><Button size="small" icon={<CheckCircleOutlined />} onClick={() => void startTask('confirm_bind')} disabled={starting || !selectedIds.length}>确认绑定</Button><Button size="small" icon={<SearchOutlined />} onClick={() => void startTask('query_points')} disabled={starting || !selectedIds.length}>刷新积分</Button><Button size="small" onClick={() => void startTask('query_act_tasks')} disabled={starting || !selectedIds.length}>宝典任务</Button><Button size="small" onClick={() => void startTask('query_exchange_records')} disabled={starting || !selectedIds.length}>兑换记录</Button>
</div></div>
<div className="huya-operation-section"><div className="huya-operation-title"><ShoppingOutlined /><span>兑换</span></div><Select size="small" showSearch optionFilterProp="label" value={selectedGoodsId || undefined} onChange={setSelectedGoodsId} options={filteredGoods.map((item) => ({ value: item.product_id, label: item.label }))} placeholder="选择兑换商品" style={{ width: '100%' }} /><div className="huya-action-grid"><Button size="small" icon={<ReloadOutlined />} onClick={() => void startTask('refresh_goods')} disabled={starting || !selectedIds.length}>刷新商品</Button><Button size="small" type="primary" icon={<ShoppingOutlined />} onClick={() => void startTask('exchange_goods')} disabled={starting || !selectedIds.length || !selectedGoodsId}>兑换商品</Button></div></div>
<div className="huya-operation-section"><div className="huya-operation-title"><GiftOutlined /><span>开通宝典</span></div>{eliteRechargeGoods.length > 1 ? <Select size="small" showSearch optionFilterProp="label" value={selectedEliteGoods?.spu_id} onChange={selectEliteGoods} options={eliteRechargeGoods.map((item) => ({ value: item.spu_id, label: rechargeGoodsLabel(item) }))} style={{ width: '100%' }} /> : <Text style={{ fontSize: 12 }} ellipsis>{selectedEliteGoods ? `${rechargeGoodsLabel(selectedEliteGoods)}${rechargeEliteLimit < RECHARGE_COUNT_MAX ? ` · 限购 ${rechargeEliteLimit} 份` : ''}` : '列表里还没有精英宝典,请先刷新开通商品'}</Text>}<Button block size="small" type="primary" icon={<QrcodeOutlined />} onClick={() => { if (selectedEliteGoods) void startTask('create_recharge_order', selectedIds, { spu: selectedEliteGoods.spu_id, count: 1 }); }} disabled={starting || !selectedIds.length || !selectedEliteGoods} style={{ marginTop: 6 }}>确认开通宝典并生成支付码</Button></div>
<div className="huya-operation-section"><div className="huya-operation-title"><ShoppingOutlined /><span>其他开通商品</span></div><Select size="small" showSearch optionFilterProp="label" value={selectedRechargeSpu || undefined} onChange={selectRechargeGoods} options={otherRechargeGoods.map((item) => ({ value: item.spu_id, label: rechargeGoodsLabel(item) }))} placeholder="先刷新开通商品" style={{ width: '100%' }} /><div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6 }}><Text type="secondary" style={{ fontSize: 12 }}>数量</Text><InputNumber size="small" min={1} max={rechargeBuyLimit} value={rechargeCountValue} onChange={changeRechargeCount} style={{ width: 80 }} /><Text type="secondary" style={{ fontSize: 12 }}>{rechargeAmountText}{rechargeBuyLimit < RECHARGE_COUNT_MAX ? ` · 限购 ${rechargeBuyLimit} 份` : ''}</Text></div><Button block size="small" type="primary" icon={<QrcodeOutlined />} onClick={() => void startTask('create_recharge_order')} disabled={starting || !selectedIds.length || !selectedRechargeSpu} style={{ marginTop: 6 }}>{rechargeCountValue > 1 ? `确认充值并生成支付码 ×${rechargeCountValue}` : '确认充值并生成支付码'}</Button><Button block size="small" icon={<ReloadOutlined />} onClick={() => void startTask('refresh_recharge_goods')} disabled={starting || !selectedIds.length} style={{ marginTop: 6 }}>刷新开通商品</Button></div>
<RealtimeLogPanel logs={logs.logs} connected={logs.connected} title="实时日志" emptyText="暂无任务日志" height={150} collapsible defaultVisible={false} />
</Space>
);
const accountsBody = <><Space style={{ marginBottom: 8, width: '100%', justifyContent: 'space-between' }} wrap><Input size="small" allowClear prefix={<SearchOutlined />} placeholder="搜索账号/昵称/游戏名/手机号" value={search} onChange={(event) => setSearch(event.target.value)} style={{ width: 240 }} /><Space><Button size="small" icon={<ImportOutlined />} onClick={() => setImportOpen(true)}>导入账号</Button>{canImport && <Button size="small" icon={<ImportOutlined />} onClick={() => setCkImportOpen(true)}>导入外部 CK</Button>}{selectedIds.length > 0 && <Button size="small" danger onClick={() => void saveAccounts(accounts.map((item) => item.id).filter((id) => !selectedIds.includes(id)))}>移出选中</Button>}</Space></Space><div className="huya-account-table"><Table rowKey="id" size="small" loading={loading} tableLayout="fixed" rowSelection={{ selectedRowKeys: selectedIds, onChange: (keys) => setSelectedIds(keys.map(Number)) }} columns={accountColumns} dataSource={filteredAccounts} locale={{ emptyText: '工作台暂无账号,点击右上角「导入账号」添加' }} pagination={{ pageSize: 20, showSizeChanger: true, showTotal: (total) => `共 ${total} 条` }} scroll={{ y: 'calc(100vh - 300px)' }} onRow={(row) => ({ onClick: () => { const task = latestTask(tasks, row.id); if (!task?.result) return; if (task.task_type === 'get_bind_qr') void openQrTask(task); else if (task.task_type === 'create_recharge_order') openPayTasks(task.batch_id); }, onContextMenu: (event) => handleRowContextMenu(row, event), style: { cursor: 'context-menu' }, title: '右键打开账号动作' })} /></div></>;
const configField = (key: Exclude<keyof HuyaConfig, 'updated_at'>, label: string) => configDraft && <Space key={key} style={{ width: '100%', justifyContent: 'space-between' }}><Text>{label}</Text><Input value={configDraft[key] || ''} onChange={(event) => setConfigDraft({ ...configDraft, [key]: event.target.value })} style={{ width: 300 }} /></Space>;
const contextMenuStyle = contextMenu ? {
position: 'fixed' as const,
zIndex: 1000,
left: Math.max(8, Math.min(contextMenu.x, window.innerWidth - 228)),
top: Math.max(8, Math.min(contextMenu.y, window.innerHeight - 330)),
} : undefined;
const tableStyle = `.huya-operation-section{border:1px solid rgba(128,128,128,.22);border-radius:6px;padding:8px}.huya-operation-title{display:flex;gap:6px;align-items:center;font-weight:600;margin-bottom:8px}.huya-action-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:6px}.huya-account-table{flex:1;min-height:0;overflow:hidden}.huya-account-table .ant-table-wrapper,.huya-account-table .ant-spin-nested-loading,.huya-account-table .ant-spin-container{height:100%}.huya-account-table .ant-table{height:100%;display:flex;flex-direction:column}.huya-account-table .ant-table-container{flex:1;min-height:0;display:flex;flex-direction:column}.huya-account-table .ant-table-header{flex-shrink:0}.huya-account-table .ant-table-body{flex:1;min-height:0;overflow:auto !important}.huya-account-table .ant-table-thead > tr > th,.huya-account-table .ant-table-tbody > tr > td{padding:4px 8px;line-height:20px}.huya-account-table .ant-typography{font-size:12px}.huya-account-table .ant-tag{font-size:11px;line-height:18px;margin-inline-end:0;padding-inline:5px}.huya-account-table .ant-pagination{flex-shrink:0;margin:0;padding:6px 4px 2px;border-top:1px solid rgba(128,128,128,.22)}`;
return <div style={{ height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}><style>{tableStyle}</style>
<Space style={{ justifyContent: 'space-between', width: '100%', marginBottom: 8, flexShrink: 0 }}><div><h2 style={{ margin: 0 }}>虎牙精英宝典工作台</h2><Text type="secondary">绑定、开通、积分与兑换任务</Text></div><Space><Tooltip title={layoutMode === 'split' ? '切换为上下布局' : '切换为左右布局'}><Button icon={<ColumnWidthOutlined />} onClick={() => { const next = layoutMode === 'split' ? 'stack' : 'split'; setLayoutMode(next); localStorage.setItem(LAYOUT_KEY, next); }} /></Tooltip><Button icon={<ReloadOutlined />} onClick={() => void load()} loading={loading}>刷新</Button>{canConfig && <Button icon={<SettingOutlined />} onClick={() => void openSettings()}>设置</Button>}{!!activeBatches.length && <Button danger icon={<StopOutlined />} onClick={() => void stop()}>停止</Button>}</Space></Space>
{layoutMode === 'split' ? <div style={{ flex: 1, minHeight: 0, display: 'flex', gap: 12, overflow: 'hidden' }}><Card size="small" title="账号" extra={<Tag color="blue">已选 {selectedIds.length}/{accounts.length}</Tag>} style={{ flex: 1, minWidth: 0, minHeight: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden' }} styles={{ body: { flex: 1, minHeight: 0, padding: '4px 6px', overflow: 'hidden', display: 'flex', flexDirection: 'column' } }}>{accountsBody}</Card><Card size="small" title="精英宝典操作" extra={<Space size={4}><Text type="secondary">并发</Text><InputNumber size="small" min={1} max={10} value={concurrency} onChange={(value) => setConcurrency(value || 1)} style={{ width: 58 }} /></Space>} style={{ width: 360, flexShrink: 0, minHeight: 0, overflow: 'hidden' }} styles={{ body: { padding: 8, overflowY: 'auto', height: 'calc(100% - 38px)' } }}>{operationBody}</Card></div> : <><Card size="small" title="精英宝典操作" extra={<Space size={4}><Text type="secondary">并发</Text><InputNumber size="small" min={1} max={10} value={concurrency} onChange={(value) => setConcurrency(value || 1)} style={{ width: 58 }} /></Space>} style={{ flexShrink: 0, marginBottom: 12 }} styles={{ body: { padding: 8 } }}>{operationBody}</Card><Card size="small" title="账号" extra={<Tag color="blue">已选 {selectedIds.length}/{accounts.length}</Tag>} style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden' }} styles={{ body: { flex: 1, minHeight: 0, padding: '4px 6px', overflow: 'hidden', display: 'flex', flexDirection: 'column' } }}>{accountsBody}</Card></>}
<Text type="secondary" style={{ fontSize: 12, marginTop: 6 }}>兑换任务 {exchangeCount} 条;勾选账号后可批量执行,账号行支持右键操作。</Text>
{contextMenu && <div style={contextMenuStyle} onClick={(event) => event.stopPropagation()}><Card size="small" title={contextMenu.accountIds.length > 1 ? '批量动作' : '账号动作'} styles={{ body: { padding: 4 } }} style={{ width: 220, boxShadow: '0 4px 12px rgba(0,0,0,0.14)' }}><Space direction="vertical" style={{ width: '100%' }}>{HUYA_QUICK_ACTIONS.map((item) => <Button key={item.key} block size="small" type="text" icon={item.icon} onClick={() => runContextAction(item.key)} disabled={starting} style={{ justifyContent: 'flex-start' }}>{TASK_LABELS[item.key] || item.key}</Button>)}</Space></Card></div>}
<Modal open={qrTask !== null} title="绑定二维码" footer={null} onCancel={() => setQrTask(null)} centered>{qrTask && <div style={{ textAlign: 'center' }}>{resultText(qrTask, 'mini_qrcode_image') ? <img src={`data:image/png;base64,${resultText(qrTask, 'mini_qrcode_image')}`} alt="绑定二维码" style={{ width: 240, height: 240 }} /> : <QRCode value={resultText(qrTask, 'bind_redirect_url') || 'https://zt.huya.com/b02faae1/pc/index.html'} size={240} color="#000" bgColor="#fff" />}<p><Tag color={TASK_COLORS[qrTask.status] || 'default'}>{qrTask.message || qrTask.status}</Tag></p></div>}</Modal>
<Modal
open={payOpen}
title={payTasks.length ? `开通支付码(${payPendingTasks.length} 个待扫码 · 已完成 ${payDoneTasks.length}/${payTasks.length})` : '开通支付码'}
width={920}
centered
onCancel={() => setPayOpen(false)}
footer={<Space><Text type="secondary">多选账号会同时生成多个码并排展示,各自独立等待支付;支付后自动确认开通状态</Text><Button onClick={() => setPayOpen(false)}>关闭</Button><Button onClick={() => { setPayBatchIds([]); setPayOpen(false); }}>清空列表</Button></Space>}
>
{payTasks.length === 0 ? <div style={{ padding: 24, textAlign: 'center' }}><Text type="secondary">正在为选中的账号生成支付码…</Text></div> : <div style={{ maxHeight: '62vh', overflowY: 'auto' }}>
{payQueuedCount > 0 && <div style={{ marginBottom: 10, textAlign: 'left' }}><Text type="secondary" style={{ fontSize: 12 }}>还有 {payQueuedCount} 个账号在排队生成支付码(并发不够时会等已出的码付完/超时,可调大右侧「并发」)</Text></div>}
{payPendingTasks.length > 0 && <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(230px, 1fr))', gap: 12 }}>
{payPendingTasks.map((task) => {
const qrValue = payQrValue(task);
return (
<div key={task.id} style={{ border: '1px solid rgba(128,128,128,.22)', borderRadius: 6, padding: 10, textAlign: 'center' }}>
<div style={{ background: '#fff', padding: 6, borderRadius: 6, lineHeight: 0, display: 'inline-block' }}>{resultText(task, 'mini_qrcode_image') ? <img src={`data:image/png;base64,${resultText(task, 'mini_qrcode_image')}`} alt="支付码" style={{ width: 150, height: 150, objectFit: 'contain' }} /> : <QRCode value={qrValue} size={150} type="svg" errorLevel="L" bordered={false} color="#000" bgColor="#fff" />}</div>
<div><Text strong ellipsis>{payTaskLabel(task)}</Text></div>
<Text type="secondary" style={{ fontSize: 12 }}>UID {task.account_uid || '-'}</Text>
<div><Text type="secondary" style={{ fontSize: 12 }}>{[resultText(task, 'product_name') || '精英宝典', Number(resultText(task, 'count')) > 1 ? `×${resultText(task, 'count')}` : '', resultText(task, 'amount_text')].filter(Boolean).join(' ')}</Text></div>
<div style={{ marginTop: 4 }}><Tag color={TASK_COLORS[task.status] || 'default'}>{resultText(task, 'payment_status_label') || TASK_STATUS_LABELS[task.status] || task.status}</Tag></div>
<Text type="secondary" style={{ fontSize: 12 }} ellipsis title={task.message}>{task.message || '-'}</Text>
{isLoopbackUrl(qrValue) && <div><Text type="warning" style={{ fontSize: 12 }}>二维码是本机地址(localhost),手机扫不开</Text></div>}
<div style={{ marginTop: 6 }}><Space size={6}><Button size="small" icon={<ZoomInOutlined />} onClick={() => setZoomPayTask(task)}>放大扫码</Button><Button size="small" icon={<CopyOutlined />} onClick={() => void copyPayLink(qrValue, '支付链接')}>复制链接</Button></Space></div>
</div>
);
})}
</div>}
{payFailedTasks.length > 0 && <div style={{ marginTop: payPendingTasks.length ? 12 : 0, textAlign: 'left' }}>
<Text type="secondary" style={{ fontSize: 12 }}>生成失败(没有二维码)</Text>
<div style={{ marginTop: 6, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
{payFailedTasks.map((task) => <Tag key={task.id} color="error" title={task.message}>{payTaskLabel(task)} · {task.message || '生成失败'}</Tag>)}
</div>
</div>}
{payDoneTasks.length > 0 && <div style={{ marginTop: payPendingTasks.length ? 12 : 0, textAlign: 'left' }}>
<Text type="secondary" style={{ fontSize: 12 }}>已完成(二维码已收起)</Text>
<div style={{ marginTop: 6, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
{payDoneTasks.map((task) => (
<Tag key={task.id} color={task.result?.elite_opened === true ? 'success' : 'blue'}>{payTaskLabel(task)} · {task.result?.elite_opened === true ? '已开通' : resultText(task, 'payment_status_label') || '已支付'}</Tag>
))}
</div>
</div>}
</div>}
</Modal>
<Modal open={zoomPayTask !== null} title={`扫码支付 · ${zoomPayTask ? payTaskLabel(zoomPayTask) : ''}`} footer={null} onCancel={() => setZoomPayTask(null)} width={680} centered>
{zoomPayTask && <div style={{ textAlign: 'center' }}>
<div style={{ display: 'inline-block', background: '#fff', padding: 16, borderRadius: 8, lineHeight: 0 }}><QRCode value={payQrValue(zoomPayTask)} size={520} type="svg" errorLevel="L" bordered={false} color="#000" bgColor="#fff" /></div>
<p><Space size={8}><Tag color={TASK_COLORS[zoomPayTask.status] || 'default'}>{resultText(zoomPayTask, 'payment_status_label') || zoomPayTask.status}</Tag><Text type="secondary">{resultText(zoomPayTask, 'amount_text')}</Text></Space></p>
<Text type="secondary" style={{ fontSize: 12, wordBreak: 'break-all' }}>{payQrValue(zoomPayTask)}</Text>
<div style={{ marginTop: 10 }}><Space><Button size="small" icon={<CopyOutlined />} onClick={() => void copyPayLink(payQrValue(zoomPayTask), '支付链接')}>复制支付链接</Button><Button size="small" onClick={() => void copyPayLink(resultText(zoomPayTask, 'pay_url'), '原始支付链接')}>复制原始链接</Button></Space></div>
</div>}
</Modal>
<Modal open={importOpen} title="导入精英宝典账号" onCancel={() => setImportOpen(false)} onOk={() => { void saveAccounts([...new Set([...accounts.map((item) => item.id), ...importSelected])]).then(() => { setImportSelected([]); setImportOpen(false); }).catch((error) => message.error(getErrorMessage(error))); }} okText="导入" cancelText="取消"><Input.Search allowClear placeholder="搜索账号" value={importSearch} onChange={(event) => setImportSearch(event.target.value)} style={{ marginBottom: 8 }} /><Select allowClear placeholder="标签" value={importTag || undefined} onChange={(value) => setImportTag(value || '')} options={importTags.map((tag) => ({ value: tag, label: tag }))} style={{ width: '100%', marginBottom: 8 }} /><Table rowKey="id" size="small" dataSource={pool.filter((item) => !accounts.some((current) => current.id === item.id) && (!importSearch || [item.uid, item.nickname, item.username].some((value) => String(value || '').includes(importSearch))) && (!importTag || item.tag === importTag))} columns={[{ title: '账号', render: (_value, row) => row.nickname || row.username || row.uid }, { title: '标签', dataIndex: 'tag' }]} pagination={{ pageSize: 8 }} rowSelection={{ selectedRowKeys: importSelected, onChange: (keys) => setImportSelected(keys.map(Number)) }} /></Modal>
<Modal open={configOpen} title="精英宝典设置" onCancel={() => setConfigOpen(false)} onOk={() => void saveConfig()} confirmLoading={configSaving} okText="保存" cancelText="取消" width={500}>{configLoading ? <div style={{ padding: 24, textAlign: 'center' }}>加载中...</div> : configDraft && <Space direction="vertical" size={10} style={{ width: '100%' }}>{configField('sid', '活动 SID')}{configField('bind_act_id', '绑定活动 ID')}{configField('outer_act_id', '外部活动 ID')}{configField('room_pid', '直播间 PID')}{configField('pay_channel', '支付渠道')}<Space style={{ width: '100%', justifyContent: 'space-between' }}><Text>空闲轮询间隔(秒)</Text><InputNumber min={5} max={60} value={refreshInterval} onChange={(value) => { const next = Math.min(60, Math.max(5, value || 15)); setRefreshInterval(next); localStorage.setItem('huya_elite_refresh_interval', String(next)); }} style={{ width: 300 }} /></Space></Space>}</Modal>
<HuyaExternalCkImportModal open={ckImportOpen} onClose={() => setCkImportOpen(false)} tags={importTags} scope={SCOPE} onImported={(result) => { localStorage.setItem('huya_elite_workbench_account_ids', JSON.stringify(result.account_ids)); void load(); }} />
</div>;
}