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

989 lines
65 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 { useNavigate } from 'react-router-dom';
import {
Button, Card, Form, Input, InputNumber, Modal, QRCode, Select, Space, Spin, Table, Tag, Tooltip, Typography,
} from 'antd';
import type { TableProps } from 'antd';
import {
CheckCircleOutlined, ColumnWidthOutlined, CopyOutlined, DownloadOutlined, GiftOutlined, ImportOutlined, PictureOutlined, QrcodeOutlined,
ReloadOutlined, SearchOutlined, SettingOutlined, ShoppingOutlined, StopOutlined, SwapOutlined,
} from '@ant-design/icons';
import { huyaApi, type HuyaAccountItem, type HuyaConfig, type HuyaGoodsItem, type HuyaRechargeGoodsItem, type HuyaTaskItem } from '../api/modules';
import HuyaConfigFields from '../components/HuyaConfigFields';
import HuyaExternalCkImportModal from '../components/HuyaExternalCkImportModal';
import PaymentQrQueue, { type PaymentQrQueueItem } from '../components/PaymentQrQueue';
import RealtimeLogPanel from '../components/RealtimeLogPanel';
import { usePermissions } from '../hooks/usePermissions';
import { useWebSocketLogs } from '../hooks/useWebSocketLogs';
import {
clipboardImageSupported,
copyImageToClipboard,
getExchangeResultImage,
type ExchangeResultImageData,
} from '../utils/exchangeImage';
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 LAYOUT_KEY = 'huya_elite_layout_mode';
const PAGE_SIZE_KEY = 'huya_elite_page_size';
// 开通/充值:记住上次选的商品与数量(浏览器本地,换台机器不影响)
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;
}
/** 账号表格每页条数:用户改过一次后就记住,默认与账号管理页一致为 20。 */
function savedPageSize(): number {
const value = Number(localStorage.getItem(PAGE_SIZE_KEY));
return Number.isInteger(value) && value > 0 && value <= 200 ? value : 20;
}
/** 上次选的开通商品(列表里已不存在时会自动回落到第一个)。 */
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 roleDisplay(task: HuyaTaskItem | undefined, row: HuyaAccountItem) {
const hasRoleSplit = Boolean(
task?.result
&& ('current_role_name' in task.result || 'pending_role_name' in task.result),
);
if (!hasRoleSplit) {
return {
currentName: row.game_name || '',
currentChannel: row.game_channel || '',
pendingName: '',
pendingChannel: '',
};
}
return {
currentName: resultText(task, 'current_role_name'),
currentChannel: resultText(task, 'current_game_channel'),
pendingName: resultText(task, 'pending_role_name'),
pendingChannel: resultText(task, 'pending_game_channel'),
};
}
/** mini_qrcode_image 可能存裸 base64,也可能存 livelink 返回的 data URI;统一成 img src。 */
function miniQrcodeSrc(image: string): string {
return image.startsWith('data:image/') ? image : `data:image/png;base64,${image}`;
}
/** 开通支付码是否还需要扫码:已支付或已确认开通就不用再展示了 */
function needsScanPay(task: HuyaTaskItem): boolean {
const result = task.result || {};
return !(
result.payment_paid === true
|| result.elite_opened === true
|| result.elite_opening === true
);
}
/**
* 列表「二维码」列的占位文案:扫码这件事做完后就别再挂二维码了(真机反馈:
* 支付成功后那一格还挂着码,容易被当成待支付)。返回 null 表示仍要展示二维码。
*
* 只针对「开通支付码」:绑定二维码那类任务 status=success 只代表码生成成功,
* 客户还没扫,必须继续展示。
*/
function qrDoneLabel(task: HuyaTaskItem): string | null {
if (!['create_recharge_order', 'exchange_goods'].includes(task.task_type)) return null;
if (needsScanPay(task)) return null;
if (task.task_type === 'exchange_goods') return '已兑换';
if (task.result?.elite_opening === true) return '开通中';
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 latestRoleTask(tasks: HuyaTaskItem[], accountId: number): HuyaTaskItem | undefined {
return tasks
.filter((task) => task.account_id === accountId)
.filter((task) => ['query_game_name', 'query_all', 'get_bind_qr', 'confirm_bind'].includes(task.task_type)
|| Boolean(task.result && ('current_role_name' in task.result || 'pending_role_name' in task.result)))
.sort((a, b) => b.id - a.id)[0];
}
function taskResultRecords(task: HuyaTaskItem | null | undefined): Record<string, unknown>[] {
const records = task?.result?.records;
return Array.isArray(records)
? records.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === 'object'))
: [];
}
function taskQrUrl(task: HuyaTaskItem | undefined): string {
if (!task) return '';
if (['create_recharge_order', 'exchange_goods'].includes(task.task_type)) {
return payQrValue(task);
}
return resultText(task, 'bind_redirect_url') || resultText(task, 'url');
}
function payTaskLabel(task: HuyaTaskItem): string {
return task.account_nickname || task.account_uid || `#${task.account_id}`;
}
export default function HuyaElitePage() {
const navigate = useNavigate();
const { can } = usePermissions();
const canConfig = can('huya:config');
const canImport = can('huya:import') || can('huya:elite:import_ck');
const canTransferCollab = can('huya:collab:edit');
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 [goodsLoading, setGoodsLoading] = useState(false);
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 [pageSize, setPageSize] = useState(savedPageSize);
const [currentPage, setCurrentPage] = useState(1);
const [loading, setLoading] = useState(false);
const [transferring, setTransferring] = 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 [recordsTask, setRecordsTask] = useState<HuyaTaskItem | null>(null);
const [exchangeImagePreview, setExchangeImagePreview] = useState<{
data: ExchangeResultImageData;
url: string;
blob: Blob;
} | null>(null);
const [exchangeImageLoadingKey, setExchangeImageLoadingKey] = useState<string | null>(null);
const [qrTaskLoading, setQrTaskLoading] = useState(false);
// 小程序码图片独立保存:任务轮询只会更新轻量 tasks,不允许覆盖这张大图。
const [qrImage, setQrImage] = useState('');
// 开通支付码:多选账号时可以一次生成多个码,弹窗里逐个展示(按批次收集)
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 [configForm] = Form.useForm<HuyaConfig>();
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 liveGoodsRequestId = useRef(0);
const qrTaskFetchId = useRef<number | null>(null);
const qrImageCacheRef = useRef<Map<number, string>>(new Map());
const logs = useWebSocketLogs();
const load = useCallback(async () => {
setLoading(true);
try {
const [poolResult, workbenchResult, rechargeGoodsResult, taskResult] = await Promise.all([
huyaApi.listAccounts({ include_cookie: false }), huyaApi.listWorkbenchAccounts(SCOPE),
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)));
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; }
}, []);
const loadLiveGoods = useCallback(async (accountId: number | null) => {
const requestId = ++liveGoodsRequestId.current;
if (!accountId) {
setGoods([]);
setSelectedGoodsId('');
return;
}
setGoodsLoading(true);
try {
const result = await huyaApi.listLiveGoods(accountId);
if (liveGoodsRequestId.current !== requestId) return;
setGoods(result);
setSelectedGoodsId((current) => (
result.some((item) => item.product_id === current)
? current
: result[0]?.product_id || ''
));
} catch (error) {
if (liveGoodsRequestId.current !== requestId) return;
setGoods([]);
setSelectedGoodsId('');
message.error(`实时商品加载失败:${getErrorMessage(error)}`);
} finally {
if (liveGoodsRequestId.current === requestId) setGoodsLoading(false);
}
}, []);
const goodsAccountId = selectedIds[0] ?? accounts[0]?.id ?? null;
useEffect(() => { void loadLiveGoods(goodsAccountId); }, [goodsAccountId, loadLiveGoods]);
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 transferToCollab = async () => {
if (selectedIds.length !== 1) {
message.warning('一次只能选择一个账号转入外部单协作');
return;
}
const accountId = selectedIds[0];
const account = accounts.find((item) => item.id === accountId);
if (account && account.has_cookie === false) {
message.warning('该账号没有可用 Cookie,不能转入外部单协作');
return;
}
setTransferring(true);
try {
const result = await huyaApi.transferWorkbenchToCollab(accountId);
message.success('已从精英宝典工作台移除,正在打开外部单协作');
navigate('/huya/collab', {
replace: true,
state: { transferCk: result.ck_text },
});
} catch (error) {
setTransferring(false);
message.error(getErrorMessage(error));
}
};
// 开通商品分组:精英宝典(限购主商品,单独一块)与其他商品(币/徽章/令…,带数量那一块)
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'
? {
product_id: selectedGoodsId,
product_name: goods.find((item) => item.product_id === selectedGoodsId)?.name || '',
pay_channel: config?.pay_channel || '',
}
: 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 || {}) as Record<string, unknown>;
// 积分兑换只有积分不足时才会生成支付码;直兑任务不弹空支付窗。
if (
next.task_type === 'exchange_goods'
&& (result.pay_url || result.pay_qr_code || result.mini_qrcode_image)
) {
setPayBatchIds((prev) => [...new Set([...prev, created.batch_id])]);
setPayOpen(true);
}
// 开通支付码只在批次创建时打开弹窗;后续回包不能反复把用户关掉的弹窗顶出来。
if (next.task_type === 'get_bind_qr') {
if (result.mini_qrcode_image) {
const directImage = String(result.mini_qrcode_image);
qrImageCacheRef.current.set(next.id, directImage);
setQrImage(directImage);
setQrTask(next);
} else if (result.has_mini_qrcode && qrTaskFetchId.current !== next.id) {
// WS 只送 has_mini_qrcode,真实小程序码体积大,必须按详情接口取。
qrTaskFetchId.current = next.id;
setQrImage('');
setQrTaskLoading(true);
setQrTask(next);
void huyaApi.getTask(next.id).then((detail) => {
const image = resultText(detail, 'mini_qrcode_image');
if (image) {
qrImageCacheRef.current.set(detail.id, image);
setQrImage(image);
}
setQrTask((current) => (current && current.id === detail.id ? detail : current));
}).catch(() => {}).finally(() => setQrTaskLoading(false));
} else if (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);
setConfigLoading(true);
try {
const current = await huyaApi.getConfig();
setConfig(current);
configForm.setFieldsValue(current);
}
catch (error) { setConfigOpen(false); message.error(getErrorMessage(error)); }
finally { setConfigLoading(false); }
};
const saveConfig = async () => {
setConfigSaving(true);
try {
const values = await configForm.validateFields();
const saved = await huyaApi.updateConfig(values);
setConfig(saved);
configForm.setFieldsValue(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) => {
const currentImage = resultText(task, 'mini_qrcode_image');
const cachedImage = currentImage || qrImageCacheRef.current.get(task.id) || '';
// 图片是独立 state,轮询/任务对象刷新不会把它清掉。
setQrImage(cachedImage);
setQrTask(task);
if (currentImage) {
qrImageCacheRef.current.set(task.id, currentImage);
return;
}
if (cachedImage) return;
if (task.result?.has_mini_qrcode !== true) return;
setQrTaskLoading(true);
try {
const detail = await huyaApi.getTask(task.id);
const image = resultText(detail, 'mini_qrcode_image');
if (image) {
qrImageCacheRef.current.set(detail.id, image);
setQrImage((current) => current || image);
}
setQrTask((current) => (current && current.id === detail.id ? detail : current));
} catch { /* 使用列表结果 */ } finally { setQrTaskLoading(false); }
};
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 currentPageIds = useMemo(() => {
const start = (currentPage - 1) * pageSize;
return filteredAccounts.slice(start, start + pageSize).map((item) => item.id);
}, [currentPage, filteredAccounts, pageSize]);
const selectCurrentPage = () => {
setSelectedIds((prev) => Array.from(new Set([...prev, ...currentPageIds])));
};
const invertCurrentPage = () => {
setSelectedIds((prev) => {
const selected = new Set(prev);
const page = new Set(currentPageIds);
const kept = prev.filter((id) => !page.has(id));
const added = currentPageIds.filter((id) => !selected.has(id));
return [...kept, ...added];
});
};
useEffect(() => {
const totalPages = Math.max(1, Math.ceil(filteredAccounts.length / pageSize));
if (currentPage > totalPages) setCurrentPage(totalPages);
}, [currentPage, filteredAccounts.length, pageSize]);
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 payAllTasks = useMemo(() => tasks.filter((task) => ['create_recharge_order', 'exchange_goods'].includes(task.task_type)
&& payBatchIds.includes(task.batch_id)
&& Boolean(resultText(task, 'pay_url') || resultText(task, 'mini_qrcode_image'))), [tasks, payBatchIds]);
const payTasks = useMemo(() => payAllTasks.filter(needsScanPay), [payAllTasks]);
const payDoneCount = payAllTasks.length - payTasks.length;
const payQrTaskIds = useMemo(() => new Set(payAllTasks.map((task) => task.id)), [payAllTasks]);
// 多选账号时一次生成多个码:个别账号失败(限购、CK 失效…)要单独点名,否则少一个码看不出原因
const payFailedTasks = useMemo(() => tasks.filter((task) => ['create_recharge_order', 'exchange_goods'].includes(task.task_type)
&& payBatchIds.includes(task.batch_id)
&& !payQrTaskIds.has(task.id)
&& ['failed', 'error', 'stopped'].includes(task.status)), [payBatchIds, payQrTaskIds, tasks]);
// 还在排队/生成中的码(并发不够时,后面的码要等前面的码付完或超时才轮到)
const payQueuedCount = useMemo(() => tasks.filter((task) => ['create_recharge_order', 'exchange_goods'].includes(task.task_type)
&& payBatchIds.includes(task.batch_id)
&& ['planned', 'pending', 'running'].includes(task.status)
&& !resultText(task, 'pay_url')).length, [tasks, payBatchIds]);
const payTaskById = useMemo(() => new Map(payAllTasks.map((task) => [task.id, task])), [payAllTasks]);
const payQueueItems = useMemo<PaymentQrQueueItem[]>(() => {
const pending = payTasks
.map((task) => ({
key: task.id,
title: payTaskLabel(task),
subtitle: `UID ${task.account_uid || '-'}`,
description: [resultText(task, 'product_name') || '精英宝典', Number(resultText(task, 'count')) > 1 ? `×${resultText(task, 'count')}` : '', resultText(task, 'amount_text')].filter(Boolean).join(' '),
phase: 'ready' as const,
qrValue: payQrValue(task),
qrImage: resultText(task, 'mini_qrcode_image') ? miniQrcodeSrc(resultText(task, 'mini_qrcode_image')) : '',
copyValue: payQrValue(task),
statusLabel: resultText(task, 'payment_status_label') || TASK_STATUS_LABELS[task.status] || task.status,
statusColor: TASK_COLORS[task.status] || 'default',
warning: isLoopbackUrl(payQrValue(task)) ? '二维码是本机地址(localhost),手机无法扫码' : '',
}))
.sort((a, b) => Number(a.key) - Number(b.key));
const queued = tasks
.filter((task) => ['create_recharge_order', 'exchange_goods'].includes(task.task_type)
&& payBatchIds.includes(task.batch_id)
&& ['planned', 'pending', 'running'].includes(task.status)
&& !resultText(task, 'pay_url'))
.map((task) => ({
key: `queued-${task.id}`,
title: payTaskLabel(task),
subtitle: `UID ${task.account_uid || '-'}`,
phase: task.status === 'running' ? 'generating' as const : 'queued' as const,
}));
const failed = payFailedTasks.map((task) => ({
key: `failed-${task.id}`,
title: payTaskLabel(task),
subtitle: `UID ${task.account_uid || '-'}`,
phase: 'error' as const,
error: task.message || '支付码生成失败',
}));
return [...pending, ...queued, ...failed];
}, [payBatchIds, payFailedTasks, payTasks, tasks]);
const openPayTasks = (batchId?: string) => {
if (batchId) setPayBatchIds((prev) => (prev.includes(batchId) ? prev : [...prev, batchId]));
setPayOpen(true);
};
const copyPayLink = async (text: string, label: string) => {
if (!text) { message.warning('没有可复制的链接'); return; }
try { await navigator.clipboard.writeText(text); message.success(`${label}已复制`); }
catch { message.error('复制失败,请手动选中复制'); }
};
const exchangeRecordImageData = (
record: Record<string, unknown>,
index: number,
): ExchangeResultImageData => {
const snapshot = (
recordsTask?.result?.account_snapshot
&& typeof recordsTask.result.account_snapshot === 'object'
)
? recordsTask.result.account_snapshot as Record<string, unknown>
: {};
const account = accounts.find((item) => item.id === recordsTask?.account_id);
const recordKey = String(record.record_id || record.order_id || index);
return {
key: `huya:${recordsTask?.id || 'records'}:${recordKey}`,
goodsName: String(record.prize_name || '未知商品'),
goodsPic: String(record.icon || ''),
roleName: String(snapshot.game_name || account?.game_name || ''),
channel: String(snapshot.game_channel || account?.game_channel || ''),
exchangeTime: String(record.exchange_time_text || ''),
statusText: String(record.status_label || '兑换成功'),
footerText: '虎牙精英宝典兑换记录凭证 · 数据来自官方兑换记录',
};
};
const generateExchangeRecordImage = async (
record: Record<string, unknown>,
index: number,
) => {
const data = exchangeRecordImageData(record, index);
const key = String(data.key);
setExchangeImageLoadingKey(key);
try {
const generated = await getExchangeResultImage(data);
setExchangeImagePreview({ data, url: generated.url, blob: generated.blob });
} catch (error) {
message.error(`兑换结果图生成失败:${getErrorMessage(error)}`);
} finally {
setExchangeImageLoadingKey(null);
}
};
const copyExchangeRecordImage = async () => {
if (!exchangeImagePreview) return;
try {
await copyImageToClipboard(exchangeImagePreview.blob);
message.success('兑换结果图已复制');
} catch (error) {
if (clipboardImageSupported()) {
message.error(`复制图片失败:${getErrorMessage(error)}`);
} else {
message.warning('当前浏览器不支持复制图片,请使用“下载图片”');
}
}
};
const downloadExchangeRecordImage = () => {
if (!exchangeImagePreview) return;
const link = document.createElement('a');
link.href = exchangeImagePreview.url;
link.download = `虎牙兑换凭证-${exchangeImagePreview.data.goodsName}.png`;
link.click();
};
const viewedRecords = taskResultRecords(recordsTask);
const exchangeRecordColumns: TableProps<Record<string, unknown>>['columns'] = [
{
title: '商品',
dataIndex: 'prize_name',
width: 210,
render: (value: unknown) => String(value || '-'),
},
{
title: '积分',
dataIndex: 'score',
width: 90,
align: 'right',
render: (value: unknown) => Number(value || 0).toLocaleString(),
},
{
title: '兑换时间',
dataIndex: 'exchange_time',
width: 180,
render: (value: unknown, record) => {
const text = record.exchange_time_text;
if (typeof text === 'string' && text) return text;
const timestamp = Number(value || 0);
return timestamp > 0 ? formatUnixSeconds(timestamp) : '-';
},
},
{
title: '发放状态',
dataIndex: 'status_label',
width: 100,
align: 'center',
render: (value: unknown, record) => {
const label = String(value || record.prize_status || '-');
return <Tag color={label === '已发放' ? 'success' : 'default'}>{label}</Tag>;
},
},
{
title: '订单号',
dataIndex: 'order_id',
width: 240,
ellipsis: true,
render: (value: unknown) =>
value ? <Text copyable={{ text: String(value) }}>{String(value)}</Text> : '-',
},
{
title: '结果图',
width: 110,
align: 'center',
render: (_value: unknown, record, index) => {
const key = String(record.record_id || record.order_id || index);
return (
<Button
size="small"
type="link"
icon={<PictureOutlined />}
loading={exchangeImageLoadingKey === `huya:${recordsTask?.id || 'records'}:${key}`}
onClick={() => void generateExchangeRecordImage(record, index)}
>
结果图
</Button>
);
},
},
];
// 列宽按比例分配(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: '20%',
align: 'center',
ellipsis: true,
render: (_value, row) => {
const task = latestTask(tasks, row.id);
const roleTask = latestRoleTask(tasks, row.id);
const expired = ckExpired(task, row);
const role = roleDisplay(roleTask, row);
const hasRoleSplit = Boolean(
roleTask?.result
&& ('current_role_name' in roleTask.result || 'pending_role_name' in roleTask.result),
);
return (
<Space direction="vertical" align="center" size={1} style={{ width: '100%' }}>
<Text ellipsis title={role.currentName || role.currentChannel}>
{role.currentName || (
<Text type={expired ? 'danger' : 'secondary'}>
{expired ? '角色未查到' : hasRoleSplit ? '当前未绑定' : '未查询'}
</Text>
)}
</Text>
{role.currentChannel && <Text type="secondary" style={{ fontSize: 12 }} ellipsis>{role.currentChannel}</Text>}
{role.pendingName && (
<>
<Tag color="processing" style={{ marginInlineEnd: 0 }}>待确认 {role.pendingName}</Tag>
{role.pendingChannel && <Text type="secondary" style={{ fontSize: 12 }} ellipsis>{role.pendingChannel}</Text>}
</>
)}
</Space>
);
},
},
{ title: '精英宝典', width: '13%', align: 'center', ellipsis: true, render: (_value, row) => { const task = latestTask(tasks, row.id); const opening = task?.result?.elite_opening === true; return <Space direction="vertical" align="center" size={0} style={{ width: '100%' }}><Tag color={opening ? 'processing' : row.elite_opened === true ? 'success' : row.elite_opened === false ? 'default' : undefined}>{opening ? '开通中' : 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: '18%', align: 'center', ellipsis: true, render: (_value, row) => { const task = latestTask(tasks, row.id); const expired = ckExpired(task, row); const records = taskResultRecords(task); 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>{task.task_type === 'query_exchange_records' && records.length > 0 && <Button size="small" type="link" onClick={(event) => { event.stopPropagation(); setRecordsTask(task); }}>查看记录</Button>}</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 (task.task_type === 'get_bind_qr' && !image) { const hasMini = task.result?.has_mini_qrcode === true; if (!hasMini) return <Text type="secondary">-</Text>; return <div onClick={(event) => { event.stopPropagation(); void openQrTask(task); }} style={{ cursor: 'pointer', display: 'inline-block', lineHeight: 0, background: '#fff', padding: 6, borderRadius: 4 }} title="点击查看小程序码"><QrcodeOutlined style={{ fontSize: 26, color: '#000' }} /></div>; } 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 (['create_recharge_order', 'exchange_goods'].includes(task.task_type)) setZoomPayTask(task); else void openQrTask(task); }} style={{ cursor: 'pointer', display: 'inline-block', lineHeight: 0, background: '#fff', padding: 3, borderRadius: 4 }} title="点击放大扫码">{image ? <img src={miniQrcodeSrc(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" loading={goodsLoading} disabled={!goodsAccountId || goodsLoading || !goods.length} value={selectedGoodsId || undefined} onChange={setSelectedGoodsId} options={filteredGoods.map((item) => ({ value: item.product_id, label: item.label }))} placeholder={goodsLoading ? '正在读取实时商品' : !goodsAccountId ? '请先选择账号' : '暂无实时商品'} style={{ width: '100%' }} /><div className="huya-action-grid"><Button size="small" icon={<ReloadOutlined />} loading={goodsLoading} onClick={() => void loadLiveGoods(goodsAccountId)} disabled={starting || !goodsAccountId || goodsLoading}>刷新商品</Button><Button size="small" type="primary" icon={<ShoppingOutlined />} onClick={() => void startTask('exchange_goods')} disabled={starting || !selectedIds.length || !selectedGoodsId || goodsLoading}>兑换商品</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); setCurrentPage(1); }} style={{ width: 240 }} /><Space><Button size="small" onClick={selectCurrentPage} disabled={!currentPageIds.length}>全选本页</Button><Button size="small" onClick={invertCurrentPage} disabled={!currentPageIds.length}>反选本页</Button><Button size="small" onClick={() => setSelectedIds([])} disabled={!selectedIds.length}>清空选择</Button><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>}{canTransferCollab && selectedIds.length === 1 && <Button size="small" icon={<SwapOutlined />} loading={transferring} onClick={() => void transferToCollab()}>转入外部单协作</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)), preserveSelectedRowKeys: true }} columns={accountColumns} dataSource={filteredAccounts} locale={{ emptyText: '工作台暂无账号,点击右上角「导入账号」添加' }} pagination={{ current: currentPage, pageSize, total: filteredAccounts.length, showSizeChanger: true, showTotal: (total) => `共 ${total} 条`, onChange: (page, size) => { setCurrentPage(page); if (size !== pageSize) { setPageSize(size); localStorage.setItem(PAGE_SIZE_KEY, String(size)); setCurrentPage(1); } } }} 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 === 'query_exchange_records' && taskResultRecords(task).length > 0) setRecordsTask(task); else if (['create_recharge_order', 'exchange_goods'].includes(task.task_type)) openPayTasks(task.batch_id); }, onContextMenu: (event) => handleRowContextMenu(row, event), style: { cursor: 'context-menu' }, title: '右键打开账号动作' })} /></div></>;
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;display:flex;overflow:hidden}.huya-account-table .ant-table-wrapper,.huya-account-table .ant-spin,.huya-account-table .ant-spin-nested-loading,.huya-account-table .ant-spin-container{flex:1 1 auto;min-width:0;min-height:0;display:flex;flex-direction:column}.huya-account-table .ant-table{flex:1 1 auto;min-height:0;display:flex;flex-direction:column}.huya-account-table .ant-table-container{flex:1 1 auto;min-height:0;display:flex;flex-direction:column}.huya-account-table .ant-table-header{flex:0 0 auto}.huya-account-table .ant-table-body{flex:1 1 auto;min-height:0;max-height:none !important;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:0 0 auto;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); setQrImage(''); }} centered>{qrTask && <div style={{ textAlign: 'center' }}>{qrImage ? <img src={miniQrcodeSrc(qrImage)} alt="绑定二维码" style={{ width: 240, height: 240, background: '#fff', padding: 12, boxSizing: 'border-box', borderRadius: 8 }} /> : qrTask.result?.has_mini_qrcode === true ? <div style={{ width: 240, height: 240, display: 'grid', placeItems: 'center', background: '#fff', borderRadius: 8 }}>{qrTaskLoading ? <Spin size="large" /> : <Text type="secondary">正在获取小程序码…</Text>}</div> : <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={recordsTask !== null}
title={`兑换记录 · ${recordsTask?.account_nickname || recordsTask?.account_uid || ''}`}
footer={null}
onCancel={() => setRecordsTask(null)}
width={980}
centered
>
<Space orientation="vertical" size={12} style={{ width: '100%' }}>
<Space wrap>
<Tag color="blue">共 {viewedRecords.length} 条</Tag>
<Tag>活动 SID {String(recordsTask?.result?.sid || '-')}</Tag>
{recordsTask?.message ? <Text type="secondary">{recordsTask.message}</Text> : null}
</Space>
<Table
rowKey={(record, index) => String(record.record_id || record.order_id || index)}
size="small"
columns={exchangeRecordColumns}
dataSource={viewedRecords}
pagination={{
pageSize: 10,
showSizeChanger: false,
showTotal: (total) => `共 ${total} 条`,
}}
scroll={{ x: 930 }}
/>
</Space>
</Modal>
<Modal
open={exchangeImagePreview !== null}
title="兑换结果图"
width={390}
centered
footer={null}
onCancel={() => setExchangeImagePreview(null)}
>
{exchangeImagePreview && (
<Space direction="vertical" size={12} align="center" style={{ width: '100%' }}>
<img
src={exchangeImagePreview.url}
alt="兑换结果"
style={{ width: '100%', borderRadius: 8, display: 'block' }}
/>
<Space wrap style={{ justifyContent: 'center' }}>
<Button icon={<CopyOutlined />} onClick={() => void copyExchangeRecordImage()}>
复制图片
</Button>
<Button icon={<DownloadOutlined />} onClick={downloadExchangeRecordImage}>
下载图片
</Button>
<Button onClick={() => setExchangeImagePreview(null)}>关闭</Button>
</Space>
</Space>
)}
</Modal>
<Modal
open={payOpen}
title={`支付码${payQueueItems.length ? `(${payTasks.length} 个待扫码${payQueuedCount ? ` · ${payQueuedCount} 个排队中` : ''}${payDoneCount ? ` · ${payDoneCount} 个已支付` : ''})` : ''}`}
width={920}
centered
onCancel={() => setPayOpen(false)}
footer={<Space><Text type="secondary">多选账号会同时生成多个码并排展示,各自独立等待支付;支付后自动确认开通状态</Text><Button onClick={() => setPayOpen(false)}>关闭</Button><Button onClick={() => { setPayBatchIds([]); setPayOpen(false); }}>清空列表</Button></Space>}
>
<PaymentQrQueue
items={payQueueItems}
emptyText={payDoneCount > 0 ? '待扫码队列已清空,支付完成的账号已自动移除' : '当前没有待扫码支付码'}
queuedText="还有账号在排队生成支付码"
onZoom={(item) => {
const task = payTaskById.get(Number(item.key));
if (task) setZoomPayTask(task);
}}
onCopy={(item) => void copyPayLink(item.copyValue || item.qrValue || '', '支付链接')}
/>
</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={680}>{configLoading ? <div style={{ padding: 24, textAlign: 'center' }}>加载中...</div> : <Space direction="vertical" size={10} style={{ width: '100%' }}><Form form={configForm} layout="vertical"><HuyaConfigFields /></Form><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>;
}