464 lines
16 KiB
React
464 lines
16 KiB
React
/*
|
||
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, Divider, theme } from 'antd';
|
||
import {
|
||
X,
|
||
RefreshCw,
|
||
Headphones,
|
||
ChevronLeft,
|
||
ChevronRight,
|
||
} from 'lucide-react';
|
||
import { API } from '../../helpers';
|
||
import { getServerURL } from '../../helpers/config';
|
||
import { useTranslation } from 'react-i18next';
|
||
import './styles.css';
|
||
|
||
// 在线客服列表停留时的轮询间隔
|
||
const ONLINE_POLL_INTERVAL = 15000;
|
||
|
||
// 页面内“联系客服”入口派发的可取消事件;客服启用时由本组件 preventDefault 并打开面板。
|
||
export const CUSTOMER_SERVICE_OPEN_EVENT = 'customer-service:open';
|
||
|
||
const CustomerServiceFloat = () => {
|
||
const { t } = useTranslation();
|
||
const { token } = theme.useToken();
|
||
const [isOpen, setIsOpen] = useState(false);
|
||
const [isCollapsed, setIsCollapsed] = useState(false);
|
||
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 handleExpand = () => {
|
||
setIsCollapsed(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]);
|
||
|
||
// 页面内入口(如密钥管理“联系客服”)与悬浮按钮共用同一打开逻辑。
|
||
useEffect(() => {
|
||
if (!config.enabled) return undefined;
|
||
const onOpenRequest = (event) => {
|
||
event.preventDefault();
|
||
setIsCollapsed(false);
|
||
setIsOpen(true);
|
||
};
|
||
window.addEventListener(CUSTOMER_SERVICE_OPEN_EVENT, onOpenRequest);
|
||
return () =>
|
||
window.removeEventListener(CUSTOMER_SERVICE_OPEN_EVENT, onOpenRequest);
|
||
}, [config.enabled]);
|
||
|
||
// 获取分配的客服(会让后端 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: 'default' },
|
||
};
|
||
const s = statusMap[status] || statusMap[0];
|
||
return <Tag color={s.color}>{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${isCollapsed ? ' customer-service-container-collapsed' : ''}`}
|
||
ref={containerRef}
|
||
style={{
|
||
'--cs-surface': token.colorBgContainer,
|
||
'--cs-text': token.colorText,
|
||
'--cs-muted': token.colorTextSecondary,
|
||
'--cs-border': token.colorBorderSecondary,
|
||
'--cs-fill': token.colorFillQuaternary,
|
||
'--cs-hover': token.colorFillTertiary,
|
||
'--cs-primary': token.colorPrimary,
|
||
'--cs-primary-hover': token.colorPrimaryHover,
|
||
'--cs-primary-active': token.colorPrimaryActive,
|
||
'--cs-on-primary': token.colorTextLightSolid,
|
||
'--cs-primary-bg': token.colorPrimaryBg,
|
||
'--cs-primary-border': token.colorPrimaryBorder,
|
||
'--cs-primary-text': token.colorPrimaryText,
|
||
'--cs-mask': token.colorBgMask,
|
||
'--cs-shadow': token.boxShadowSecondary,
|
||
}}
|
||
>
|
||
{isOpen && (
|
||
<div className='cs-backdrop' onClick={handleClose} aria-hidden='true' />
|
||
)}
|
||
<div
|
||
className={`cs-float-wrapper${isCollapsed ? ' cs-float-wrapper-collapsed' : ''}`}
|
||
>
|
||
{!isOpen &&
|
||
(isCollapsed ? (
|
||
<div className='cs-float-tab'>
|
||
<Button
|
||
className='cs-float-tab-action'
|
||
type='text'
|
||
title={t('联系客服')}
|
||
aria-label={t('联系客服')}
|
||
onClick={handleExpand}
|
||
icon={<Headphones size={16} strokeWidth={2} />}
|
||
/>
|
||
<Button
|
||
className='cs-float-tab-action'
|
||
type='text'
|
||
title={t('展开')}
|
||
aria-label={t('展开')}
|
||
aria-expanded={false}
|
||
onClick={() => setIsCollapsed(false)}
|
||
icon={<ChevronLeft size={16} strokeWidth={2} />}
|
||
/>
|
||
</div>
|
||
) : (
|
||
<Button
|
||
className='cs-float-toggle'
|
||
type='default'
|
||
title={t('收起')}
|
||
aria-label={t('收起')}
|
||
aria-expanded={true}
|
||
onClick={() => setIsCollapsed(true)}
|
||
>
|
||
<ChevronRight size={16} strokeWidth={2} aria-hidden='true' />
|
||
</Button>
|
||
))}
|
||
<div
|
||
className='cs-float-main'
|
||
inert={isCollapsed ? '' : undefined}
|
||
aria-hidden={isCollapsed}
|
||
>
|
||
<Button
|
||
type='primary'
|
||
shape='circle'
|
||
className='cs-float-button'
|
||
onClick={isOpen ? handleClose : handleExpand}
|
||
ref={triggerRef}
|
||
title={isOpen ? t('关闭客服') : t('联系客服')}
|
||
aria-label={isOpen ? t('关闭客服') : t('联系客服')}
|
||
icon={
|
||
isOpen ? (
|
||
<X size={22} strokeWidth={1.5} />
|
||
) : (
|
||
<Headphones size={22} strokeWidth={1.5} />
|
||
)
|
||
}
|
||
/>
|
||
</div>
|
||
</div>
|
||
<div
|
||
className={`cs-panel ${isOpen ? 'cs-panel-open' : ''}`}
|
||
role='dialog'
|
||
aria-label={t('在线客服')}
|
||
aria-hidden={!isOpen}
|
||
inert={!isOpen ? '' : undefined}
|
||
tabIndex={-1}
|
||
ref={panelRef}
|
||
>
|
||
<div className='cs-panel-header'>
|
||
<span className='cs-header-title'>{t('在线客服')}</span>
|
||
<div className='cs-panel-actions'>
|
||
{currentAgent && !showAgentList && (
|
||
<Button type='text' size='small' onClick={switchAgent}>
|
||
{t('切换')}
|
||
</Button>
|
||
)}
|
||
<Button
|
||
type='text'
|
||
className='cs-close-btn'
|
||
onClick={handleClose}
|
||
aria-label={t('关闭')}
|
||
icon={<X size={16} strokeWidth={1.5} />}
|
||
/>
|
||
</div>
|
||
</div>
|
||
<div className='cs-panel-content'>
|
||
{loading ? (
|
||
<div className='cs-loading'>
|
||
<Spin size='large' />
|
||
<p>{t('正在为您分配客服...')}</p>
|
||
</div>
|
||
) : error ? (
|
||
<div className='cs-error'>
|
||
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={error} />
|
||
<Button
|
||
icon={<RefreshCw size={14} />}
|
||
onClick={fetchAllocatedAgent}
|
||
>
|
||
{t('重新获取')}
|
||
</Button>
|
||
</div>
|
||
) : showAgentList ? (
|
||
<div className='cs-agent-list'>
|
||
<p className='cs-list-title'>{t('请选择客服')}</p>
|
||
{agentList.length === 0 ? (
|
||
<Empty
|
||
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||
description={t('暂无在线客服')}
|
||
/>
|
||
) : (
|
||
agentList.map((agent) => (
|
||
<Button
|
||
key={agent.id}
|
||
className='cs-agent-item'
|
||
onClick={() => selectAgent(agent)}
|
||
>
|
||
<Avatar src={agent.avatar} size={32}>
|
||
{agent.name?.[0]}
|
||
</Avatar>
|
||
<span className='cs-agent-name'>{agent.name}</span>
|
||
{getStatusTag(agent.status)}
|
||
<span className='cs-agent-busy'>
|
||
{agent.current_sessions}/{agent.max_sessions}
|
||
</span>
|
||
</Button>
|
||
))
|
||
)}
|
||
</div>
|
||
) : currentAgent ? (
|
||
<div className='cs-chat-container'>
|
||
<div className='cs-current-agent'>
|
||
<Avatar src={currentAgent.avatar} size={32}>
|
||
{currentAgent.name?.[0]}
|
||
</Avatar>
|
||
<span className='cs-agent-name'>{currentAgent.name}</span>
|
||
{getStatusTag(currentAgent.status)}
|
||
</div>
|
||
{hasContact ? (
|
||
<div className='cs-contact-container'>
|
||
{hasQrcode && (
|
||
<div className='cs-qrcode'>
|
||
<p className='cs-qrcode-label'>{t('扫码联系客服')}</p>
|
||
<div className='cs-qrcode-frame'>
|
||
<img
|
||
src={currentAgent.qrcode_url}
|
||
alt={t('客服二维码')}
|
||
className='cs-qrcode-img'
|
||
onError={() => setQrcodeError(true)}
|
||
/>
|
||
</div>
|
||
</div>
|
||
)}
|
||
{currentAgent.wecom_url && (
|
||
<div className='cs-wecom-link'>
|
||
{hasQrcode && <Divider plain>{t('或')}</Divider>}
|
||
<Button
|
||
type='primary'
|
||
className='cs-wecom-btn'
|
||
onClick={() =>
|
||
window.open(currentAgent.wecom_url, '_blank')
|
||
}
|
||
>
|
||
{t('打开微信客服')}
|
||
</Button>
|
||
</div>
|
||
)}
|
||
</div>
|
||
) : (
|
||
<Empty
|
||
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||
description={
|
||
qrcodeError
|
||
? t('二维码加载失败,请稍后重试')
|
||
: t('客服信息配置不完整')
|
||
}
|
||
/>
|
||
)}
|
||
</div>
|
||
) : null}
|
||
</div>
|
||
</div>
|
||
</div>
|
||
);
|
||
};
|
||
|
||
export default CustomerServiceFloat;
|