558 lines
19 KiB
TypeScript
558 lines
19 KiB
TypeScript
import { useEffect, useState, useCallback, useRef } from 'react';
|
|
import {
|
|
Card, Table, Button, Select, Input, Tag, Row, Col, Statistic,
|
|
Space, Tabs, Typography, Badge, theme, Tooltip,
|
|
} from 'antd';
|
|
import { message } from '../utils/antdMessage';
|
|
import {
|
|
UserOutlined, CheckCircleOutlined, TeamOutlined,
|
|
SwapOutlined, ClearOutlined, UsergroupAddOutlined, ReloadOutlined,
|
|
} from '@ant-design/icons';
|
|
import {
|
|
accountApi,
|
|
type AccountItem,
|
|
type SupportUserItem,
|
|
type AssignmentsSummary,
|
|
} from '../api/modules';
|
|
import { getErrorMessage } from '../utils/error';
|
|
|
|
const { Text } = Typography;
|
|
|
|
const STORAGE_KEY_SELECTED_USER = 'assignments_selected_user_id';
|
|
|
|
export default function AssignmentsPage() {
|
|
const { token } = theme.useToken();
|
|
const [summary, setSummary] = useState<AssignmentsSummary | null>(null);
|
|
const [supportUsers, setSupportUsers] = useState<SupportUserItem[]>([]);
|
|
const [selectedUser, setSelectedUser] = useState<SupportUserItem | null>(null);
|
|
const [allTags, setAllTags] = useState<string[]>([]);
|
|
|
|
// 表格分页与筛选状态
|
|
const [pagedAccounts, setPagedAccounts] = useState<AccountItem[]>([]);
|
|
const [totalCount, setTotalCount] = useState(0);
|
|
const [tableLoading, setTableLoading] = useState(false);
|
|
const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
|
|
const [searchText, setSearchText] = useState('');
|
|
const [filterTag, setFilterTag] = useState<string | undefined>(undefined);
|
|
const [activeTab, setActiveTab] = useState<'unassigned' | 'assigned'>('unassigned');
|
|
const [assigning, setAssigning] = useState(false);
|
|
const [refreshing, setRefreshing] = useState(false);
|
|
const summaryRequestRef = useRef(0);
|
|
const pagedRequestRef = useRef(0);
|
|
const [pageSize, setPageSize] = useState(() => {
|
|
const v = localStorage.getItem('assignment_page_size');
|
|
return v ? Number(v) || 15 : 15;
|
|
});
|
|
const [currentPage, setCurrentPage] = useState(1);
|
|
|
|
// 加载分配概览统计
|
|
const loadSummary = useCallback(async (silent = false) => {
|
|
const requestId = ++summaryRequestRef.current;
|
|
try {
|
|
const data = await accountApi.assignmentsSummary();
|
|
if (requestId !== summaryRequestRef.current) return [];
|
|
setSummary(data);
|
|
setSupportUsers(data.support_users);
|
|
return data.support_users;
|
|
} catch (e: unknown) {
|
|
if (requestId === summaryRequestRef.current && !silent) {
|
|
message.error(getErrorMessage(e));
|
|
}
|
|
return [];
|
|
}
|
|
}, []);
|
|
|
|
// 加载标签列表
|
|
const loadTags = useCallback(async () => {
|
|
try {
|
|
const tags = await accountApi.listTags();
|
|
setAllTags(tags);
|
|
} catch {
|
|
// 忽略标签加载异常
|
|
}
|
|
}, []);
|
|
|
|
// 分页按需加载账号(服务端过滤与分页)
|
|
const loadPagedAccounts = useCallback(async (silent = false) => {
|
|
const requestId = ++pagedRequestRef.current;
|
|
if (!silent) setTableLoading(true);
|
|
try {
|
|
const params: Parameters<typeof accountApi.listPaged>[0] = {
|
|
page: currentPage,
|
|
page_size: pageSize,
|
|
// 分配池只收当前 Cookie 已通过新鲜 CK 检测的账号。
|
|
assignable_only: true,
|
|
include_sensitive: false,
|
|
search: searchText.trim() || undefined,
|
|
tag: filterTag || undefined,
|
|
};
|
|
|
|
if (activeTab === 'unassigned') {
|
|
params.assign_status = 'unassigned';
|
|
} else if (selectedUser) {
|
|
params.assigned_user_id = selectedUser.id;
|
|
}
|
|
|
|
const data = await accountApi.listPaged(params);
|
|
if (requestId !== pagedRequestRef.current) return;
|
|
setPagedAccounts(data.items);
|
|
setTotalCount(data.total);
|
|
} catch (e: unknown) {
|
|
if (requestId === pagedRequestRef.current && !silent) {
|
|
message.error(getErrorMessage(e));
|
|
}
|
|
} finally {
|
|
if (requestId === pagedRequestRef.current) {
|
|
setTableLoading(false);
|
|
}
|
|
}
|
|
}, [activeTab, selectedUser, currentPage, pageSize, searchText, filterTag]);
|
|
|
|
// 初始化加载
|
|
useEffect(() => {
|
|
const init = async () => {
|
|
loadTags();
|
|
const users = await loadSummary();
|
|
if (users.length > 0) {
|
|
const savedId = localStorage.getItem(STORAGE_KEY_SELECTED_USER);
|
|
const savedUser = savedId ? users.find((u) => u.id === Number(savedId)) : null;
|
|
setSelectedUser(savedUser || users[0]);
|
|
}
|
|
};
|
|
init();
|
|
}, [loadSummary, loadTags]);
|
|
|
|
// 当筛选或选中客服变化时触发分页请求
|
|
useEffect(() => {
|
|
loadPagedAccounts();
|
|
}, [loadPagedAccounts]);
|
|
|
|
useEffect(() => {
|
|
const refreshVisibleData = () => {
|
|
if (document.visibilityState !== 'visible') return;
|
|
void loadSummary(true);
|
|
void loadPagedAccounts(true);
|
|
};
|
|
const timer = window.setInterval(refreshVisibleData, 15000);
|
|
const handleVisibility = () => {
|
|
if (document.visibilityState === 'visible') refreshVisibleData();
|
|
};
|
|
document.addEventListener('visibilitychange', handleVisibility);
|
|
window.addEventListener('focus', refreshVisibleData);
|
|
return () => {
|
|
window.clearInterval(timer);
|
|
document.removeEventListener('visibilitychange', handleVisibility);
|
|
window.removeEventListener('focus', refreshVisibleData);
|
|
};
|
|
}, [loadPagedAccounts, loadSummary]);
|
|
|
|
const handleRefresh = async () => {
|
|
setRefreshing(true);
|
|
try {
|
|
await Promise.all([loadSummary(), loadPagedAccounts()]);
|
|
} finally {
|
|
setRefreshing(false);
|
|
}
|
|
};
|
|
|
|
// 切换客服
|
|
const handleSelectUser = (user: SupportUserItem) => {
|
|
setSelectedUser(user);
|
|
setSelectedRowKeys([]);
|
|
setCurrentPage(1);
|
|
localStorage.setItem(STORAGE_KEY_SELECTED_USER, String(user.id));
|
|
};
|
|
|
|
// 批量分配选中账号
|
|
const handleBatchAssign = async () => {
|
|
if (selectedRowKeys.length === 0) {
|
|
message.warning('请先选择账号');
|
|
return;
|
|
}
|
|
if (!selectedUser) {
|
|
message.warning('请先选择客服');
|
|
return;
|
|
}
|
|
setAssigning(true);
|
|
try {
|
|
await accountApi.batchAssign(selectedRowKeys, selectedUser.id);
|
|
message.success(`已将 ${selectedRowKeys.length} 个账号分配给 ${selectedUser.username}`);
|
|
setSelectedRowKeys([]);
|
|
await loadSummary();
|
|
await loadPagedAccounts();
|
|
} catch (e: unknown) {
|
|
message.error(getErrorMessage(e));
|
|
} finally {
|
|
setAssigning(false);
|
|
}
|
|
};
|
|
|
|
// 批量取消分配
|
|
const handleBatchUnassign = async () => {
|
|
if (selectedRowKeys.length === 0) {
|
|
message.warning('请先选择账号');
|
|
return;
|
|
}
|
|
setAssigning(true);
|
|
try {
|
|
await accountApi.batchAssign(selectedRowKeys, null);
|
|
message.success(`已取消 ${selectedRowKeys.length} 个账号的分配`);
|
|
setSelectedRowKeys([]);
|
|
await loadSummary();
|
|
await loadPagedAccounts();
|
|
} catch (e: unknown) {
|
|
message.error(getErrorMessage(e));
|
|
} finally {
|
|
setAssigning(false);
|
|
}
|
|
};
|
|
|
|
// 一键将当前未分配(含搜索/标签筛选)全部分配给选中客服
|
|
const handleAssignAllUnassigned = async () => {
|
|
if (!selectedUser) {
|
|
message.warning('请先选择客服');
|
|
return;
|
|
}
|
|
if (totalCount === 0) {
|
|
message.info('当前筛选下没有未分配的账号');
|
|
return;
|
|
}
|
|
setAssigning(true);
|
|
try {
|
|
const res = await accountApi.batchAssignSelection({
|
|
all_matching: true,
|
|
assign_status: 'unassigned',
|
|
assignable_only: true,
|
|
tag: filterTag || undefined,
|
|
search: searchText.trim() || undefined,
|
|
assigned_to: selectedUser.id,
|
|
});
|
|
message.success(res.message || `已全部分配给 ${selectedUser.username}`);
|
|
setSelectedRowKeys([]);
|
|
await loadSummary();
|
|
await loadPagedAccounts();
|
|
} catch (e: unknown) {
|
|
message.error(getErrorMessage(e));
|
|
} finally {
|
|
setAssigning(false);
|
|
}
|
|
};
|
|
|
|
// 统计数据
|
|
const assignedCount = summary?.assigned_count ?? 0;
|
|
const unassignedCount = summary?.unassigned_count ?? 0;
|
|
const totalAccountCount = summary?.total_count ?? (assignedCount + unassignedCount);
|
|
|
|
// 获取当前选中客服已分配总数
|
|
const currentSelectedUserAssignedCount =
|
|
(selectedUser ? supportUsers.find((u) => u.id === selectedUser.id)?.assigned_count : 0) ??
|
|
selectedUser?.assigned_count ??
|
|
0;
|
|
|
|
const columns = [
|
|
{ title: 'ID', dataIndex: 'id', width: 70 },
|
|
{
|
|
title: '用户名',
|
|
dataIndex: 'username',
|
|
render: (text: string) => <Text strong>{text}</Text>,
|
|
},
|
|
{
|
|
title: '标签',
|
|
dataIndex: 'tag',
|
|
width: 120,
|
|
render: (tag: string) => (tag ? <Tag color="blue">{tag}</Tag> : <Text type="secondary">-</Text>),
|
|
},
|
|
{
|
|
title: '积分 / 鱼翅',
|
|
dataIndex: 'points',
|
|
width: 140,
|
|
render: (_: unknown, record: AccountItem) => (
|
|
<Space size={4}>
|
|
<span>积分 {record.points ?? '-'}</span>
|
|
<Text type="secondary" style={{ fontSize: 12 }}>
|
|
/ 鱼翅 {record.gold_balance ?? '-'}
|
|
</Text>
|
|
</Space>
|
|
),
|
|
},
|
|
{
|
|
title: '状态',
|
|
dataIndex: 'status',
|
|
width: 110,
|
|
render: (status: string, record: AccountItem) => (
|
|
<Tag color={status === 'active' ? 'green' : 'default'}>
|
|
{record.status_label || status || '-'}
|
|
</Tag>
|
|
),
|
|
},
|
|
];
|
|
|
|
return (
|
|
<div style={{ height: '100%', display: 'flex', flexDirection: 'column', gap: 12 }}>
|
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
|
<h2 style={{ margin: 0 }}>分配管理</h2>
|
|
<Button icon={<ReloadOutlined />} loading={refreshing} onClick={handleRefresh}>
|
|
刷新
|
|
</Button>
|
|
</div>
|
|
|
|
{/* 统计卡片 */}
|
|
<Row gutter={12} style={{ flexShrink: 0 }}>
|
|
<Col span={6}>
|
|
<Card size="small">
|
|
<Statistic title="总账号 (CK 有效)" value={totalAccountCount} prefix={<TeamOutlined />} />
|
|
</Card>
|
|
</Col>
|
|
<Col span={6}>
|
|
<Card size="small">
|
|
<Statistic
|
|
title="已分配"
|
|
value={assignedCount}
|
|
styles={{ content: { color: token.colorSuccess } }}
|
|
prefix={<CheckCircleOutlined />}
|
|
/>
|
|
</Card>
|
|
</Col>
|
|
<Col span={6}>
|
|
<Card size="small">
|
|
<Tooltip title="仅统计当前 Cookie 已通过有效 CK 检测、且未停用/归档的账号。登录成功后会自动复检 CK;本页每 15 秒刷新一次。">
|
|
<Statistic
|
|
title="未分配"
|
|
value={unassignedCount}
|
|
styles={{ content: { color: token.colorError } }}
|
|
prefix={<SwapOutlined />}
|
|
/>
|
|
</Tooltip>
|
|
</Card>
|
|
</Col>
|
|
<Col span={6}>
|
|
<Card size="small">
|
|
<Statistic
|
|
title="客服人数"
|
|
value={supportUsers.length}
|
|
prefix={<UsergroupAddOutlined />}
|
|
/>
|
|
</Card>
|
|
</Col>
|
|
</Row>
|
|
|
|
{/* 主体区域 */}
|
|
<Row gutter={12} style={{ flex: 1, minHeight: 0 }}>
|
|
{/* 左栏:客服列表 */}
|
|
<Col span={8} style={{ height: '100%', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
|
|
<Card
|
|
title="客服列表"
|
|
size="small"
|
|
style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}
|
|
styles={{ body: { flex: 1, overflow: 'auto', padding: '8px' } }}
|
|
>
|
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
|
|
{supportUsers.map((user) => {
|
|
const isSelected = selectedUser?.id === user.id;
|
|
return (
|
|
<div
|
|
key={user.id}
|
|
onClick={() => handleSelectUser(user)}
|
|
style={{
|
|
display: 'flex',
|
|
alignItems: 'center',
|
|
justifyContent: 'space-between',
|
|
padding: '10px 14px',
|
|
borderRadius: 6,
|
|
cursor: 'pointer',
|
|
border: `1px solid ${isSelected ? token.colorPrimary : token.colorBorderSecondary}`,
|
|
background: isSelected ? token.colorPrimaryBg : token.colorBgContainer,
|
|
transition: 'all 0.2s',
|
|
}}
|
|
onMouseEnter={(e) => {
|
|
if (!isSelected) (e.currentTarget as HTMLElement).style.borderColor = token.colorPrimary;
|
|
}}
|
|
onMouseLeave={(e) => {
|
|
if (!isSelected) (e.currentTarget as HTMLElement).style.borderColor = token.colorBorderSecondary;
|
|
}}
|
|
>
|
|
<Space>
|
|
<UserOutlined style={{ color: token.colorPrimary }} />
|
|
<Text strong>{user.username}</Text>
|
|
</Space>
|
|
<Tooltip title={`已分配 ${user.assigned_count} 个账号`}>
|
|
<Badge
|
|
count={user.assigned_count}
|
|
overflowCount={999999}
|
|
showZero
|
|
style={{ backgroundColor: token.colorPrimary }}
|
|
/>
|
|
</Tooltip>
|
|
</div>
|
|
);
|
|
})}
|
|
{supportUsers.length === 0 && (
|
|
<Text type="secondary" style={{ textAlign: 'center', padding: 20, display: 'block' }}>
|
|
暂无客服用户
|
|
</Text>
|
|
)}
|
|
</div>
|
|
</Card>
|
|
</Col>
|
|
|
|
{/* 右栏:账号表格 */}
|
|
<Col span={16} style={{ height: '100%', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
|
|
<Card
|
|
size="small"
|
|
title={
|
|
<Space>
|
|
{selectedUser ? (
|
|
<>
|
|
<span>已选中客服:</span>
|
|
<Tag color="blue" style={{ fontSize: 14, padding: '2px 10px' }}>
|
|
{selectedUser.username}(已分配 {currentSelectedUserAssignedCount} 个)
|
|
</Tag>
|
|
</>
|
|
) : (
|
|
<Text type="secondary">请选择左侧客服进行操作</Text>
|
|
)}
|
|
</Space>
|
|
}
|
|
style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}
|
|
styles={{ body: { flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0, padding: 0 } }}
|
|
>
|
|
{/* 筛选栏 */}
|
|
<div
|
|
style={{
|
|
padding: '8px 16px',
|
|
borderBottom: `1px solid ${token.colorBorderSecondary}`,
|
|
display: 'flex',
|
|
gap: 8,
|
|
alignItems: 'center',
|
|
flexShrink: 0,
|
|
}}
|
|
>
|
|
<Input.Search
|
|
placeholder="搜索用户名"
|
|
allowClear
|
|
value={searchText}
|
|
onChange={(e) => {
|
|
setSearchText(e.target.value);
|
|
setCurrentPage(1);
|
|
}}
|
|
style={{ width: 200 }}
|
|
size="small"
|
|
/>
|
|
<Select
|
|
allowClear
|
|
showSearch
|
|
placeholder="按标签筛选"
|
|
value={filterTag}
|
|
onChange={(v) => {
|
|
setFilterTag(v || undefined);
|
|
setCurrentPage(1);
|
|
}}
|
|
filterOption={(input, option) =>
|
|
String(option?.label || '').toLowerCase().includes(input.trim().toLowerCase())
|
|
}
|
|
style={{ width: 150 }}
|
|
size="small"
|
|
options={allTags.map((t) => ({ value: t, label: t }))}
|
|
/>
|
|
</div>
|
|
|
|
{/* Tab 切换 */}
|
|
<Tabs
|
|
size="small"
|
|
activeKey={activeTab}
|
|
onChange={(key) => {
|
|
setActiveTab(key as 'unassigned' | 'assigned');
|
|
setSelectedRowKeys([]);
|
|
setCurrentPage(1);
|
|
}}
|
|
style={{ padding: '0 16px', flexShrink: 0, marginBottom: 0 }}
|
|
items={[
|
|
{
|
|
key: 'unassigned',
|
|
label: `未分配 (${unassignedCount})`,
|
|
},
|
|
{
|
|
key: 'assigned',
|
|
label: selectedUser
|
|
? `已分配给 ${selectedUser.username} (${currentSelectedUserAssignedCount})`
|
|
: '已分配账号',
|
|
disabled: !selectedUser,
|
|
},
|
|
]}
|
|
/>
|
|
|
|
{/* 操作按钮 */}
|
|
<div style={{ padding: '0 16px 8px', flexShrink: 0 }}>
|
|
<Space>
|
|
{activeTab === 'unassigned' && selectedUser && (
|
|
<>
|
|
<Button
|
|
type="primary"
|
|
size="small"
|
|
icon={<SwapOutlined />}
|
|
loading={assigning}
|
|
disabled={selectedRowKeys.length === 0}
|
|
onClick={handleBatchAssign}
|
|
>
|
|
分配选中 ({selectedRowKeys.length}) 给 {selectedUser.username}
|
|
</Button>
|
|
<Button
|
|
size="small"
|
|
loading={assigning}
|
|
onClick={handleAssignAllUnassigned}
|
|
>
|
|
全部分配给 {selectedUser.username}
|
|
</Button>
|
|
</>
|
|
)}
|
|
{activeTab === 'assigned' && selectedUser && (
|
|
<Button
|
|
danger
|
|
size="small"
|
|
icon={<ClearOutlined />}
|
|
loading={assigning}
|
|
disabled={selectedRowKeys.length === 0}
|
|
onClick={handleBatchUnassign}
|
|
>
|
|
取消分配选中 ({selectedRowKeys.length})
|
|
</Button>
|
|
)}
|
|
</Space>
|
|
</div>
|
|
|
|
{/* 表格 */}
|
|
<Table
|
|
columns={columns}
|
|
dataSource={pagedAccounts}
|
|
rowKey="id"
|
|
size="small"
|
|
loading={tableLoading}
|
|
pagination={{
|
|
current: currentPage,
|
|
pageSize,
|
|
total: totalCount,
|
|
size: 'small',
|
|
showSizeChanger: true,
|
|
showTotal: (t) => `共 ${t} 条`,
|
|
onChange: (page, size) => {
|
|
setCurrentPage(page);
|
|
if (size !== pageSize) {
|
|
setPageSize(size);
|
|
localStorage.setItem('assignment_page_size', String(size));
|
|
setCurrentPage(1);
|
|
}
|
|
},
|
|
}}
|
|
rowSelection={{
|
|
selectedRowKeys,
|
|
onChange: (keys) => setSelectedRowKeys(keys as number[]),
|
|
}}
|
|
scroll={{ y: 'calc(100vh - 460px)' }}
|
|
/>
|
|
</Card>
|
|
</Col>
|
|
</Row>
|
|
</div>
|
|
);
|
|
}
|