Files
order_site/apps/frontend/src/pages/douyu-fulfillment/DouyuFulfillmentPage.tsx
T

667 lines
23 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {
CheckCircleFilled,
ExclamationCircleOutlined,
LoadingOutlined,
QrcodeOutlined,
ReloadOutlined,
} from '@ant-design/icons'
import { Alert, App, Button, Image, Input, Progress, Space, Spin } from 'antd'
import QRCode from 'qrcode'
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { useParams } from 'react-router'
import {
confirmDouyuBinding,
fetchDouyuFulfillment,
refreshDouyuBinding,
saveDouyuProfile,
startDouyuBinding,
} from '@/services/douyu-fulfillment'
import type {
DouyuCustomerFulfillment,
DouyuCustomerPlatform,
DouyuCustomerSystem,
} from '@/types/douyu-fulfillment'
import { formatAdminDateTime } from '@/utils/admin-time'
import { DOUYU_ROLE_NAME_FORMAT_HINT, getDouyuRoleNameIssue } from '@/utils/douyu-role-name'
import { useRealtimeEvents } from '@/hooks/useRealtimeEvents'
const BINDING_FAILURE_ISSUES = new Set([
'binding_failed',
'account_role_cooldown',
'customer_role_cooldown',
])
const STATUS_LABELS: Record<string, string> = {
waiting_profile: '等待填写资料',
preparing: '正在准备账号',
allocated: '账号已分配',
qr_pending: '等待扫码绑定',
role_ready: '请确认游戏角色',
bound: '角色已绑定',
waiting_operator: '待客服处理',
processing: '正在兑换',
completed: '领取完成',
failed: '角色绑定失败',
manual_required: '等待人工处理',
cancelled: '订单已取消',
}
function platformLabel(value: string) {
if (value === 'wechat') return '微信'
if (value === 'qq') return 'QQ'
return '未填写'
}
function systemLabel(value: string) {
if (value === 'ios') return '苹果'
if (value === 'android') return '安卓'
return '未填写'
}
function formatRemainingTime(totalSeconds: number) {
const seconds = Math.max(0, Math.ceil(totalSeconds))
const minutes = Math.floor(seconds / 60)
const rest = seconds % 60
return `${String(minutes).padStart(2, '0')}:${String(rest).padStart(2, '0')}`
}
export default function DouyuFulfillmentPage() {
const { message } = App.useApp()
const { orderNo = '' } = useParams<{ orderNo: string }>()
const [data, setData] = useState<DouyuCustomerFulfillment | null>(null)
const [loading, setLoading] = useState(true)
const [loadError, setLoadError] = useState('')
const [saving, setSaving] = useState(false)
const [bindingLoading, setBindingLoading] = useState(false)
const [roleName, setRoleName] = useState('')
const [platform, setPlatform] = useState<DouyuCustomerPlatform>('wechat')
const [system, setSystem] = useState<DouyuCustomerSystem>('android')
const [qrImage, setQrImage] = useState('')
const [bindingQrExpanded, setBindingQrExpanded] = useState(false)
const [nowMs, setNowMs] = useState(() => Date.now())
const customerRoleRef = useRef('')
const roleNameIssue = useMemo(() => getDouyuRoleNameIssue(roleName), [roleName])
const applyData = useCallback((next: DouyuCustomerFulfillment) => {
const previousRole = customerRoleRef.current
const nextRole = next.task.customer_role_name || ''
customerRoleRef.current = nextRole
setData(next)
if (previousRole && !nextRole) {
setRoleName('')
setPlatform('wechat')
setSystem('android')
} else {
setRoleName((current) => current || nextRole)
}
if (next.task.customer_platform === 'qq' || next.task.customer_platform === 'wechat') {
setPlatform(next.task.customer_platform)
}
if (next.task.customer_system === 'ios' || next.task.customer_system === 'android') {
setSystem(next.task.customer_system)
}
}, [])
const load = useCallback(
async (silent = false) => {
if (!orderNo) {
setLoadError('订单号无效')
setLoading(false)
return
}
if (!silent) setLoading(true)
try {
const response = await fetchDouyuFulfillment(orderNo)
applyData(response.data)
setLoadError('')
} catch (error) {
if (!silent) {
setLoadError(error instanceof Error ? error.message : '读取订单失败')
}
} finally {
if (!silent) setLoading(false)
}
},
[applyData, orderNo],
)
useEffect(() => {
void load()
}, [load])
useRealtimeEvents({
url: orderNo ? `/api/v1/douyu-fulfillment/${encodeURIComponent(orderNo)}/realtime` : '',
allowAnonymous: true,
onConnected: () => {
void load(true)
},
onResync: () => {
void load(true)
},
onEvent: (event) => {
if (
event.type === 'customer_order.changed' &&
event.scopes.includes(`customer_order:${orderNo}`)
) {
void load(true)
}
},
})
const task = data?.task
const live = data?.live
const needsProfile = Boolean(task && !task.customer_role_name)
const bindingFailed = Boolean(live && BINDING_FAILURE_ISSUES.has(live.issueCode))
useEffect(() => {
const url = live?.qrUrl || ''
if (!url) {
setQrImage('')
return
}
void QRCode.toDataURL(url, {
width: 320,
margin: 2,
color: { dark: '#111827', light: '#e8ebef' },
}).then(setQrImage)
}, [live?.qrUrl])
useEffect(() => {
setBindingQrExpanded(false)
}, [live?.bindConfirmed, live?.bindReadyForConfirm, live?.qrUrl])
useEffect(() => {
const tick = () => setNowMs(Date.now())
tick()
const timer = window.setInterval(tick, 1000)
return () => window.clearInterval(timer)
}, [live?.qrExpiresAt])
const expiresInSeconds = useMemo(() => {
const raw = live?.qrExpiresAt || ''
const expiresAt = raw ? Date.parse(raw) : 0
if (!expiresAt || Number.isNaN(expiresAt)) return 0
return Math.max(0, Math.floor((expiresAt - nowMs) / 1000))
}, [live?.qrExpiresAt, nowMs])
const qrExpired = Boolean(live?.qrUrl && live.qrExpiresAt && expiresInSeconds <= 0)
const qrTotalSeconds = (() => {
const generatedAt = live?.qrGeneratedAt ? Date.parse(live.qrGeneratedAt) : 0
const expiresAt = live?.qrExpiresAt ? Date.parse(live.qrExpiresAt) : 0
if (!generatedAt || !expiresAt || Number.isNaN(generatedAt) || Number.isNaN(expiresAt)) {
return 600
}
return Math.max(1, Math.floor((expiresAt - generatedAt) / 1000))
})()
const qrProgressPercent = Math.max(0, Math.min(100, (expiresInSeconds / qrTotalSeconds) * 100))
const canRevealBindingQr = Boolean(
live?.qrUrl && (live.bindReadyForConfirm || live.bindConfirmed),
)
const showBindingQr = Boolean(live?.qrUrl && (!canRevealBindingQr || bindingQrExpanded))
const waitingForSupport = Boolean(
task && (live?.bindConfirmed || task.status === 'waiting_operator' || task.status === 'bound'),
)
const bindingFailureMessage =
live?.issueCode === 'account_role_cooldown'
? '当前斗鱼账号暂不可换绑,本次绑定未生效。'
: live?.issueCode === 'customer_role_cooldown'
? '该游戏角色仍处于换绑冷却期,本次绑定未生效。'
: '本次游戏角色绑定失败。'
const bindingDescription = live?.bindConfirmed
? '角色绑定已完成,待客服处理。'
: live?.bindReadyForConfirm
? '已识别游戏角色,请核对并确认绑定。'
: bindingFailed
? bindingFailureMessage
: qrExpired
? '当前二维码已过期,请刷新二维码后重新扫码。'
: live?.issueCode === 'binding_failed'
? '暂未识别到绑定角色,请继续使用当前二维码完成扫码。'
: !live?.accountReady
? '系统正在自动准备账号和二维码,请稍候,无需重复操作。'
: live?.qrUrl
? '必须使用微信扫码。请选择与资料一致的和平精英角色,QQ 扫码或其他方式无效。'
: live?.message || '正在准备绑定二维码,请稍候。'
const bindingStageTitle =
task?.status === 'qr_pending' && live?.qrUrl
? '必须使用微信扫码绑定'
: STATUS_LABELS[task?.status || ''] || '等待处理'
async function submitProfile() {
if (!roleName.trim()) {
message.warning('请输入游戏角色名')
return
}
if (roleNameIssue) {
message.warning(roleNameIssue)
return
}
setSaving(true)
try {
const response = await saveDouyuProfile(orderNo, {
roleName: roleName.trim(),
platform,
system,
})
applyData(response.data)
message.success('资料已提交,正在准备绑定二维码')
} catch (error) {
message.error(error instanceof Error ? error.message : '提交资料失败')
} finally {
setSaving(false)
}
}
async function startBinding(forceRefresh = false) {
setBindingLoading(true)
try {
if (forceRefresh) {
const refreshed = await refreshDouyuBinding(orderNo)
applyData(refreshed.data)
const refreshedLive = refreshed.data.live
const expiresAt = refreshedLive.qrExpiresAt ? Date.parse(refreshedLive.qrExpiresAt) : 0
if (refreshedLive.qrUrl && expiresAt > Date.now()) {
message.info('二维码仍在有效期内,已复用当前二维码')
return
}
}
const response = await startDouyuBinding(orderNo, forceRefresh)
applyData(response.data)
message.success(forceRefresh ? '二维码已刷新' : '绑定流程已继续')
} catch (error) {
message.error(error instanceof Error ? error.message : '生成绑定二维码失败')
} finally {
setBindingLoading(false)
}
}
async function refreshStatus() {
setBindingLoading(true)
try {
const response = await refreshDouyuBinding(orderNo)
applyData(response.data)
message.success('绑定状态已刷新')
} catch (error) {
message.error(error instanceof Error ? error.message : '刷新绑定状态失败')
} finally {
setBindingLoading(false)
}
}
async function confirmBinding() {
setBindingLoading(true)
try {
const response = await confirmDouyuBinding(orderNo)
applyData(response.data)
message.success('角色绑定已确认,待客服处理')
} catch (error) {
message.error(error instanceof Error ? error.message : '确认角色绑定失败')
} finally {
setBindingLoading(false)
}
}
if (loading) {
return (
<CustomerFrame>
<div className="customer-auth-loading">
<Spin indicator={<LoadingOutlined spin />} />
<span>正在读取订单...</span>
</div>
</CustomerFrame>
)
}
if (loadError || !data || !task) {
return (
<CustomerFrame>
<div className="customer-auth-state is-error">
<h2>暂时无法打开订单</h2>
<p>{loadError || '订单信息不存在'}</p>
</div>
</CustomerFrame>
)
}
if (task.status === 'completed') {
return (
<CustomerFrame>
<OrderCard data={data} />
<div className="customer-auth-state is-success">
<div className="customer-auth-state-icon">
<CheckCircleFilled />
</div>
<h2>领取已完成</h2>
<p>运营已完成本订单兑换,请到和平精英账号中确认。</p>
{task.completed_at ? (
<span className="customer-auth-state-time">
完成时间:{formatAdminDateTime(task.completed_at)}
</span>
) : null}
</div>
</CustomerFrame>
)
}
if (task.status === 'cancelled') {
return (
<CustomerFrame>
<OrderCard data={data} />
<Alert
className="customer-order-closed-alert"
type="warning"
showIcon
message="订单领取已关闭"
description="如订单发生退款或取消,请联系客服确认。"
/>
</CustomerFrame>
)
}
return (
<CustomerFrame
compact={Boolean(
live?.qrUrl && !live.bindReadyForConfirm && !live.bindConfirmed && !bindingFailed,
)}
>
<OrderCard data={data} />
{needsProfile ? (
<section className="customer-auth-section">
<div className="customer-auth-section-heading">
<div>
<h2>填写游戏角色</h2>
<p>资料用于核对扫码绑定的和平精英角色。</p>
</div>
</div>
<div className="customer-collect-body">
<label className="customer-collect-label">登录方式</label>
<ChoiceSwitch
ariaLabel="登录方式"
value={platform}
onChange={setPlatform}
options={[
{ label: '微信', value: 'wechat' },
{ label: 'QQ', value: 'qq' },
]}
/>
<label className="customer-collect-label">设备系统</label>
<ChoiceSwitch
ariaLabel="设备系统"
value={system}
onChange={setSystem}
options={[
{ label: '安卓', value: 'android' },
{ label: '苹果', value: 'ios' },
]}
/>
<label className="customer-collect-label">游戏角色名</label>
<Input
className={`customer-collect-input${roleNameIssue ? ' is-warning' : ''}`}
value={roleName}
onChange={(event) => setRoleName(event.target.value)}
placeholder="请输入和平精英角色名"
maxLength={100}
aria-invalid={Boolean(roleNameIssue)}
aria-describedby="douyu-role-name-help"
/>
<p
id="douyu-role-name-help"
className={`customer-douyu-role-name-help${roleNameIssue ? ' is-warning' : ''}`}
aria-live="polite"
>
{roleNameIssue ? <ExclamationCircleOutlined aria-hidden="true" /> : null}
<span>{roleNameIssue || DOUYU_ROLE_NAME_FORMAT_HINT}</span>
</p>
<Button
block
size="large"
className="customer-collect-submit"
loading={saving}
onClick={() => void submitProfile()}
>
提交资料并继续
</Button>
</div>
</section>
) : waitingForSupport ? (
<section className="customer-binding-stage">
<Alert type="success" showIcon message="待客服处理" />
</section>
) : (
<section className="customer-binding-stage">
{bindingFailed ? (
<div className="customer-douyu-binding-failure">
<Alert
type="error"
showIcon
message="角色绑定失败"
description={bindingFailureMessage}
/>
<p>请截图本页面并联系客服处理,客服会根据截图重新安排绑定。</p>
</div>
) : (
<Alert
className={live?.qrUrl ? 'customer-douyu-binding-alert is-wechat' : undefined}
type={qrExpired ? 'warning' : live?.bindConfirmed ? 'success' : 'info'}
showIcon
message={bindingStageTitle}
description={bindingDescription}
/>
)}
{!bindingFailed && canRevealBindingQr ? (
<Button
className="customer-binding-qr-toggle"
icon={<QrcodeOutlined />}
onClick={() => setBindingQrExpanded((current) => !current)}
>
{bindingQrExpanded ? '收起绑定二维码' : '查看绑定二维码'}
</Button>
) : null}
{!bindingFailed &&
!live?.qrUrl &&
!live?.bindReadyForConfirm &&
task.status !== 'completed' ? (
<div className="customer-binding-qr-card customer-douyu-preparing-card">
<h3>游戏角色绑定二维码</h3>
<div className="customer-douyu-qr-main">
<span className="customer-douyu-qr-rail" aria-hidden="true">
必须使用微信扫码
</span>
<div className="customer-binding-qr-code">
<div className="customer-douyu-qr-preparing">
<div className="customer-douyu-qr-skeleton" aria-hidden="true" />
<div className="customer-douyu-qr-preparing-copy">
<Spin />
<strong>正在生成二维码</strong>
<span>系统会自动刷新,请稍候</span>
</div>
</div>
</div>
<span className="customer-douyu-qr-rail" aria-hidden="true">
必须使用微信扫码
</span>
</div>
<p className="customer-binding-qr-hint">
二维码准备完成后,必须使用微信扫码并选择游戏角色。
</p>
<Button
block
size="large"
className="customer-douyu-preparing-button"
loading={bindingLoading}
onClick={() => void refreshStatus()}
>
刷新状态
</Button>
</div>
) : null}
{!bindingFailed && live?.qrUrl && showBindingQr ? (
<div className="customer-binding-qr-card">
<h3>游戏角色绑定二维码</h3>
<div className="customer-douyu-qr-main">
<span className="customer-douyu-qr-rail" aria-hidden="true">
必须使用微信扫码
</span>
<div className="customer-binding-qr-code">
{qrImage ? (
<Image
src={qrImage}
alt="和平精英角色绑定二维码"
width="100%"
preview={false}
/>
) : (
<div className="customer-auth-qr-placeholder">
<Spin />
<span>正在生成二维码图片...</span>
</div>
)}
</div>
<span className="customer-douyu-qr-rail" aria-hidden="true">
必须使用微信扫码
</span>
</div>
<p className="customer-binding-qr-hint">
必须使用微信扫码,并选择与资料一致的和平精英角色。
</p>
{qrExpired ? (
<div className="customer-binding-qr-countdown is-expired">二维码已过期</div>
) : (
<div className="customer-binding-qr-countdown">
二维码有效期剩余 {formatRemainingTime(expiresInSeconds)}
</div>
)}
<Progress percent={qrProgressPercent} showInfo={false} />
<div className="customer-binding-qr-actions is-single">
<Button
icon={<ReloadOutlined />}
loading={bindingLoading}
disabled={!qrExpired}
onClick={() => void startBinding(true)}
>
刷新二维码
</Button>
</div>
<p className="customer-douyu-qr-refresh-note">
{qrExpired
? '二维码已过期,请刷新后重新扫码'
: '二维码有效期内无需刷新,过期后可重新生成'}
</p>
</div>
) : null}
{!bindingFailed && live?.bindReadyForConfirm ? (
<div className="customer-binding-qr-card">
<h3>核对绑定角色</h3>
<p className="customer-binding-qr-hint">
平台识别角色:{live.roleName || '-'} · {live.areaName || '-'} ·{' '}
{live.platName || '-'}
</p>
<p className="customer-binding-qr-hint">
已填资料:{task.customer_role_name} · {platformLabel(task.customer_platform)} ·{' '}
{systemLabel(task.customer_system)}
</p>
<Alert
type={data.comparison.matched ? 'success' : 'warning'}
showIcon
message={data.comparison.matched ? '角色信息一致' : '角色信息不一致'}
description={data.comparison.message}
/>
<Space direction="vertical" size={10} style={{ width: '100%' }}>
<Button
block
size="large"
type="primary"
disabled={!data.comparison.matched}
loading={bindingLoading}
onClick={() => void confirmBinding()}
>
确认绑定角色
</Button>
<Button
block
danger
icon={<ExclamationCircleOutlined />}
onClick={() => {
setData({ ...data, task: { ...task, customer_role_name: '' } })
}}
>
修改资料
</Button>
</Space>
</div>
) : null}
</section>
)}
</CustomerFrame>
)
}
function ChoiceSwitch<T extends string>(input: {
value: T
options: ReadonlyArray<{ label: string; value: T }>
ariaLabel: string
onChange: (value: T) => void
}) {
return (
<div className="customer-choice-switch" role="radiogroup" aria-label={input.ariaLabel}>
{input.options.map((option) => {
const selected = input.value === option.value
return (
<button
key={option.value}
type="button"
role="radio"
aria-checked={selected}
className={`customer-choice-option${selected ? ' is-selected' : ''}`}
onClick={() => input.onChange(option.value)}
>
{option.label}
</button>
)
})}
</div>
)
}
function CustomerFrame({ compact = false, children }: { compact?: boolean; children: ReactNode }) {
return (
<div className={`customer-auth-page is-huya is-douyu${compact ? ' is-compact' : ''}`}>
<div className="customer-auth-shell">
<header className="customer-auth-hero" aria-hidden="true" />
<div className="customer-auth-warning">温馨提示:未成年人禁止下单</div>
<main className="customer-auth-main">{children}</main>
</div>
</div>
)
}
function OrderCard({ data }: { data: DouyuCustomerFulfillment }) {
return (
<section className="customer-order-card customer-douyu-order-card">
<div className="customer-douyu-order-head">
<h3>订单信息</h3>
<strong
className={`customer-order-status customer-douyu-order-status is-${data.task.status}`}
>
{STATUS_LABELS[data.task.status] || data.task.status}
</strong>
</div>
<div className="customer-douyu-order-field">
<span>订单号</span>
<strong>{data.task.platform_order_id}</strong>
</div>
<div className="customer-douyu-order-field">
<span>商品</span>
<strong>
{data.task.product_name || data.task.sku_name} × {data.task.quantity}
</strong>
</div>
</section>
)
}