import { CheckCircleOutlined, ChromeOutlined, CopyOutlined, HistoryOutlined, KeyOutlined, ReloadOutlined, SendOutlined, UserSwitchOutlined, } from '@ant-design/icons' import { Alert, App, Button, Card, Descriptions, Drawer, Form, Input, InputNumber, Modal, Select, Space, Tabs, Tag, Timeline, Typography, } from 'antd' import type { TableColumnsType } from 'antd' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useEffect, useMemo, useRef, useState } from 'react' import { useSearchParams } from 'react-router' import ImageUpload from '@/components/files/ImageUpload' import PageHeader from '@/components/admin/PageHeader' import SemiAutoTaskHistoryDrawer from '@/components/admin/SemiAutoTaskHistoryDrawer' import PercentTable from '@/components/common/PercentTable' import { cancelAdminSemiAutoTask, claimAdminSemiAutoTask, completeAdminSemiAutoTask, createSemiAutoBrowserSession, exportAdminSemiAutoCredential, fetchAdminSemiAutoTask, fetchAdminSemiAutoTasks, requestAdminSemiAutoCustomerReauth, syncAdminSemiAutoTask, } from '@/services/admin/semi-auto' import { SEMI_AUTO_CATEGORY_KEYS, SEMI_AUTO_CATEGORY_LABELS, semiAutoCategoryLabel, } from '@/types/admin/semi-auto' import type { SemiAutoTask } from '@/types/admin/semi-auto' import type { UploadedFile } from '@/types/worker-platform' import { formatAdminDateTime } from '@/utils/admin-time' import { buildCustomerFulfillmentPath } from '@/utils/customer-fulfillment-link' import { formatHuyaBindingDecisionMessage } from '@/utils/semi-auto-binding-decision' import { buildSemiAutoInjectionKit, dispatchSemiAutoInjection, isSemiAutoExchangeHelperReady, matchSemiAutoInjectionResult, resolvePostInjectionUrl, SEMI_AUTO_RESULT_EVENT, } from '@/utils/semi-auto-injection' import { buildSemiAutoTaskListParams, isSemiAutoPlatformTab, resolveSemiAutoPlatformTab, SEMI_AUTO_PLATFORM_TABS, type SemiAutoCategoryFilter, } from '@/utils/semi-auto-task-filters' import { canCompleteSemiAutoTask, canInjectSemiAutoBrowser } from '@/utils/semi-auto-task-readiness' const { Text } = Typography const STATUS_COLORS: Record = { waiting_profile: 'gold', waiting_customer: 'blue', waiting_login: 'blue', login_scanned: 'cyan', waiting_binding: 'gold', binding_confirm: 'orange', rebind_required: 'gold', rebind_blocked_account: 'red', rebind_blocked_target_role: 'red', rebind_effect_pending: 'processing', binding_support: 'magenta', binding_expired: 'red', binding_failed: 'red', waiting_operator: 'volcano', credential_expired: 'red', processing: 'processing', completed: 'success', failed: 'error', cancelled: 'default', } const PLATFORM_LABELS: Record = { huya: '虎牙', weibo: '微博', } const BINDING_STATUS_LABELS: Record = { not_started: '未开始', qr_pending: '待扫码', scanned: '已扫码', role_ready: '待确认角色', confirmed: '已确认', failed: '失败', expired: '已过期', } const BINDING_FLOW_LABELS: Record = { binding_query_required: '待查询绑定', initial_bind_required: '待首次绑定', first_bind_qr_pending: '首次绑定待扫码', first_bind_role_ready: '首次绑定待确认', first_bind_role_mismatch: '首次绑定角色不一致', first_bind_failed: '首次绑定失败', current_role_confirmable: '当前角色待确认', rebind_required: '需要换绑', rebind_qr_pending: '换绑待扫码', rebind_role_ready: '换绑待确认', rebind_effect_pending: '绑定生效中', rebind_blocked_account: '虎牙账号换绑冷却中', rebind_blocked_target_role: '目标角色冷却', rebind_rejected: '虎牙拒绝换绑', rebind_effect_failed: '换绑未生效', confirmed: '绑定已确认', manual_review: '绑定需人工核实', expired: '绑定已过期', } type CompleteFormValues = { note?: string externalOrderNo?: string costYuan?: number } const INJECTION_RESULT_TIMEOUT_MS = 30_000 /** 一次在途注入:只接受 request_id 与它匹配的扩展回执。 */ type PendingInjection = { requestId: string taskId: number timeoutId: number } export default function AdminSemiAutoTasksPage() { const { message, modal } = App.useApp() const queryClient = useQueryClient() const [searchParams, setSearchParams] = useSearchParams() const [keyword, setKeyword] = useState('') const [categoryFilter, setCategoryFilter] = useState('all') const [status, setStatus] = useState('') const [page, setPage] = useState(1) const [pageSize, setPageSize] = useState(20) const [detailTaskId, setDetailTaskId] = useState(null) const [historyTaskId, setHistoryTaskId] = useState(null) const [completeTask, setCompleteTask] = useState(null) const [completeFiles, setCompleteFiles] = useState([]) const [completeForm] = Form.useForm() const pendingInjectionRef = useRef(null) // tab 即平台:URL 上没有 tab 或值非法时落到虎牙,刷新/分享链接后仍是同一个列表。 const tab = resolveSemiAutoPlatformTab(searchParams.get('tab')) const params = useMemo( () => buildSemiAutoTaskListParams({ tab, categoryFilter, keyword, status, page, pageSize }), [tab, categoryFilter, keyword, status, page, pageSize], ) const listQuery = useQuery({ queryKey: ['admin-semi-auto-tasks', params], queryFn: () => fetchAdminSemiAutoTasks(params), }) const detailQuery = useQuery({ queryKey: ['admin-semi-auto-task', detailTaskId], queryFn: () => fetchAdminSemiAutoTask(Number(detailTaskId)), enabled: Boolean(detailTaskId), }) const list = listQuery.data?.data?.items || [] const pagination = listQuery.data?.data?.pagination const detail = detailQuery.data?.data useEffect(() => { if (detailTaskId && listQuery.data && !list.some((item) => item.id === detailTaskId)) { setDetailTaskId(null) } }, [detailTaskId, list, listQuery.data]) useEffect(() => { const handleResult = (event: Event) => { const pending = pendingInjectionRef.current if (!pending) return // 扩展回执是页面级广播:只消费 request_id 与本次注入匹配的那一条。 const result = matchSemiAutoInjectionResult( (event as CustomEvent).detail, pending.requestId, ) if (!result) return window.clearTimeout(pending.timeoutId) pendingInjectionRef.current = null if (result.ok) { message.success(`已写入 ${result.written} 个 Cookie(扩展已打开平台页面)`) } else { message.error( result.error || (result.written > 0 ? `只写入 ${result.written} 个 Cookie,${result.failed} 个失败,请重新注入` : '浏览器登录态写入失败,请确认「半自动兑换助手」可用后重试'), ) } void queryClient.invalidateQueries({ queryKey: ['admin-semi-auto-tasks'] }) void queryClient.invalidateQueries({ queryKey: ['admin-semi-auto-task'] }) } window.addEventListener(SEMI_AUTO_RESULT_EVENT, handleResult) return () => window.removeEventListener(SEMI_AUTO_RESULT_EVENT, handleResult) }, [message, queryClient]) // 页面卸载时清掉在途注入的定时器,避免已卸载页面继续弹提示。 useEffect(() => { return () => { const pending = pendingInjectionRef.current if (!pending) return window.clearTimeout(pending.timeoutId) pendingInjectionRef.current = null } }, []) const syncMutation = useMutation({ mutationFn: (taskId: number) => syncAdminSemiAutoTask(taskId), onSuccess: () => { message.success('状态已刷新') void refreshAll() }, onError: (error) => message.error(error instanceof Error ? error.message : '刷新失败'), }) const claimMutation = useMutation({ mutationFn: (taskId: number) => claimAdminSemiAutoTask(taskId), onSuccess: () => { message.success('任务已领取') void refreshAll() }, onError: (error) => message.error(error instanceof Error ? error.message : '领取失败'), }) function cancelPendingInjection() { const pending = pendingInjectionRef.current if (!pending) return window.clearTimeout(pending.timeoutId) pendingInjectionRef.current = null } const credentialExportMutation = useMutation({ mutationFn: (taskId: number) => exportAdminSemiAutoCredential(taskId), onSuccess: (response) => { const text = String(response.data?.cookieHeader || '').trim() || (response.data?.cookies || []).map((cookie) => `${cookie.name}=${cookie.value}`).join('; ') if (!text) { message.error('当前任务没有可复制的 CK') return } void navigator.clipboard .writeText(text) .then(() => message.success('最终 CK 已复制')) .catch(() => message.error('复制失败,请检查浏览器剪贴板权限')) }, onError: (error) => message.error(error instanceof Error ? error.message : '复制账号 CK 失败'), }) /** * 注入流程:取 CK → 组装材料包 → 派发 CustomEvent → 等扩展回执。 * 前端不再签发/消费票据,也不自己开关标签页(写入 Cookie 并打开目标页都是扩展的职责)。 */ const injectionMutation = useMutation({ mutationFn: (task: SemiAutoTask) => createSemiAutoBrowserSession(task.id, resolveInjectionTargetUrl(task)), onSuccess: (response, task) => { const session = response.data const cookieCount = Array.isArray(session?.cookies) ? session.cookies.length : 0 if (!session || cookieCount === 0) { cancelPendingInjection() message.error('账号 CK 不可用,请客户重新登录后再注入浏览器') return } cancelPendingInjection() const kit = buildSemiAutoInjectionKit(session) const timeoutId = window.setTimeout(() => { const pending = pendingInjectionRef.current if (!pending || pending.requestId !== kit.request_id) return pendingInjectionRef.current = null message.warning('未收到「半自动兑换助手」回执,请确认扩展已启用后重试') }, INJECTION_RESULT_TIMEOUT_MS) pendingInjectionRef.current = { requestId: kit.request_id, taskId: task.id, timeoutId } if (!dispatchSemiAutoInjection(kit)) { cancelPendingInjection() message.error('注入材料派发失败,请刷新页面后重试') return } message.info(`正在向浏览器写入 ${cookieCount} 个 Cookie,请稍候`) void refreshAll() }, onError: (error) => { cancelPendingInjection() message.error(error instanceof Error ? error.message : '获取浏览器登录态失败') }, }) function startInjection(task: SemiAutoTask) { if (pendingInjectionRef.current) { message.warning('上一次注入尚未完成,请稍候') return } // 扩展内容脚本会在白名单页面打标记;没有标记时直接提示 + 提供复制 CK 兜底,不静默失败。 if (!isSemiAutoExchangeHelperReady(document.documentElement?.dataset)) { modal.warning({ title: '未检测到「半自动兑换助手」扩展', content: '请先在 Chrome / Edge 安装并启用「半自动兑换助手」,然后刷新本页再注入;也可以直接复制账号 CK 手工兑换。', okText: '复制 CK', cancelText: '我知道了', onOk: () => credentialExportMutation.mutateAsync(task.id), }) return } injectionMutation.mutate(task) } const reauthMutation = useMutation({ mutationFn: (task: SemiAutoTask) => requestAdminSemiAutoCustomerReauth(task.id), onSuccess: async (response, task) => { const copied = await copyCustomerLink(response.data?.task || task, '') message.success( copied ? '已重新发起授权,客户链接已复制' : '已重新发起授权,请手动复制客户链接', ) await refreshAll() }, onError: (error) => message.error(error instanceof Error ? error.message : '重新发起客户授权失败'), }) const completeMutation = useMutation({ mutationFn: async (values: CompleteFormValues) => { if (!completeTask) throw new Error('任务不存在') const costFen = values.costYuan !== undefined && values.costYuan !== null ? Math.round(Number(values.costYuan) * 100) : undefined return completeAdminSemiAutoTask(completeTask.id, { note: values.note || '', externalOrderNo: values.externalOrderNo || '', ...(costFen !== undefined ? { costFen } : {}), screenshots: completeFiles.map((file) => ({ ...file })), }) }, onSuccess: () => { message.success('半自动履约已完成') setCompleteTask(null) setCompleteFiles([]) completeForm.resetFields() void refreshAll() }, onError: (error) => message.error(error instanceof Error ? error.message : '完成履约失败'), }) const cancelMutation = useMutation({ mutationFn: ({ taskId, reason }: { taskId: number; reason: string }) => cancelAdminSemiAutoTask(taskId, reason), onSuccess: () => { message.success('任务已取消') void refreshAll() }, onError: (error) => message.error(error instanceof Error ? error.message : '取消失败'), }) async function refreshAll() { await Promise.all([ queryClient.invalidateQueries({ queryKey: ['admin-semi-auto-tasks'] }), detailTaskId ? queryClient.invalidateQueries({ queryKey: ['admin-semi-auto-task', detailTaskId] }) : Promise.resolve(), ]) } function changeTab(nextTab: string) { if (!isSemiAutoPlatformTab(nextTab) || nextTab === tab) return setPage(1) setSearchParams( (current) => { current.set('tab', nextTab) return current }, { replace: true }, ) } async function copyCustomerLink(task: SemiAutoTask, successMessage = '客户授权链接已复制') { const path = buildCustomerFulfillmentPath(task.orderNo, task.platform) if (!path) { message.error('订单号为空,无法生成客户链接') return false } const url = `${window.location.origin}${path}` try { await navigator.clipboard.writeText(url) if (successMessage) message.success(successMessage) return true } catch { message.error('复制失败,请手动复制客户链接') return false } } function confirmReauth(task: SemiAutoTask) { modal.confirm({ title: '重新发送客户授权', content: '当前登录状态会失效,客户需要打开新的授权链接重新登录。原授权记录会保留。', okText: '重新发送并复制链接', cancelText: '取消', onOk: () => reauthMutation.mutateAsync(task), }) } function confirmCopyCredential(task: SemiAutoTask) { modal.confirm({ title: '复制最终 CK', content: 'CK 等同于平台登录态。复制后请勿发给无关人员,也不要保存到聊天记录或工单备注。', okText: '确认复制', okButtonProps: { danger: true }, cancelText: '取消', onOk: () => credentialExportMutation.mutateAsync(task.id), }) } function openComplete(task: SemiAutoTask) { setCompleteTask(task) setCompleteFiles([]) completeForm.resetFields() } function confirmCancel(task: SemiAutoTask) { let reason = '' modal.confirm({ title: '取消半自动履约任务', content: ( { reason = event.target.value }} /> ), okText: '确认取消', okButtonProps: { danger: true }, cancelText: '返回', onOk: () => cancelMutation.mutateAsync({ taskId: task.id, reason }), }) } const columns: TableColumnsType = [ { title: '订单 / 商品', key: 'order', width: 260, render: (_, task) => ( {task.orderNo} {task.productName || task.skuName || task.skuCode} SKU:{task.skuCode || '-'} ), }, { title: '平台', dataIndex: 'platform', width: 120, render: (value: string, task) => ( {PLATFORM_LABELS[value] || value} {task.connectorMode === 'mock' ? 'Mock' : '真实'} ), }, { title: '分类', dataIndex: 'semiAutoCategory', width: 100, render: (value: string) => ( {semiAutoCategoryLabel(value)} ), }, { title: '客户登录', key: 'login', width: 180, render: (_, task) => ( {task.displayStatus.label} {task.displayStatus.nextAction} {task.huyaUid ? `UID ${task.huyaUid}` : '未获取 UID'} {`绑定:${ BINDING_FLOW_LABELS[task.bindingFlowState] || BINDING_STATUS_LABELS[task.bindingStatus] || task.bindingStatus }`} {task.bindGameRole ? ( {`当前角色:${task.bindGameRole}`} ) : null} {task.pendingBindGameRole ? ( {`待确认角色:${task.pendingBindGameRole}`} ) : null} CK: {task.credentialStatus === 'valid' ? '有效' : task.credentialStatus === 'invalid' ? '失效' : task.credentialStatus === 'error' ? '检测异常' : '未保存'} ), }, { title: '账号凭证', key: 'credential', width: 190, render: (_, task) => ( {task.platformNickname || task.huyaUid || '未获取账号'} {task.credentialSource ? `${task.credentialSource} · ${formatAdminDateTime(task.credentialUpdatedAt)}` : '尚无 CK'} ), }, { title: '客服', dataIndex: 'assignedAdminName', width: 110, render: (value: string) => value || '未领取', }, { title: '更新时间', dataIndex: 'updatedAt', width: 155, render: (value: string) => formatAdminDateTime(value), }, { title: '操作', key: 'actions', width: 520, render: (_, task) => ( {taskNeedsCustomerReauth(task) ? ( ) : null} {!task.assignedAdminUserId ? ( ) : null} {task.executionStatus !== 'completed' && task.executionStatus !== 'cancelled' && !taskNeedsCustomerReauth(task) ? ( ) : null} {task.executionStatus !== 'completed' && task.executionStatus !== 'cancelled' ? ( ) : null} ), }, ] function renderTaskPanel() { return ( { setKeyword(event.target.value) setPage(1) }} style={{ width: 280 }} /> { setStatus(value || '') setPage(1) }} options={[ { value: 'waiting_customer', label: '等待客户' }, { value: 'waiting_operator', label: '等待客服' }, { value: 'processing', label: '处理中' }, { value: 'completed', label: '已完成' }, { value: 'failed', label: '失败' }, { value: 'cancelled', label: '已取消' }, ]} style={{ width: 130 }} /> rowKey="id" loading={listQuery.isLoading} columns={columns} dataSource={list} scroll={{ x: 1500 }} pagination={{ current: pagination?.page || page, pageSize: pagination?.pageSize || pageSize, total: pagination?.total || 0, showSizeChanger: true, onChange: (nextPage, nextPageSize) => { setPage(nextPage) setPageSize(nextPageSize) }, }} /> ) } return (
({ key: platformKey, label: PLATFORM_LABELS[platformKey] || platformKey, // 只渲染当前 tab:两个平台同时挂在 DOM 上会重复拉一次列表。 children: tab === platformKey ? renderTaskPanel() : null, }))} /> setDetailTaskId(null)} > {detailQuery.isLoading ? ( 加载中... ) : detail?.task ? ( {detail.task.productName} {PLATFORM_LABELS[detail.task.platform] || detail.task.platform} {semiAutoCategoryLabel(detail.task.semiAutoCategory)} {detail.task.connectorMode === 'mock' ? '内置 Mock' : detail.task.connectorMode === 'external' ? '远程真实' : '内置真实'} {detail.task.displayStatus.label} {detail.task.huyaUid || '-'} {detail.task.platformNickname || '-'} {detail.task.credentialStatus === 'valid' ? '有效' : detail.task.credentialStatus === 'invalid' ? '失效' : detail.task.credentialStatus === 'error' ? '检测异常' : '未保存'} {detail.task.credentialSource ? `${detail.task.credentialSource} · ${formatAdminDateTime(detail.task.credentialUpdatedAt)}` : '-'} {detail.task.platformNickname || '-'} {detail.task.loginStatus === 'authenticated' ? 'CK 已获取' : '等待客户登录'} {BINDING_FLOW_LABELS[detail.task.bindingFlowState] || BINDING_STATUS_LABELS[detail.task.bindingStatus] || detail.task.bindingStatus} {detail.task.bindGameRole || '-'} {detail.task.pendingBindGameRole || '-'} {detail.task.platformGameRoleUid ? ( {detail.task.platformGameRoleUid} ) : null} {detail.task.pendingPlatformGameRoleUid ? ( {detail.task.pendingPlatformGameRoleUid} ) : null} {[ detail.task.bindGameChannel, detail.comparison?.boundZone ? `识别区服 ${detail.comparison.boundZone}` : '', ] .filter(Boolean) .join(' · ') || '-'} {detail.task.customerGameRoleName || '-'} {detail.task.customerGameRoleId || '-'} {detail.task.customerServerZone || '-'} {detail.comparison?.verdict === 'match' ? '角色名与区服一致,可提交平台绑定' : detail.comparison?.verdict === 'mismatch' ? '资料与平台角色不一致' : '信息不完整,需人工核实'} {detail.comparison?.message || '-'} {BINDING_FLOW_LABELS[detail.task.bindingFlowState] || '-'} {formatHuyaBindingDecisionMessage(detail.task.bindingDecision) || '-'} {detail.task.bindingDecision?.rebindBlockScope ? ( 阻塞作用域: {detail.task.bindingDecision.rebindBlockScope === 'account' ? '虎牙账号' : detail.task.bindingDecision.rebindBlockScope === 'target_role' ? '目标游戏角色' : '平台其他原因'} ) : null} {detail.task.assignedAdminName || '未领取'} {formatAdminDateTime(detail.task.updatedAt)} {taskNeedsCustomerReauth(detail.task) ? ( ) : null} {detail.task.lastError ? ( {detail.task.lastError} ) : null} {taskNeedsCustomerReauth(detail.task) ? ( ) : null} ({ color: event.eventType.includes('failed') ? 'red' : 'blue', children: ( {event.eventType} {formatAdminDateTime(event.createdAt)} · {event.actorType} {event.actorId ? ` ${event.actorId}` : ''} {event.eventType === 'binding_status_changed' && event.detail?.message ? ( {String(event.detail.message)} {Number(event.detail.rebindCooldownDays || 0) > 0 && event.detail.nextRebindAt ? ` · 下次可换绑 ${formatAdminDateTime( String(event.detail.nextRebindAt), )}` : ''} ) : null} {event.eventType === 'binding_status_changed' && event.detail?.rebindConfirmMessage ? ( 虎牙返回:{String(event.detail.rebindConfirmMessage)} ) : null} ), }))} /> ) : ( 暂无任务详情 )} setHistoryTaskId(null)} /> { setCompleteTask(null) setCompleteFiles([]) completeForm.resetFields() }} onOk={() => { void completeForm.validateFields().then((values) => completeMutation.mutate(values)) }} > form={completeForm} layout="vertical">
) } function resolveInjectionTargetUrl(task: SemiAutoTask) { // 优先用人工 SKU 里配的 browserTargets,再用平台默认目标页; // 这个 URL 只是 `target_url`,写入 Cookie 后由扩展负责打开。 const targets = Array.isArray(task.semiAutoConfig?.browserTargets) ? task.semiAutoConfig.browserTargets : [] const configured = String(targets.find((item) => item?.url)?.url || '') return configured || resolvePostInjectionUrl(task.platform) } function taskNeedsCustomerReauth(task: SemiAutoTask) { if (task.executionStatus === 'completed' || task.executionStatus === 'cancelled') return false return ( task.credentialStatus === 'invalid' || task.credentialStatus === 'error' || task.executionStatus === 'failed' || task.loginStatus === 'failed' || task.loginStatus === 'expired' ) }