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 = { 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 = { planned: 'default', pending: 'default', running: 'processing', success: 'success', failed: 'error', error: 'error', stopped: 'warning', timeout: 'warning', }; const TASK_STATUS_LABELS: Record = { planned: '已计划', pending: '等待中', running: '执行中', success: '成功', failed: '失败', error: '异常', stopped: '已停止', timeout: '支付超时', }; const HUYA_QUICK_ACTIONS = [ { key: 'query_all', icon: }, { key: 'get_bind_qr', icon: }, { key: 'query_game_name', icon: }, { key: 'confirm_bind', icon: }, { key: 'query_points', icon: }, { key: 'query_act_tasks', icon: }, { key: 'refresh_goods', icon: }, { key: 'query_exchange_records', icon: }, ]; 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/?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[] { const records = task?.result?.records; return Array.isArray(records) ? records.filter((item): item is Record => 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([]); const [accounts, setAccounts] = useState([]); const [selectedIds, setSelectedIds] = useState([]); const [tasks, setTasks] = useState([]); const [goods, setGoods] = useState([]); const [goodsLoading, setGoodsLoading] = useState(false); const [selectedGoodsId, setSelectedGoodsId] = useState(''); const [rechargeGoods, setRechargeGoods] = useState([]); 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([]); const [importOpen, setImportOpen] = useState(false); const [importSearch, setImportSearch] = useState(''); const [importTag, setImportTag] = useState(''); const [importTags, setImportTags] = useState([]); const [importSelected, setImportSelected] = useState([]); const [qrTask, setQrTask] = useState(null); const [recordsTask, setRecordsTask] = useState(null); const [exchangeImagePreview, setExchangeImagePreview] = useState<{ data: ExchangeResultImageData; url: string; blob: Blob; } | null>(null); const [exchangeImageLoadingKey, setExchangeImageLoadingKey] = useState(null); const [qrTaskLoading, setQrTaskLoading] = useState(false); // 小程序码图片独立保存:任务轮询只会更新轻量 tasks,不允许覆盖这张大图。 const [qrImage, setQrImage] = useState(''); // 开通支付码:多选账号时可以一次生成多个码,弹窗里逐个展示(按批次收集) const [payBatchIds, setPayBatchIds] = useState([]); const [payOpen, setPayOpen] = useState(false); // 放大扫码用(二维码在弹窗里开到底,手机才好扫) const [zoomPayTask, setZoomPayTask] = useState(null); const [ckImportOpen, setCkImportOpen] = useState(false); const [config, setConfig] = useState(null); const [configForm] = Form.useForm(); 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(null); const qrImageCacheRef = useRef>(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; // 积分兑换只有积分不足时才会生成支付码;直兑任务不弹空支付窗。 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(() => { 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, index: number, ): ExchangeResultImageData => { const snapshot = ( recordsTask?.result?.account_snapshot && typeof recordsTask.result.account_snapshot === 'object' ) ? recordsTask.result.account_snapshot as Record : {}; 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, 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>['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 {label}; }, }, { title: '订单号', dataIndex: 'order_id', width: 240, ellipsis: true, render: (value: unknown) => value ? {String(value)} : '-', }, { title: '结果图', width: 110, align: 'center', render: (_value: unknown, record, index) => { const key = String(record.record_id || record.order_id || index); return ( ); }, }, ]; // 列宽按比例分配(percent),表头与单元格统一居中,避免左右跳着看 const accountColumns: TableProps['columns'] = [ { title: '#', width: '4%', align: 'center', render: (_value, _row, index) => {index + 1} }, { title: '账号', width: '15%', align: 'center', ellipsis: true, render: (_value, row) => {row.nickname || row.username || row.uid}UID {row.uid || '-'} }, { title: '手机号', width: '10%', align: 'center', ellipsis: true, render: (_value, row) => row.game_phone || - }, { 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 ( {role.currentName || ( {expired ? '角色未查到' : hasRoleSplit ? '当前未绑定' : '未查询'} )} {role.currentChannel && {role.currentChannel}} {role.pendingName && ( <> 待确认 {role.pendingName} {role.pendingChannel && {role.pendingChannel}} )} ); }, }, { title: '精英宝典', width: '13%', align: 'center', ellipsis: true, render: (_value, row) => { const task = latestTask(tasks, row.id); const opening = task?.result?.elite_opening === true; return {opening ? '开通中' : row.elite_opened === true ? '已开通' : row.elite_opened === false ? '未开通' : '未查询'}{row.elite_opened === true && row.elite_open_time ? {`开通 ${formatUnixSeconds(row.elite_open_time)}`} : null}{row.elite_expire_time ? {`有效期至 ${formatUnixSeconds(row.elite_expire_time)}`} : null}; } }, { title: '积分', dataIndex: 'points', width: '7%', align: 'center', render: (value: number | null) => value ?? - }, { 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 ? {TASK_LABELS[task.task_type] || task.task_type}{task.message || '-'}{formatTime(task.finished_at || task.created_at)}{task.task_type === 'query_exchange_records' && records.length > 0 && } : 暂无操作; } }, { title: '二维码', width: '6%', align: 'center', render: (_value, row) => { const task = latestTask(tasks, row.id); if (!task) return -; 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 -; return
{ event.stopPropagation(); void openQrTask(task); }} style={{ cursor: 'pointer', display: 'inline-block', lineHeight: 0, background: '#fff', padding: 6, borderRadius: 4 }} title="点击查看小程序码">
; } if (!url && !image) return -; const doneLabel = qrDoneLabel(task); if (doneLabel) return {doneLabel}; return
{ 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 ? 二维码 : }
; } }, { title: '状态', width: '7%', align: 'center', render: (_value, row) => { const task = latestTask(tasks, row.id); if (ckExpired(task, row)) return CK 失效; const status = task?.status || row.status || ''; return {TASK_STATUS_LABELS[status] || status || '待操作'}; } }, ]; const operationBody = (
绑定与查询
兑换
({ value: item.spu_id, label: rechargeGoodsLabel(item) }))} style={{ width: '100%' }} /> : {selectedEliteGoods ? `${rechargeGoodsLabel(selectedEliteGoods)}${rechargeEliteLimit < RECHARGE_COUNT_MAX ? ` · 限购 ${rechargeEliteLimit} 份` : ''}` : '列表里还没有精英宝典,请先刷新开通商品'}}
其他开通商品
} placeholder="搜索账号/昵称/游戏名/手机号" value={search} onChange={(event) => { setSearch(event.target.value); setCurrentPage(1); }} style={{ width: 240 }} />{canImport && }{selectedIds.length > 0 && }{canTransferCollab && selectedIds.length === 1 && }
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: '右键打开账号动作' })} />; 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

