import { CheckCircleOutlined, ReloadOutlined, RollbackOutlined, SearchOutlined, SendOutlined, SyncOutlined, } from '@ant-design/icons' import { Alert, Button, Card, DatePicker, Input, InputNumber, Select, Space, Table, Tabs, Tag, Typography, } from 'antd' import type { TableColumnsType } from 'antd' import dayjs from 'dayjs' import type { Dayjs } from 'dayjs' import { useEffect, useMemo, useState } from 'react' import PageHeader from '@/components/admin/PageHeader' import { showError, showSuccess } from '@/lib/feedback' import { approveAdminKuaishouIndustryRefund, checkAdminKuaishouIndustryVoucherAvailable, consumeAdminKuaishouIndustryVoucher, disagreeAdminKuaishouIndustryRefund, fetchAdminKuaishouIndustryVouchers, listAdminKuaishouIndustryRefunds, resendAdminKuaishouIndustryVoucherCode, reverseAdminKuaishouIndustryVoucher, } from '@/services/admin' import type { AdminKuaishouIndustryOpenApiResult, AdminKuaishouIndustryRefundApprovePayload, AdminKuaishouIndustryRefundDisagreePayload, AdminKuaishouIndustryRefundListPayload, AdminKuaishouIndustryVoucher, AdminKuaishouIndustryVoucherToolPayload, } from '@/types/admin' import { formatAdminDateTime } from '@/utils/admin-time' import { stringifyDisplayJson } from '@/utils/date-time' type DateRangeValue = [Dayjs | null, Dayjs | null] | null type IndustryTab = 'vouchers' | 'refunds' | 'result' type VoucherFilterState = { oid: string voucherCode: string taskId: string sellerId: string status: string page: number pageSize: number } type RefundListState = { sellerId: string orderId: string type: string pageSize: string currentPage: string pcursor: string status: string negotiateStatus: string } const DEFAULT_ETICKET_TYPE = 'DINING_OPEN_TICKET' export default function AdminKuaishouIndustryPage() { const [activeTab, setActiveTab] = useState('vouchers') const [voucherLoading, setVoucherLoading] = useState(false) const [actionLoading, setActionLoading] = useState('') const [vouchers, setVouchers] = useState([]) const [voucherTotal, setVoucherTotal] = useState(0) const [voucherFilters, setVoucherFilters] = useState({ oid: '', voucherCode: '', taskId: '', sellerId: '', status: '', page: 1, pageSize: 50, }) const [toolForm, setToolForm] = useState({ eticketType: DEFAULT_ETICKET_TYPE, consumeType: 'consume', }) const [refundDateRange, setRefundDateRange] = useState(() => [ dayjs().subtract(1, 'day'), dayjs(), ]) const [refundListForm, setRefundListForm] = useState({ sellerId: '', orderId: '', type: '8', pageSize: '50', currentPage: '1', pcursor: '', status: '10', negotiateStatus: '', }) const [approveForm, setApproveForm] = useState({ refundId: '', refundAmount: '', status: '', negotiateStatus: '', refundHandingWay: '10', }) const [disagreeForm, setDisagreeForm] = useState({ refundId: '', sellerDisagreeReason: '100', sellerDisagreeDesc: '', status: '10', negotiateStatus: '1', }) const [lastResultTitle, setLastResultTitle] = useState('接口结果') const [lastResult, setLastResult] = useState(null) const [refundRows, setRefundRows] = useState>>([]) const columns = useMemo>( () => [ { title: '券码', minWidth: 220, render: (_, row) => (
{row.voucherCode} 序号:{row.unitIndex}
), }, { title: '订单 / 任务', minWidth: 220, render: (_, row) => (
{row.oid || '-'} 任务:{row.taskId || '-'} / 订单:{row.orderId || '-'}
), }, { title: '状态', width: 150, render: (_, row) => (
{getVoucherStatusLabel(row.status)} 发码:{row.sendCallbackStatus || '-'}
), }, { title: '卖家', minWidth: 160, render: (_, row) => (
{row.sellerId || '-'} Token:{row.tokenMasked || '-'}
), }, { title: '核销', minWidth: 180, render: (_, row) => (
{row.consumeSerialNum || '-'} {formatAdminDateTime(row.consumedAt)}
), }, { title: '更新时间', width: 170, render: (_, row) => formatAdminDateTime(row.updatedAt), }, { title: '操作', fixed: 'right', width: 120, render: (_, row) => ( ), }, ], [], ) const refundColumns = useMemo>>( () => [ { title: '售后单', dataIndex: 'refundId', minWidth: 160 }, { title: '订单', dataIndex: 'oid', minWidth: 160 }, { title: '状态', dataIndex: 'status', width: 100 }, { title: '协商', dataIndex: 'negotiateStatus', width: 100 }, { title: '金额', dataIndex: 'refundFee', width: 100 }, { title: '提交时间', minWidth: 170, render: (_, row) => formatTimestamp(row.submitTime || row.createTime), }, { title: '操作', fixed: 'right', width: 120, render: (_, row) => ( ), }, ], [], ) useEffect(() => { void loadVouchers() }, []) async function loadVouchers(nextFilters: Partial = {}) { const filters = { ...voucherFilters, ...nextFilters } setVoucherFilters(filters) setVoucherLoading(true) try { const response = await fetchAdminKuaishouIndustryVouchers({ oid: filters.oid.trim(), voucherCode: filters.voucherCode.trim(), taskId: filters.taskId.trim(), sellerId: filters.sellerId.trim(), status: filters.status, page: filters.page, pageSize: filters.pageSize, }) setVouchers(response.data.items) setVoucherTotal(response.data.pagination.total) } catch (error) { showError(error instanceof Error ? error.message : '查询电子凭证失败') } finally { setVoucherLoading(false) } } function selectVoucher(row: AdminKuaishouIndustryVoucher) { setToolForm((current) => ({ ...current, sellerId: row.sellerId, oid: row.oid, orderId: row.oid, taskId: row.taskId || '', voucherCode: row.voucherCode, serialNum: row.consumeSerialNum || current.serialNum, })) showSuccess('已填入券码操作区') } async function runCheckAvailable() { await runOpenApiAction('检查电子凭证有效性', 'check', () => checkAdminKuaishouIndustryVoucherAvailable(buildVoucherToolPayload()), ) } async function runReverse() { await runOpenApiAction('电子凭证冲正回调', 'reverse', () => reverseAdminKuaishouIndustryVoucher({ ...buildVoucherToolPayload(), reason: toolForm.reason || '后台手动冲正', }), ) await loadVouchers() } async function runConsume() { setActionLoading('consume') try { const response = await consumeAdminKuaishouIndustryVoucher(buildVoucherToolPayload()) setLastResultTitle('手动核销') setLastResult(response.data) setActiveTab('result') showSuccess('手动核销已完成') await loadVouchers() } catch (error) { showError(error instanceof Error ? error.message : '手动核销失败') } finally { setActionLoading('') } } async function runResendCode() { setActionLoading('resend') try { const response = await resendAdminKuaishouIndustryVoucherCode(buildVoucherToolPayload()) setLastResultTitle('重发发码回调') setLastResult(response.data) setActiveTab('result') if (response.data.success) { showSuccess('发码回调已重发') } else { showError(response.data.error || '发码回调重发失败') } await loadVouchers() } catch (error) { showError(error instanceof Error ? error.message : '重发发码回调失败') } finally { setActionLoading('') } } async function runRefundList() { const [begin, end] = refundDateRange || [] await runOpenApiAction('售后单列表', 'refund-list', () => listAdminKuaishouIndustryRefunds({ ...refundListForm, beginTime: begin?.valueOf(), endTime: end?.valueOf(), } satisfies AdminKuaishouIndustryRefundListPayload), (result) => { const rows = extractRefundRows(result.response) setRefundRows(rows) }, ) } async function runApproveRefund() { await runOpenApiAction('同意退款', 'refund-approve', () => approveAdminKuaishouIndustryRefund({ ...approveForm, sellerId: approveForm.sellerId || refundListForm.sellerId, }), ) } async function runDisagreeRefund() { await runOpenApiAction('不同意退款', 'refund-disagree', () => disagreeAdminKuaishouIndustryRefund({ ...disagreeForm, sellerId: disagreeForm.sellerId || refundListForm.sellerId, }), ) } async function runOpenApiAction( title: string, loadingKey: string, action: () => Promise<{ data: AdminKuaishouIndustryOpenApiResult }>, afterSuccess?: (result: AdminKuaishouIndustryOpenApiResult) => void, ) { setActionLoading(loadingKey) try { const response = await action() setLastResultTitle(title) setLastResult(response.data) setActiveTab('result') afterSuccess?.(response.data) if (response.data.success) { showSuccess(`${title}已执行`) } else { showError(response.data.error || `${title}返回失败`) } } catch (error) { showError(error instanceof Error ? error.message : `${title}失败`) } finally { setActionLoading('') } } function buildVoucherToolPayload(): AdminKuaishouIndustryVoucherToolPayload { const voucherCode = String(toolForm.voucherCode || '').trim() return { ...toolForm, etickets: voucherCode ? [{ id: voucherCode, code: voucherCode, num: 1 }] : undefined, } } function fillRefundAction(row: Record) { const refundId = String(row.refundId || '').trim() const status = String(row.status || '').trim() const negotiateStatus = String(row.negotiateStatus || '').trim() setApproveForm((current) => ({ ...current, refundId, status, negotiateStatus, refundAmount: String(row.refundFee || current.refundAmount || ''), })) setDisagreeForm((current) => ({ ...current, refundId, status, negotiateStatus: negotiateStatus || current.negotiateStatus, })) showSuccess('已填入退款操作区') } return (
setActiveTab(key as IndustryTab)} items={[ { key: 'vouchers', label: '券码操作', children: renderVoucherTab(), }, { key: 'refunds', label: '售后退款', children: renderRefundTab(), }, { key: 'result', label: '接口结果', children: renderResultTab(), }, ]} />
) function renderVoucherTab() { return (
setVoucherFilters({ ...voucherFilters, oid: event.target.value })} /> setVoucherFilters({ ...voucherFilters, voucherCode: event.target.value }) } /> setVoucherFilters({ ...voucherFilters, taskId: event.target.value }) } /> setVoucherFilters({ ...voucherFilters, sellerId: event.target.value }) } /> updateToolForm({ sellerId: event.target.value })} /> updateToolForm({ oid: event.target.value, orderId: event.target.value }) } /> updateToolForm({ taskId: event.target.value })} /> updateToolForm({ voucherCode: event.target.value })} /> updateToolForm({ eticketType: event.target.value })} /> updateToolForm({ serialNum: event.target.value })} /> updateToolForm({ consumeType: event.target.value })} /> updateToolForm({ reason: event.target.value })} /> updateToolForm({ storeName: event.target.value })} /> updateToolForm({ storeAddress: event.target.value })} />
) } function renderRefundTab() { return (
updateRefundListForm({ sellerId: event.target.value })} /> updateRefundListForm({ orderId: event.target.value })} /> setRefundDateRange(value)} /> updateRefundListForm({ status: event.target.value })} /> updateRefundListForm({ pcursor: event.target.value })} /> updateRefundListForm({ pageSize: String(value || 50) })} /> String(row.refundId || row.oid || JSON.stringify(row))} columns={refundColumns} dataSource={refundRows} scroll={{ x: 980 }} pagination={{ pageSize: 10 }} style={{ marginTop: 16 }} />
setApproveForm({ ...approveForm, sellerId: event.target.value })} /> setApproveForm({ ...approveForm, refundId: event.target.value })} /> setApproveForm({ ...approveForm, refundAmount: event.target.value }) } /> setApproveForm({ ...approveForm, status: event.target.value })} /> setApproveForm({ ...approveForm, negotiateStatus: event.target.value }) } /> setApproveForm({ ...approveForm, refundHandingWay: event.target.value }) } /> setApproveForm({ ...approveForm, desc: event.target.value })} />
setDisagreeForm({ ...disagreeForm, sellerId: event.target.value }) } /> setDisagreeForm({ ...disagreeForm, refundId: event.target.value }) } /> setDisagreeForm({ ...disagreeForm, sellerDisagreeReason: event.target.value }) } /> setDisagreeForm({ ...disagreeForm, sellerDisagreeDesc: event.target.value }) } /> setDisagreeForm({ ...disagreeForm, status: event.target.value }) } /> setDisagreeForm({ ...disagreeForm, negotiateStatus: event.target.value }) } />
) } function renderResultTab() { const summary = resolveOpenApiResultSummary(lastResult) return ( } onClick={() => setLastResult(null)}> 清空 } > {lastResult ? (
{stringifyDisplayJson(lastResult)}
) : ( )}
) } function updateToolForm(patch: Partial) { setToolForm((current) => ({ ...current, ...patch })) } function updateRefundListForm(patch: Partial) { setRefundListForm((current) => ({ ...current, ...patch })) } } function extractRefundRows(response: Record | null): Array> { const data = response?.data if (!data || typeof data !== 'object' || Array.isArray(data)) { return [] } const rows = (data as { refundOrderInfoList?: unknown }).refundOrderInfoList return Array.isArray(rows) ? rows.filter((item): item is Record => Boolean(item && typeof item === 'object' && !Array.isArray(item)), ) : [] } function resolveOpenApiResultSummary(value: unknown) { const result = value && typeof value === 'object' && !Array.isArray(value) ? value as Record : {} const response = result.response && typeof result.response === 'object' && !Array.isArray(result.response) ? result.response as Record : null const success = Boolean(result.success) const code = String(response?.code || response?.sub_code || '').trim() const resultCode = String(response?.result || '').trim() const message = String( response?.error_msg || response?.msg || response?.sub_msg || response?.message || result.error || '', ).trim() const status = Number(result.httpStatus || 0) || 0 const durationMs = Number(result.durationMs || 0) || 0 const markers = [ status ? `HTTP ${status}` : '', resultCode ? `result=${resultCode}` : '', code ? `code=${code}` : '', durationMs ? `${durationMs}ms` : '', ].filter(Boolean) return { success, title: success ? '接口返回成功' : '接口返回失败', description: [markers.join(' / '), message].filter(Boolean).join(',') || '请查看下方原始响应。', } } function getVoucherStatusColor(status: string) { const normalized = String(status || '').toUpperCase() if (normalized === 'CONSUMED') return 'green' if (normalized === 'DESTROYED') return 'red' return 'blue' } function getVoucherStatusLabel(status: string) { const normalized = String(status || '').toUpperCase() if (normalized === 'CONSUMED') return '已核销' if (normalized === 'DESTROYED') return '已销毁' if (normalized === 'UNUSED') return '未使用' return status || '-' } function formatTimestamp(value: unknown) { const timestamp = Number(value || 0) if (!Number.isFinite(timestamp) || timestamp <= 0) { return '-' } return formatAdminDateTime(new Date(timestamp).toISOString()) }