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, 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 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, createAdminSemiAutoBrowserSession, exportAdminSemiAutoCredential, fetchAdminSemiAutoTask, fetchAdminSemiAutoTasks, requestAdminSemiAutoCustomerReauth, syncAdminSemiAutoTask, } from '@/services/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 { resolvePostInjectionUrl } from '@/utils/semi-auto-injection' 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_FOLLOW_UP_TIMEOUT_MS = 30_000 type PendingInjection = { taskId: number platform: SemiAutoTask['platform'] popup: Window | null timeoutId: number } export default function AdminSemiAutoTasksPage() { const { message, modal } = App.useApp() const queryClient = useQueryClient() const [keyword, setKeyword] = useState('') const [platform, setPlatform] = useState('') 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) const params = useMemo( () => ({ page, pageSize, keyword: keyword.trim() || undefined, platform: platform || undefined, status: status || undefined, }), [keyword, page, pageSize, platform, status], ) 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 detail = (event as CustomEvent).detail if (typeof detail !== 'string') return let result: { ok?: boolean; written?: number; error?: string } try { result = JSON.parse(detail) as { ok?: boolean; written?: number; error?: string } } catch { return } if (!result || typeof result !== 'object') return const pending = pendingInjectionRef.current if (result.ok) { message.success(`浏览器登录态已注入(${Number(result.written || 0)} 个 Cookie)`) if (!pending) return window.clearTimeout(pending.timeoutId) pendingInjectionRef.current = null const targetUrl = resolvePostInjectionUrl(pending.platform) const popup = pending.popup if (!targetUrl) { if (popup && !popup.closed) popup.close() return } if (popup && !popup.closed) { try { popup.location.href = targetUrl popup.focus() return } catch { // 占位页已被关闭或无法导航:先关掉残留标签,再用 window.open 兜底。 try { popup.close() } catch { // 关闭失败不影响继续打开目标页。 } } } const opened = window.open(targetUrl, '_blank') if (opened) { opened.focus() return } modal.info({ title: '注入成功', content: ( 浏览器拦截了自动打开的新标签页,请 点击这里打开平台页面 。 ), }) return } message.error(result.error || '浏览器登录态注入失败') if (!pending) return window.clearTimeout(pending.timeoutId) pendingInjectionRef.current = null if (pending.popup && !pending.popup.closed) pending.popup.close() } window.addEventListener('huya-exchange-result', handleResult) return () => window.removeEventListener('huya-exchange-result', handleResult) }, [message, modal]) // 页面卸载时清理未完成的占位页,避免留下空白标签。 useEffect(() => { return () => { const pending = pendingInjectionRef.current if (!pending) return window.clearTimeout(pending.timeoutId) if (pending.popup && !pending.popup.closed) pending.popup.close() 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) if (pending.popup && !pending.popup.closed) pending.popup.close() pendingInjectionRef.current = null } function openInjectionPlaceholder() { const popup = window.open('about:blank', '_blank') if (!popup) return null try { popup.document.title = '正在注入浏览器登录态' popup.document.body.textContent = '正在注入浏览器登录态,完成后将自动打开平台页面…' } catch { // 占位内容写入失败不影响后续跳转。 } return popup } const injectionMutation = useMutation({ mutationFn: (task: SemiAutoTask) => createAdminSemiAutoBrowserSession(task.id, firstTargetUrl(task)), onSuccess: (response) => { const ticket = String(response.data?.ticket || '').trim() if (!ticket) { cancelPendingInjection() message.error('注入票据生成失败') return } window.postMessage({ type: 'ORDER_SITE_SEMI_AUTO_INJECT', ticket }, window.location.origin) message.info('正在注入浏览器登录态,请稍候') void refreshAll() }, onError: (error) => { cancelPendingInjection() message.error(error instanceof Error ? error.message : '打开浏览器登录态失败') }, }) function startInjection(task: SemiAutoTask) { if (pendingInjectionRef.current) { message.warning('上一次注入尚未完成,请稍候') return } // 扩展内容脚本会在白名单页面打标记;没有标记时直接提示,避免空等 30 秒。 if (document.documentElement.dataset.huyaExchangeHelper !== '1') { message.warning('未检测到浏览器扩展,请启用「虎牙兑换助手」后刷新本页') return } const popup = openInjectionPlaceholder() const timeoutId = window.setTimeout(() => { const pending = pendingInjectionRef.current if (!pending) return pendingInjectionRef.current = null if (pending.popup && !pending.popup.closed) pending.popup.close() message.warning('未检测到注入完成,请确认浏览器扩展已启用后重试') }, INJECTION_FOLLOW_UP_TIMEOUT_MS) pendingInjectionRef.current = { taskId: task.id, platform: task.platform, popup, timeoutId, } injectionMutation.mutate(task) } 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 失败'), }) 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(), ]) } 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: '客户登录', 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.bindGameRoleToken ? ( {`当前角色:${task.bindGameRole || '-'}${ task.bindGameRoleToken ? '(平台加密标识已识别)' : '' }`} ) : 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} ), }, ] 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: 1400 }} pagination={{ current: pagination?.page || page, pageSize: pagination?.pageSize || pageSize, total: pagination?.total || 0, showSizeChanger: true, onChange: (nextPage, nextPageSize) => { setPage(nextPage) setPageSize(nextPageSize) }, }} /> setDetailTaskId(null)} > {detailQuery.isLoading ? ( 加载中... ) : detail?.task ? ( {detail.task.productName} {PLATFORM_LABELS[detail.task.platform] || detail.task.platform} {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 ? `游戏角色 UID ${detail.task.platformGameRoleUid}` : detail.task.bindGameRoleToken || detail.task.pendingBindGameRoleToken ? '已识别的虎牙加密角色标识' : '-'} {[ 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] || '-'} {detail.task.bindingDecision?.message || '-'} {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 firstTargetUrl(task: SemiAutoTask) { const targets = Array.isArray(task.semiAutoConfig?.browserTargets) ? task.semiAutoConfig.browserTargets : [] return String(targets.find((item) => item?.url)?.url || '') } 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' ) }