import { useCallback, useEffect, useState } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; import { Button, Card, Col, Descriptions, Divider, Empty, Input, Popconfirm, Row, Select, Space, Spin, Statistic, Table, Tag, Tooltip, Typography, } from 'antd'; import type { TableProps } from 'antd'; import { ArrowLeftOutlined, EditOutlined, ReloadOutlined, ThunderboltOutlined, } from '@ant-design/icons'; import { accountApi, douyuApi, userApi, type AccountCommodityState, type AccountEventItem, type AccountOverview, type HighValueAssetState, type HighValueStatus, type UserInfo } from '../api/modules'; import AccountOverviewPanel from './douyu-tasks/AccountOverviewPanel'; import { eliteIsExpired } from '../utils/douyuElite'; import { getErrorMessage } from '../utils/error'; import { message } from '../utils/antdMessage'; import { formatTime, formatUnixSeconds } from '../utils/time'; const { Text, Title } = Typography; /** * 事件类型 → 展示样式。 * 颜色用来一眼区分「钱进来 / 分出去 / 状态变化」三类,而不是按类型各给一个颜色。 */ const EVENT_STYLE: Record = { imported: { label: '导入', color: 'default' }, login_ok: { label: '登录', color: 'blue' }, ck_invalid: { label: 'CK 失效', color: 'red' }, ck_cleared: { label: 'CK 已清除', color: 'red' }, relogin_ok: { label: '重登成功', color: 'green' }, relogin_failed: { label: '重登转人工', color: 'orange' }, status_changed: { label: '状态变更', color: 'geekblue' }, bind_ok: { label: '绑定', color: 'cyan' }, recharge: { label: '充值', color: 'green' }, exchange: { label: '兑换', color: 'purple' }, points_credit: { label: '积分到账', color: 'gold' }, elite_opened: { label: '精英宝典', color: 'magenta' }, esports_opened: { label: '电竞手册', color: 'volcano' }, assigned: { label: '分配', color: 'default' }, tag_changed: { label: '标签', color: 'default' }, remark_changed: { label: '备注', color: 'default' }, automation_changed: { label: '自动化开关', color: 'geekblue' }, task_started: { label: '任务创建', color: 'blue' }, task_succeeded: { label: '任务成功', color: 'green' }, task_failed: { label: '任务失败', color: 'red' }, task_stopped: { label: '任务停止', color: 'orange' }, query_completed: { label: '查询完成', color: 'blue' }, lease_acquired: { label: '账号占用', color: 'cyan' }, collab_synced: { label: '外部协作同步', color: 'geekblue' }, lease_released: { label: '账号释放', color: 'default' }, }; /** 事件粗分类(与后端 `account_events_service.CATEGORY_*` 对应)。 */ const CATEGORY_OPTIONS = [ { value: 'lifecycle', label: '状态变迁' }, { value: 'auth', label: '登录与 CK' }, { value: 'business', label: '业务流水' }, { value: 'activity', label: '查询与任务' }, { value: 'ops', label: '人工操作' }, ]; const ACTOR_TYPE_LABELS: Record = { user: '用户', system: '系统', public: '客户', }; /** 生命周期状态 → 展示色(与账号列表页保持一致,取值域见后端 account_lifecycle)。 */ const STATUS_TONES: Record = { imported: 'default', active: 'green', invalid: 'red', manual: 'orange', disabled: 'default', archived: 'default', }; /** 绑定状态 → 展示色(与后端 account_binding 的四个枚举对应)。 */ const BIND_TONES: Record = { bound: 'green', pending: 'orange', unbound: 'red', unknown: 'default', }; function highValueShortTag(label: string, status: HighValueAssetState) { if (status === 'owned') return {label}已达上限; if (status === 'available') return {label}可换; return {label}待确认; } function CurrentHighValue({ value }: { value: HighValueStatus }) { if (value.state === 'never') { return 尚未形成高价值准入结论; } if (value.state === 'stale') { return ( 官方状态已过期,需要重新查询 ); } return ( {highValueShortTag('白日梦', value.bairimeng)} {highValueShortTag('萌兔', value.mengtu)} ); } function eventTag(type: string) { const style = EVENT_STYLE[type] ?? { label: type, color: 'default' }; return {style.label}; } function actorLabel(item: AccountEventItem) { if (item.actor_type === 'user') { const name = item.actor_name || (item.actor_id ? `用户 #${item.actor_id}` : '用户'); const role = item.actor_role_label ? `(${item.actor_role_label})` : ''; const id = item.actor_id ? ` · ID ${item.actor_id}` : ''; return `${name}${role}${id}`; } return ACTOR_TYPE_LABELS[item.actor_type || 'system'] || item.actor_type || '系统'; } const COMMODITY_STATE: Record = { available: { label: '可兑换', color: 'green' }, limited: { label: '已达上限', color: 'orange' }, no_stock: { label: '无库存', color: 'default' }, not_open: { label: '未开放', color: 'gold' }, not_offered: { label: '本次未返回', color: 'default' }, expired: { label: '限时已结束', color: 'default' }, unknown: { label: '待确认', color: 'default' }, }; function commodityStateTag(value: string) { const state = COMMODITY_STATE[value] ?? COMMODITY_STATE.unknown; return {state.label}; } const ACCOUNT_ELIGIBILITY: Record = { eligible: { label: '账号可兑换', color: 'green' }, limited: { label: '账号已限兑', color: 'orange' }, unknown: { label: '资格待确认', color: 'default' }, }; const OFFER_STATE: Record = { before: { label: '活动未开始', color: 'gold' }, active: { label: '活动进行中', color: 'blue' }, expired: { label: '活动已结束', color: 'default' }, not_offered: { label: '商品未上架', color: 'default' }, unknown: { label: '时间待确认', color: 'default' }, }; const STOCK_STATE: Record = { in_stock: { label: '有库存', color: 'green' }, out_of_stock: { label: '官方无库存', color: 'default' }, unknown: { label: '库存未知', color: 'default' }, }; function splitStateTag( value: string, states: Record, ) { const state = states[value] ?? Object.values(states).at(-1); return {state?.label || value}; } /** 金额展示:充值为正(绿色 ¥),兑换消耗为负(红色积分)。 */ function amountText(item: AccountEventItem) { if (item.amount === null || item.amount === undefined) return null; if (item.event_type === 'recharge') { return +¥{item.amount}; } if (item.event_type === 'exchange') { return {item.amount} 分; } return ( = 0 ? 'success' : 'danger'}> {item.amount > 0 ? '+' : ''} {item.amount} ); } export default function AccountDetailPage() { const { id } = useParams<{ id: string }>(); const accountId = Number(id); const navigate = useNavigate(); const [overview, setOverview] = useState(null); const [loading, setLoading] = useState(true); const [events, setEvents] = useState([]); const [eventTotal, setEventTotal] = useState(0); const [page, setPage] = useState(1); const [pageSize, setPageSize] = useState(20); const [eventType, setEventType] = useState(''); const [category, setCategory] = useState(''); const [eventsLoading, setEventsLoading] = useState(false); const [commodities, setCommodities] = useState([]); const [commoditySummary, setCommoditySummary] = useState>({}); const [commoditiesLoading, setCommoditiesLoading] = useState(false); const [tagDraft, setTagDraft] = useState(''); // 一键查询:向斗鱼实时查一次该账号的全部关键信息(异步任务 + 轮询结果) const [ovLoading, setOvLoading] = useState(false); const [ovError, setOvError] = useState(''); const [tagEditing, setTagEditing] = useState(false); const [supportUsers, setSupportUsers] = useState([]); const [remarkEditing, setRemarkEditing] = useState(false); const [remarkDraft, setRemarkDraft] = useState(''); /** 加载客服列表(分配用)。只在需要时拉一次。 */ useEffect(() => { let alive = true; void (async () => { try { const users = await userApi.list(); if (alive) setSupportUsers((users || []).filter((u) => u.role === 'support')); } catch { // 拉不到客服列表不影响页面其它部分 } })(); return () => { alive = false; }; }, []); const loadCommodities = useCallback(async () => { if (!accountId) return; setCommoditiesLoading(true); try { const data = await accountApi.commodities(accountId); setCommodities(data.items); setCommoditySummary(data.summary); } catch (e: unknown) { message.error(getErrorMessage(e)); } finally { setCommoditiesLoading(false); } }, [accountId]); // 一键查询:建一个只读聚合任务 → 轮询**账号自身**直到快照更新。 // // 结果写在账号上(`overview_snapshot`),所以轮询账号就够了。 // // ⚠️ 轮询必须**能自证在推进**。之前的 bug:详情接口忘了返回 // `overview_queried_at`(字段加到了列表接口上),于是比较永远相等、 // 轮询满 120 秒 —— 用户看到的就是"点一下就一直转圈刷请求"。 // 所以这里加了:拿不到标记字段就**立刻报错退出**,而不是傻等。 const runOverview = useCallback(async () => { if (!id) return; const accountId = Number(id); const before = overview?.overview_queried_at ?? ''; setOvLoading(true); setOvError(''); try { await douyuApi.createTasks({ account_ids: [accountId], task_type: 'query_account_overview', handbook_scope: 'elite', }); const deadline = Date.now() + 120_000; let first = true; while (Date.now() < deadline) { await new Promise((resolve) => setTimeout(resolve, 2000)); const fresh = await accountApi.overview(accountId); const marker = fresh.overview_queried_at; if (first && marker === undefined) { // 接口没返回标记字段 —— 再怎么轮询也不可能变化,直接如实报错 setOvError('接口未返回查询时间标记,无法判断是否完成(请检查后端详情接口)'); return; } first = false; if ((marker ?? '') !== before) { setOverview(fresh); void loadCommodities(); message.success('查询完成'); return; } } setOvError('查询超时(120 秒未出结果),稍后刷新页面看看'); } catch (error) { setOvError(getErrorMessage(error)); } finally { setOvLoading(false); } }, [id, loadCommodities, overview?.overview_queried_at]); const loadOverview = useCallback(async () => { if (!accountId) return; setLoading(true); try { setOverview(await accountApi.overview(accountId)); } catch (e: unknown) { message.error(getErrorMessage(e)); } finally { setLoading(false); } }, [accountId]); const loadEvents = useCallback(async () => { if (!accountId) return; setEventsLoading(true); try { const data = await accountApi.events(accountId, { page, page_size: pageSize, event_type: eventType, category, }); setEvents(data.items); setEventTotal(data.total); } catch (e: unknown) { message.error(getErrorMessage(e)); } finally { setEventsLoading(false); } }, [accountId, page, pageSize, eventType, category]); useEffect(() => { void loadOverview(); }, [loadOverview]); useEffect(() => { void loadCommodities(); }, [loadCommodities]); useEffect(() => { void loadEvents(); }, [loadEvents]); const columns: TableProps['columns'] = [ { title: '时间', dataIndex: 'occurred_at', width: 165, render: (val: string) => formatTime(val), }, { title: '类型', dataIndex: 'event_type', width: 100, render: (val: string) => eventTag(val), }, { title: '操作人', key: 'actor', width: 190, render: (_value, record) => {actorLabel(record)}, }, { title: '说明', dataIndex: 'title', ellipsis: true }, { title: '金额 / 变动', dataIndex: 'amount', width: 110, align: 'right', render: (_val, record) => amountText(record) ?? -, }, { title: '变动后余额', dataIndex: 'balance_after', width: 110, align: 'right', render: (val: number | null) => val === null || val === undefined ? - : val, }, ]; const commodityColumns: TableProps['columns'] = [ { title: '商品', key: 'commodity', width: 240, render: (_value, row) => ( {row.commodity_name || row.commodity_id} {row.commodity_id} ), }, { title: '账号兑换资格', dataIndex: 'account_eligibility', width: 130, render: (value: string) => splitStateTag(value, ACCOUNT_ELIGIBILITY), }, { title: '活动状态', dataIndex: 'offer_state', width: 120, render: (value: string) => splitStateTag(value, OFFER_STATE), }, { title: '官方库存(仅参考)', width: 150, render: (_value, row) => ( {splitStateTag(row.stock_state, STOCK_STATE)} 数量 {row.stock_count ?? '-'} ), }, { title: '兑换执行', dataIndex: 'availability', width: 120, render: (value: string) => commodityStateTag(value), }, { title: '阻塞原因', dataIndex: 'blocking_reason', ellipsis: true, render: (value: string) => value || -, }, { title: '限时窗口', width: 210, render: (_value, row) => row.time_limited || row.available_from || row.available_until ? ( {row.time_limited && 限时兑换} {formatTime(row.available_from)} ~ {formatTime(row.available_until)} ) : ( 长期 ), }, { title: '近一年兑换', width: 150, render: (_value, row) => ( {row.exchange_count_365d} 次 {row.last_exchange_at ? formatTime(row.last_exchange_at) : '无记录'} ), }, { title: '最后确认', width: 170, render: (_value, row) => ( {formatTime(row.observed_at)} {row.fresh ? '有效' : '需复查'} ), }, ]; if (!accountId) { return ; } const stats = overview?.stats; const status = overview?.status || ''; /** 人工切换生命周期状态:disabled / archived / auto(恢复自动推导)。 */ const handleLifecycle = async (next: 'disabled' | 'archived' | 'auto') => { if (!accountId) return; try { await accountApi.setLifecycle(accountId, next); message.success('状态已更新'); void loadOverview(); void loadEvents(); } catch (e: unknown) { message.error(getErrorMessage(e)); } }; const handleAssign = async (assignedTo: number | null) => { if (!accountId) return; try { await accountApi.assign(accountId, assignedTo); message.success(assignedTo ? '已分配' : '已取消分配'); void loadOverview(); void loadEvents(); } catch (e: unknown) { message.error(getErrorMessage(e)); } }; const handleSaveTag = async () => { if (!accountId) return; try { await accountApi.setTag(accountId, tagDraft.trim()); message.success('标签已更新'); setTagEditing(false); void loadOverview(); void loadEvents(); } catch (e: unknown) { message.error(getErrorMessage(e)); } }; /** 保存备注:备注是自由文本,走单个接口(标签那种短枚举才有批量)。 */ const handleSaveRemark = async () => { if (!accountId) return; try { await accountApi.setRemark(accountId, remarkDraft.trim()); message.success('备注已更新'); setRemarkEditing(false); void loadOverview(); void loadEvents(); } catch (e: unknown) { message.error(getErrorMessage(e)); } }; const handleAutomation = async (autoManaged: boolean) => { if (!accountId) return; try { await accountApi.setAutomation(accountId, autoManaged); message.success(autoManaged ? '已恢复自动化' : '已设为不参与自动化'); void loadOverview(); } catch (e: unknown) { message.error(getErrorMessage(e)); } }; return (
{status === 'disabled' || status === 'archived' ? ( void handleLifecycle('auto')} > ) : ( <> void handleLifecycle('disabled')} > void handleLifecycle('archived')} > )} {overview?.auto_managed === false ? ( ) : ( void handleAutomation(false)} > )} {/* ── 卡片 1:账号信息 ────────────────────────────── 身份 + 状态 + 归属,一张表看完。**不重复展示资产**(见卡片 2)。 */} {overview?.nickname || overview?.username || '—'} #{overview?.id ?? '-'} · {overview?.username || '—'} {overview?.status_label || '—'} {overview?.tag && {overview.tag}} {overview?.auto_managed === false && 不参与自动化} } > {overview?.uid || '-'} {overview?.game_name || '-'} {overview?.game_channel ? ( ({overview.game_channel}) ) : null} {formatTime(overview?.created_at)} {formatTime(overview?.status_changed_at)} {overview?.status_reason ? ( ({overview.status_reason}) ) : null} {overview?.has_cookie === false ? ( 无 CK ) : ( {overview?.ck_check_status === 'invalid' ? '已失效' : overview?.ck_check_status === 'valid' ? '正常' : '未检测'} )} {formatTime(stats?.last_ck_check_at)} {/* 三个作用域各一列,取值 unknown/unbound/pending/bound。 全 unknown 时把「没查过」和「查了推不出」分开说 —— 混成一个"未知"会让人不知道下一步该干什么。 */} {[ overview?.role_bind_status, overview?.esports_bind_status, overview?.xpd_bind_status, ].every((s) => !s || s === 'unknown') ? ( {overview?.overview_queried_at ? ( <> 未能判定
已查询过,但斗鱼这次没给出绑定结论 ) : ( <> 未查询
点上方「一键查询」即可查出来 )}
) : ( 精英:{overview?.role_bind_label || '未知'} 电竞:{overview?.esports_bind_label || '未知'} 小店:{overview?.xpd_bind_label || '未知'} )}
setTagDraft(e.target.value)} onPressEnter={() => void handleSaveTag()} /> ) : ( {overview?.tag || '-'} ) : ( {overview?.remark || '-'} } > rowKey={(row) => `${row.scope}:${row.commodity_id}`} columns={commodityColumns} dataSource={commodities} size="small" loading={commoditiesLoading} pagination={false} scroll={{ x: 900, y: 320 }} locale={{ emptyText: ( ), }} />
{/* ── 卡片 3:一键查询结果 ────────────────────────── 放在账号信息**下面** —— 它是补充信息(账号表里没有的两项), 不该压在最上面抢主视觉。 */} 高价值套装与兑换记录 {overview?.overview_queried_at && ( 查询于 {formatTime(overview.overview_queried_at)} )} } extra={ } > {ovError && ( {ovError} )} {overview?.high_value && (
当前官方准入:
)} {overview?.overview_snapshot ? ( ) : ( 点右上角「一键查询」实时向斗鱼查一次:鱼翅 / 积分 / 开通状态会就地刷新到上面的 「资产与统计」,这里只展示账号表里没有的两项 —— 高价值套装是否已获得,以及官方兑换记录。 )}
{ setEventType(v); setPage(1); }} options={[ { value: '', label: '全部事件' }, ...Object.entries(EVENT_STYLE).map(([value, s]) => ({ value, label: s.label })), ]} /> 共 {eventTotal} 条 } > `共 ${t} 条`, onChange: (p, s) => { setPage(p); setPageSize(s); }, }} locale={{ emptyText: }} /> ); }