虎牙精英宝典工作台

绑定、开通、积分与兑换任务
{canConfig && }{!!activeBatches.length && }
{layoutMode === 'split' ?
已选 {selectedIds.length}/{accounts.length}} 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}并发 setConcurrency(value || 1)} style={{ width: 58 }} />} style={{ width: 360, flexShrink: 0, minHeight: 0, overflow: 'hidden' }} styles={{ body: { padding: 8, overflowY: 'auto', height: 'calc(100% - 38px)' } }}>{operationBody}
: <>并发 setConcurrency(value || 1)} style={{ width: 58 }} />} style={{ flexShrink: 0, marginBottom: 12 }} styles={{ body: { padding: 8 } }}>{operationBody}已选 {selectedIds.length}/{accounts.length}} 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}} 兑换任务 {exchangeCount} 条;勾选账号后可批量执行,账号行支持右键操作。 {contextMenu &&
event.stopPropagation()}> 1 ? '批量动作' : '账号动作'} styles={{ body: { padding: 4 } }} style={{ width: 220, boxShadow: '0 4px 12px rgba(0,0,0,0.14)' }}>{HUYA_QUICK_ACTIONS.map((item) => )}
} { setQrTask(null); setQrImage(''); }} centered>{qrTask &&
{qrImage ? 绑定二维码 : qrTask.result?.has_mini_qrcode === true ?
{qrTaskLoading ? : 正在获取小程序码…}
: }

{qrTask.message || qrTask.status}

}
setRecordsTask(null)} width={980} centered > 共 {viewedRecords.length} 条 活动 SID {String(recordsTask?.result?.sid || '-')} {recordsTask?.message ? {recordsTask.message} : null}
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 }} /> setExchangeImagePreview(null)} > {exchangeImagePreview && ( 兑换结果 )} setPayOpen(false)} footer={多选账号会同时生成多个码并排展示,各自独立等待支付;支付后自动确认开通状态} > 0 ? '待扫码队列已清空,支付完成的账号已自动移除' : '当前没有待扫码支付码'} queuedText="还有账号在排队生成支付码" onZoom={(item) => { const task = payTaskById.get(Number(item.key)); if (task) setZoomPayTask(task); }} onCopy={(item) => void copyPayLink(item.copyValue || item.qrValue || '', '支付链接')} /> setZoomPayTask(null)} width={680} centered> {zoomPayTask &&

{resultText(zoomPayTask, 'payment_status_label') || zoomPayTask.status}{resultText(zoomPayTask, 'amount_text')}

{payQrValue(zoomPayTask)}
}
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="取消"> setImportSearch(event.target.value)} style={{ marginBottom: 8 }} />
!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)) }} /> setConfigOpen(false)} onOk={() => void saveConfig()} confirmLoading={configSaving} okText="保存" cancelText="取消" width={680}>{configLoading ?
加载中...
:
空闲轮询间隔(秒) { const next = Math.min(60, Math.max(5, value || 15)); setRefreshInterval(next); localStorage.setItem('huya_elite_refresh_interval', String(next)); }} style={{ width: 300 }} />
}
setCkImportOpen(false)} tags={importTags} scope={SCOPE} onImported={(result) => { localStorage.setItem('huya_elite_workbench_account_ids', JSON.stringify(result.account_ids)); void load(); }} /> ; }