/* 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 . 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 ( {s.text} ); }; // 如果没有启用客服,不显示 if (!config.enabled) { return null; } const hasQrcode = currentAgent?.qrcode_url && !qrcodeError; const hasContact = hasQrcode || currentAgent?.wecom_url; return (
{/* 移动端遮罩:点击关闭(桌面端通过点击外部关闭,遮罩隐藏不挡操作) */} {isOpen && ( ); }; export default CustomerServiceFloat;