Files
monkey-ai-web/src/components/customer-service/index.jsx
T
2026-10-15 16:33:46 +08:00

516 lines
17 KiB
React
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.
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
Avatar,
Tag,
Spin,
Empty,
Button,
Typography,
Tooltip,
} from '@douyinfe/semi-ui';
import {
MessageCircle,
X,
ChevronRight,
Users,
RefreshCw,
Headphones,
QrCode,
Sparkles,
MessageSquareMore,
} from 'lucide-react';
import { API } from '../../helpers';
import { getServerURL } from '../../helpers/config';
import { useTranslation } from 'react-i18next';
import './styles.css';
const { Text } = Typography;
// 本地存储 key
const COLLAPSED_STORAGE_KEY = 'cs-collapsed';
// 在线客服列表停留时的轮询间隔
const ONLINE_POLL_INTERVAL = 15000;
const CustomerServiceFloat = () => {
const { t } = useTranslation();
const [isOpen, setIsOpen] = useState(false);
const [isCollapsed, setIsCollapsed] = useState(() => {
// 从本地存储读取收起状态
return localStorage.getItem(COLLAPSED_STORAGE_KEY) === 'true';
});
const [loading, setLoading] = useState(false);
const [currentAgent, setCurrentAgent] = useState(null);
const [agentList, setAgentList] = useState([]);
const [showAgentList, setShowAgentList] = useState(false);
const [error, setError] = useState(null);
const [qrcodeError, setQrcodeError] = useState(false);
const [config, setConfig] = useState({ enabled: false });
// 当前持有 +1 会话计数的客服 id(仅 /allocate 会自增计数)
const allocatedIdRef = useRef(null);
// isOpen 的同步镜像,用于异步回调里判断面板是否已被关闭
const isOpenRef = useRef(false);
// 容器(点击外部关闭)、面板(打开时聚焦)、触发器(关闭后归还焦点)
const containerRef = useRef(null);
const panelRef = useRef(null);
const triggerRef = useRef(null);
// 结束当前持有的会话计数(精确释放 /allocate 自增的那一次)
const endAllocatedSession = useCallback(({ beacon = false } = {}) => {
const id = allocatedIdRef.current;
if (!id) return;
allocatedIdRef.current = null;
const path = `/api/customer-service/end/${id}`;
// 页面卸载场景用 sendBeacon,保证请求能在 unload 时发出(该接口公开、仅读 URL 参数)
if (beacon && typeof navigator !== 'undefined' && navigator.sendBeacon) {
try {
navigator.sendBeacon(`${getServerURL()}${path}`);
return;
} catch {
/* 退回普通请求 */
}
}
API.post(path).catch(() => {});
}, []);
// 切换收起状态
const toggleCollapse = (e) => {
e.stopPropagation();
const newState = !isCollapsed;
setIsCollapsed(newState);
localStorage.setItem(COLLAPSED_STORAGE_KEY, String(newState));
};
// 展开并打开面板
const handleExpand = () => {
if (isCollapsed) {
setIsCollapsed(false);
localStorage.setItem(COLLAPSED_STORAGE_KEY, 'false');
}
setIsOpen(true);
};
// 获取客服配置
const fetchConfig = useCallback(async () => {
try {
const res = await API.get('/api/customer-service/config');
if (res.data.success) {
setConfig(res.data.data);
}
} catch (err) {
// 静默失败
}
}, []);
useEffect(() => {
fetchConfig();
}, [fetchConfig]);
// 获取分配的客服(会让后端 current_sessions +1)
const fetchAllocatedAgent = useCallback(async () => {
setLoading(true);
setError(null);
try {
const res = await API.get(
'/api/customer-service/allocate?strategy=weighted',
);
if (res.data.success && res.data.data) {
const agent = res.data.data;
// 竞态保护:如果分配返回前面板已关闭,立即释放刚分配的计数,不缓存
if (!isOpenRef.current) {
API.post(`/api/customer-service/end/${agent.id}`).catch(() => {});
return;
}
setCurrentAgent(agent);
allocatedIdRef.current = agent.id;
setQrcodeError(false);
} else {
setError(res.data.message || t('暂无可用客服'));
}
} catch (err) {
setError(t('获取客服失败,请重试'));
} finally {
setLoading(false);
}
}, [t]);
// 获取所有在线客服。silent=true 用于后台轮询,不触发整屏 loading(避免列表闪烁)
const fetchOnlineAgents = useCallback(async ({ silent = false } = {}) => {
if (!silent) setLoading(true);
try {
const res = await API.get('/api/customer-service/online');
if (res.data.success) {
setAgentList(res.data.data || []);
}
} catch (err) {
console.error('获取客服列表失败', err);
} finally {
if (!silent) setLoading(false);
}
}, []);
// 打开面板时自动获取客服(已缓存则不重复分配)
useEffect(() => {
if (isOpen && !currentAgent && !showAgentList) {
fetchAllocatedAgent();
}
}, [isOpen, currentAgent, showAgentList, fetchAllocatedAgent]);
// 在线列表停留期间轮询刷新,避免展示已下线/已满的客服
useEffect(() => {
if (!isOpen || !showAgentList) return;
const timer = setInterval(
() => fetchOnlineAgents({ silent: true }),
ONLINE_POLL_INTERVAL,
);
return () => clearInterval(timer);
}, [isOpen, showAgentList, fetchOnlineAgents]);
// 选择客服(仅展示,不触发 /allocate,因此不占用计数)
const selectAgent = (agent) => {
setCurrentAgent(agent);
setShowAgentList(false);
setQrcodeError(false);
};
// 切换客服:先释放当前会话计数,再展示在线列表
const switchAgent = () => {
endAllocatedSession();
setCurrentAgent(null);
setShowAgentList(true);
fetchOnlineAgents();
};
// 关闭面板:乐观关闭(不等待网络),释放会话计数,但保留已分配客服以便下次秒开
const handleClose = useCallback(() => {
endAllocatedSession();
setIsOpen(false);
setShowAgentList(false);
// 归还焦点到触发按钮(无障碍)
requestAnimationFrame(() => triggerRef.current?.focus?.());
}, [endAllocatedSession]);
// ESC 关闭 + 点击面板外部关闭
useEffect(() => {
if (!isOpen) return;
const onKeyDown = (e) => {
if (e.key === 'Escape') handleClose();
};
const onPointerDown = (e) => {
if (containerRef.current && !containerRef.current.contains(e.target)) {
handleClose();
}
};
document.addEventListener('keydown', onKeyDown);
document.addEventListener('mousedown', onPointerDown);
return () => {
document.removeEventListener('keydown', onKeyDown);
document.removeEventListener('mousedown', onPointerDown);
};
}, [isOpen, handleClose]);
// 打开后将焦点移入面板(无障碍);同时同步 isOpenRef 供异步回调判断
useEffect(() => {
isOpenRef.current = isOpen;
if (isOpen) {
requestAnimationFrame(() => panelRef.current?.focus?.());
}
}, [isOpen]);
// 页面卸载 / 组件卸载时兜底释放会话计数,避免计数泄漏
useEffect(() => {
const onPageHide = () => endAllocatedSession({ beacon: true });
window.addEventListener('pagehide', onPageHide);
return () => {
window.removeEventListener('pagehide', onPageHide);
endAllocatedSession();
};
}, [endAllocatedSession]);
const getStatusTag = (status) => {
const statusMap = {
1: { text: t('在线'), color: 'green' },
2: { text: t('忙碌'), color: 'orange' },
0: { text: t('离线'), color: 'grey' },
};
const s = statusMap[status] || statusMap[0];
return (
<Tag color={s.color} size='small'>
{s.text}
</Tag>
);
};
// 如果没有启用客服,不显示
if (!config.enabled) {
return null;
}
const hasQrcode = currentAgent?.qrcode_url && !qrcodeError;
const hasContact = hasQrcode || currentAgent?.wecom_url;
return (
<div className='customer-service-container' ref={containerRef}>
{/* 移动端遮罩:点击关闭(桌面端通过点击外部关闭,遮罩隐藏不挡操作) */}
{isOpen && (
<div className='cs-backdrop' onClick={handleClose} aria-hidden='true' />
)}
{/* 收起状态 - 边缘小标签 */}
{!isOpen && isCollapsed && (
<Tooltip content={t('联系客服')} position='left'>
<button
className='cs-collapsed-tab'
onClick={handleExpand}
ref={triggerRef}
aria-label={t('联系客服')}
>
<div className='cs-collapsed-icon'>
<MessageSquareMore size={18} strokeWidth={2.5} />
</div>
<div className='cs-collapsed-indicator' />
</button>
</Tooltip>
)}
{/* 展开状态的浮动按钮 - 精美客服图标 */}
{!isOpen && !isCollapsed && (
<div className='cs-float-wrapper'>
<button
className='cs-float-button cs-has-pulse'
onClick={handleExpand}
ref={triggerRef}
aria-label={t('联系客服')}
>
{/* 装饰性光环 */}
<div className='cs-glow-ring' />
<div className='cs-glow-ring cs-glow-ring-2' />
{/* 主图标 */}
<div className='cs-icon-wrapper'>
<Headphones size={26} strokeWidth={2} />
</div>
{/* 在线状态指示器 */}
<div className='cs-online-indicator'>
<div className='cs-online-dot' />
</div>
{/* 悬浮文字提示 */}
<div className='cs-float-label'>
<span>{t('在线客服')}</span>
</div>
</button>
{/* 收起按钮 */}
<button
className='cs-collapse-btn'
onClick={toggleCollapse}
title={t('收起')}
aria-label={t('收起')}
>
<ChevronRight size={14} />
</button>
</div>
)}
{/* 展开的客服面板 */}
<div
className={`cs-panel ${isOpen ? 'cs-panel-open' : ''}`}
role='dialog'
aria-label={t('在线客服')}
aria-hidden={!isOpen}
/* 关闭时让面板内子元素(关闭按钮等)从 Tab 序列与可达性树中移除,
避免键盘焦点跑进屏幕外的隐藏面板(也消除 aria-hidden 含焦点元素的告警) */
inert={!isOpen ? '' : undefined}
tabIndex={-1}
ref={panelRef}
>
{/* 头部 - 渐变背景 */}
<div className='cs-panel-header'>
<div className='cs-header-content'>
<div className='cs-header-icon'>
<Headphones size={20} />
</div>
<div className='cs-header-text'>
<span className='cs-header-title'>{t('在线客服')}</span>
<span className='cs-header-subtitle'>{t('随时为您服务')}</span>
</div>
</div>
<div className='cs-panel-actions'>
{currentAgent && (
<Button
size='small'
theme='borderless'
icon={<Users size={14} />}
onClick={switchAgent}
style={{
color: 'white',
background: 'rgba(255,255,255,0.2)',
borderRadius: '10px',
}}
>
{t('切换')}
</Button>
)}
<button
className='cs-close-btn'
onClick={handleClose}
aria-label={t('关闭')}
>
<X size={18} />
</button>
</div>
</div>
{/* 内容区 */}
<div className='cs-panel-content'>
{loading ? (
<div className='cs-loading'>
<Spin size='large' />
<p className='cs-loading-text'>{t('正在为您分配客服...')}</p>
</div>
) : error ? (
<div className='cs-error'>
<Empty title={t('暂无可用客服')} description={error} />
<Button
icon={<RefreshCw size={14} />}
onClick={fetchAllocatedAgent}
style={{ marginTop: 16 }}
>
{t('重新获取')}
</Button>
</div>
) : showAgentList ? (
/* 客服选择列表 */
<div className='cs-agent-list'>
<p className='cs-list-title'>{t('请选择客服')}</p>
{agentList.length === 0 ? (
<Empty description={t('暂无在线客服')} />
) : (
agentList.map((agent) => (
<div
key={agent.id}
className='cs-agent-item'
onClick={() => selectAgent(agent)}
>
<Avatar
src={agent.avatar}
size='small'
style={{ marginRight: 12, backgroundColor: '#87d068' }}
>
{agent.name?.[0]}
</Avatar>
<div className='cs-agent-info'>
<span className='cs-agent-name'>{agent.name}</span>
{getStatusTag(agent.status)}
</div>
<span className='cs-agent-busy'>
{agent.current_sessions}/{agent.max_sessions}
</span>
</div>
))
)}
</div>
) : currentAgent ? (
/* 客服聊天界面 */
<div className='cs-chat-container'>
{/* 当前客服信息 */}
<div className='cs-current-agent'>
<Avatar
src={currentAgent.avatar}
size='small'
style={{ backgroundColor: '#87d068' }}
>
{currentAgent.name?.[0]}
</Avatar>
<span style={{ marginLeft: 8 }}>{currentAgent.name}</span>
{getStatusTag(currentAgent.status)}
</div>
{/* 客服内容 */}
{hasContact ? (
<div className='cs-contact-container'>
{/* 二维码区域 */}
{hasQrcode && (
<div className='cs-qrcode'>
<div className='cs-qrcode-label'>
<QrCode size={16} />
<span>{t('扫码联系客服')}</span>
</div>
<img
src={currentAgent.qrcode_url}
alt={t('客服二维码')}
className='cs-qrcode-img'
onError={() => setQrcodeError(true)}
/>
</div>
)}
{/* 跳转按钮区域 */}
{currentAgent.wecom_url && (
<div className='cs-wecom-link'>
{hasQrcode && (
<div className='cs-divider'>
<span>{t('或')}</span>
</div>
)}
<button
className='cs-wecom-btn'
onClick={() =>
window.open(currentAgent.wecom_url, '_blank')
}
>
<MessageCircle size={18} />
{t('打开微信客服')}
<Sparkles size={14} />
</button>
<Text
type='tertiary'
size='small'
style={{ marginTop: 12, opacity: 0.7 }}
>
{t('点击后将跳转至微信')}
</Text>
</div>
)}
</div>
) : (
<div className='cs-no-contact'>
<Empty
description={
qrcodeError
? t('二维码加载失败,请稍后重试')
: t('客服信息配置不完整')
}
/>
</div>
)}
</div>
) : null}
</div>
</div>
</div>
);
};
export default CustomerServiceFloat;