客服服务器完整源码,包含: - Express HTTP服务 (port 9501) - WebSocket服务 (port 9502) - SaaS多租户认证 - 坐席管理、消息管理、连接管理 - SQLite数据库(5张核心表) - 管理后台 (/admin) - 坐席工作台 (/agent, /agent-mobile) - 商城REST API (/plugin.yunqian-api) - 消息推送API (/message/push) 技术栈:Node.js 18 + Express 4 + ws 8 + better-sqlite3 + EJS + PM2
1129 lines
41 KiB
Plaintext
1129 lines
41 KiB
Plaintext
<!DOCTYPE html>
|
|
<html lang="zh-CN">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>客服工作台 - <%= agentInfo.tenant_name || '客服系统' %></title>
|
|
<style>
|
|
*{margin:0;padding:0;box-sizing:border-box}
|
|
body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Microsoft YaHei",sans-serif;background:#f0f2f5;height:100vh;overflow:hidden;color:#333}
|
|
.app{display:flex;height:100vh}
|
|
|
|
/* ===== 左侧客户列表 ===== */
|
|
.sidebar{width:300px;background:#fff;border-right:1px solid #e8e8e8;display:flex;flex-direction:column}
|
|
.sidebar-header{padding:16px 20px;border-bottom:1px solid #f0f0f0;background:linear-gradient(135deg,#1a73e8 0%,#0d47a1 100%);color:#fff;flex-shrink:0}
|
|
.sidebar-header h2{font-size:16px;font-weight:600}
|
|
.sidebar-header .agent-bar{display:flex;align-items:center;justify-content:space-between;margin-top:10px}
|
|
.status-selector{display:flex;align-items:center;gap:6px;font-size:12px}
|
|
.status-selector select{background:rgba(255,255,255,0.2);color:#fff;border:1px solid rgba(255,255,255,0.3);border-radius:4px;padding:2px 6px;font-size:11px;cursor:pointer;outline:none}
|
|
.status-selector select option{background:#1a73e8;color:#fff}
|
|
.status-dot{width:8px;height:8px;border-radius:50%;display:inline-block}
|
|
.status-dot.online{background:#52c41a}
|
|
.status-dot.busy{background:#faad14}
|
|
.status-dot.offline{background:#bfbfbf}
|
|
.conn-info{font-size:11px;opacity:.8;display:flex;align-items:center;gap:6px;margin-top:6px}
|
|
.sidebar-search{padding:12px 16px;border-bottom:1px solid #f0f0f0;flex-shrink:0}
|
|
.sidebar-search input{width:100%;padding:8px 12px;border:1px solid #e8e8e8;border-radius:6px;font-size:13px;outline:none;transition:border-color .2s}
|
|
.sidebar-search input:focus{border-color:#1a73e8}
|
|
.customer-list{flex:1;overflow-y:auto}
|
|
.customer-item{padding:14px 20px;border-bottom:1px solid #f5f5f5;cursor:pointer;transition:background .2s;display:flex;align-items:center;gap:12px}
|
|
.customer-item:hover{background:#f5f7fa}
|
|
.customer-item.active{background:#e6f4ff;border-left:3px solid #1a73e8}
|
|
.customer-avatar{width:40px;height:40px;border-radius:50%;background:linear-gradient(135deg,#1a73e8,#0d47a1);color:#fff;display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:600;flex-shrink:0;position:relative}
|
|
.customer-avatar.offline{background:#ccc}
|
|
.customer-avatar .online-dot{position:absolute;bottom:0;right:0;width:10px;height:10px;border-radius:50%;background:#52c41a;border:2px solid #fff}
|
|
.customer-avatar .online-dot.offline{background:#ccc}
|
|
.customer-info{flex:1;min-width:0}
|
|
.customer-name{font-size:14px;font-weight:500;color:#333;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
.customer-preview{font-size:12px;color:#999;margin-top:3px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
.customer-meta{text-align:right;flex-shrink:0}
|
|
.customer-time{font-size:11px;color:#bbb}
|
|
.customer-badge{background:#ff4d4f;color:#fff;font-size:11px;padding:2px 6px;border-radius:10px;min-width:18px;text-align:center;display:inline-block;margin-top:4px}
|
|
|
|
/* ===== 中间聊天区域 ===== */
|
|
.chat-area{flex:1;display:flex;flex-direction:column;background:#fff;min-width:0}
|
|
.chat-header{padding:14px 20px;border-bottom:1px solid #f0f0f0;display:flex;align-items:center;justify-content:space-between;background:#fafafa;flex-shrink:0}
|
|
.chat-header-left{display:flex;align-items:center;gap:12px}
|
|
.chat-header .customer-name{font-size:15px;font-weight:600}
|
|
.chat-header .customer-status{font-size:12px;color:#52c41a;display:flex;align-items:center;gap:4px}
|
|
.chat-header .customer-status.offline{color:#999}
|
|
.chat-header .conn-status{font-size:12px;padding:4px 10px;border-radius:4px;background:#f6ffed;color:#52c41a}
|
|
.chat-header .conn-status.disconnected{background:#fff0f0;color:#ff4d4f}
|
|
.chat-header .conn-status.connecting{background:#fffbe6;color:#faad14}
|
|
.chat-header-right{display:flex;align-items:center;gap:8px}
|
|
.btn-icon{width:32px;height:32px;border:none;background:none;cursor:pointer;border-radius:6px;display:flex;align-items:center;justify-content:center;font-size:16px;color:#666;transition:all .2s}
|
|
.btn-icon:hover{background:#f0f0f0;color:#1a73e8}
|
|
|
|
.chat-messages{flex:1;overflow-y:auto;padding:20px;background:#f5f5f5}
|
|
.load-more{text-align:center;padding:10px;cursor:pointer;color:#1a73e8;font-size:13px}
|
|
.load-more:hover{text-decoration:underline}
|
|
.message-group{margin-bottom:20px}
|
|
.message-date{text-align:center;font-size:12px;color:#bbb;margin-bottom:12px}
|
|
.message{display:flex;gap:10px;margin-bottom:12px;max-width:70%}
|
|
.message.self{margin-left:auto;flex-direction:row-reverse}
|
|
.message-avatar{width:36px;height:36px;border-radius:50%;background:linear-gradient(135deg,#1a73e8,#0d47a1);color:#fff;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:600;flex-shrink:0}
|
|
.message.self .message-avatar{background:linear-gradient(135deg,#52c41a,#389e0d)}
|
|
.message-content{background:#fff;padding:10px 14px;border-radius:12px;font-size:14px;line-height:1.5;box-shadow:0 1px 3px rgba(0,0,0,0.05);word-break:break-word}
|
|
.message.self .message-content{background:#1a73e8;color:#fff;border-bottom-right-radius:4px}
|
|
.message:not(.self) .message-content{border-bottom-left-radius:4px}
|
|
.message-image{max-width:200px;border-radius:8px;cursor:pointer;display:block}
|
|
.message-time-stamp{font-size:11px;color:#bbb;margin-top:4px}
|
|
.message.self .message-time-stamp{text-align:right}
|
|
.message-read{color:#1a73e8}
|
|
.message-unread{color:#faad14}
|
|
|
|
/* ===== 输入区域 ===== */
|
|
.chat-input-area{border-top:1px solid #f0f0f0;padding:12px 20px;background:#fff;flex-shrink:0}
|
|
.input-toolbar{display:flex;gap:8px;margin-bottom:8px;flex-wrap:wrap}
|
|
.toolbar-btn{padding:6px 10px;border:1px solid #e8e8e8;border-radius:4px;background:#fafafa;cursor:pointer;font-size:12px;color:#666;transition:all .2s;display:flex;align-items:center;gap:4px}
|
|
.toolbar-btn:hover{border-color:#1a73e8;color:#1a73e8}
|
|
.toolbar-btn.active{background:#e6f4ff;border-color:#1a73e8;color:#1a73e8}
|
|
.input-wrapper{display:flex;gap:10px;align-items:flex-end}
|
|
.input-wrapper textarea{flex:1;padding:10px 14px;border:1px solid #e8e8e8;border-radius:8px;font-size:14px;resize:none;outline:none;min-height:44px;max-height:120px;font-family:inherit;transition:border-color .2s}
|
|
.input-wrapper textarea:focus{border-color:#1a73e8;box-shadow:0 0 0 2px rgba(26,115,232,0.1)}
|
|
.btn-send{padding:10px 20px;background:#1a73e8;color:#fff;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;flex-shrink:0;transition:opacity .2s}
|
|
.btn-send:hover{opacity:.9}
|
|
.btn-send:disabled{background:#ccc;cursor:not-allowed}
|
|
|
|
/* ===== 图片上传 ===== */
|
|
.image-upload{display:none}
|
|
.image-preview-container{position:fixed;bottom:80px;left:340px;right:280px;background:#fff;border:1px solid #e8e8e8;border-radius:8px;padding:12px;box-shadow:0 2px 8px rgba(0,0,0,0.1);z-index:200;display:none}
|
|
.image-preview-container.show{display:block}
|
|
.image-preview-container img{max-height:120px;border-radius:4px}
|
|
.image-preview-container .btn-cancel{margin-left:10px;cursor:pointer;color:#999;font-size:13px}
|
|
|
|
/* ===== 快捷回复面板 ===== */
|
|
.quick-reply-panel{position:absolute;bottom:60px;left:20px;background:#fff;border:1px solid #e8e8e8;border-radius:8px;padding:12px;box-shadow:0 2px 8px rgba(0,0,0,0.1);z-index:200;display:none;width:300px;max-height:250px;overflow-y:auto}
|
|
.quick-reply-panel.show{display:block}
|
|
.quick-reply-panel h4{font-size:13px;color:#999;margin-bottom:8px}
|
|
.quick-reply-item{padding:8px 12px;border-radius:6px;margin-bottom:6px;font-size:13px;cursor:pointer;transition:background .2s}
|
|
.quick-reply-item:hover{background:#e6f4ff;color:#1a73e8}
|
|
.quick-reply-category{font-size:12px;color:#999;font-weight:600;margin-top:8px;margin-bottom:4px;padding-bottom:4px;border-bottom:1px solid #f0f0f0}
|
|
|
|
/* ===== 右侧信息面板 ===== */
|
|
.info-panel{width:280px;background:#fff;border-left:1px solid #e8e8e8;padding:20px;overflow-y:auto;flex-shrink:0}
|
|
.info-panel h3{font-size:14px;font-weight:600;color:#333;margin-bottom:16px;padding-bottom:10px;border-bottom:1px solid #f0f0f0}
|
|
.info-item{margin-bottom:14px}
|
|
.info-item label{display:block;font-size:12px;color:#999;margin-bottom:4px}
|
|
.info-item span{font-size:13px;color:#333}
|
|
.info-item .tag{display:inline-block;padding:2px 8px;border-radius:4px;font-size:11px;font-weight:500}
|
|
.info-item .tag.online{background:#f6ffed;color:#52c41a}
|
|
.info-item .tag.offline{background:#fff0f0;color:#ff4d4f}
|
|
.stats-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:12px}
|
|
.stat-card{background:#f5f7fa;border-radius:8px;padding:12px;text-align:center}
|
|
.stat-card .stat-value{font-size:24px;font-weight:700;color:#1a73e8}
|
|
.stat-card .stat-label{font-size:11px;color:#999;margin-top:4px}
|
|
|
|
/* ===== 空状态 ===== */
|
|
.empty-chat{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;color:#999}
|
|
.empty-chat-icon{font-size:48px;margin-bottom:16px;opacity:.3}
|
|
.empty-chat-text{font-size:14px}
|
|
|
|
/* ===== 图片查看器 ===== */
|
|
.image-viewer{position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.8);display:flex;align-items:center;justify-content:center;z-index:999;cursor:zoom-out}
|
|
.image-viewer img{max-width:80%;max-height:80%;border-radius:8px}
|
|
|
|
/* ===== 通知提示 ===== */
|
|
.toast{position:fixed;top:20px;right:20px;background:#333;color:#fff;padding:12px 20px;border-radius:8px;font-size:14px;z-index:1000;opacity:0;transform:translateY(-10px);transition:all .3s}
|
|
.toast.show{opacity:1;transform:translateY(0)}
|
|
.toast.success{background:#52c41a}
|
|
.toast.error{background:#ff4d4f}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="app">
|
|
<!-- 左侧客户列表 -->
|
|
<div class="sidebar">
|
|
<div class="sidebar-header">
|
|
<h2><%= agentInfo.tenant_name || '客服工作台' %></h2>
|
|
<div class="agent-bar">
|
|
<div class="status-selector">
|
|
<span class="status-dot" id="agentStatusDot"></span>
|
|
<select id="agentStatusSelect" onchange="changeAgentStatus(this.value)">
|
|
<option value="online">在线</option>
|
|
<option value="busy">忙碌</option>
|
|
<option value="offline">离线</option>
|
|
</select>
|
|
</div>
|
|
</div>
|
|
<div class="conn-info">
|
|
<span class="status-dot online" id="connDot"></span>
|
|
<span id="connText">连接中...</span>
|
|
</div>
|
|
</div>
|
|
<div class="sidebar-search">
|
|
<input type="text" placeholder="搜索客户..." id="searchInput" oninput="renderCustomerList()">
|
|
</div>
|
|
<div class="customer-list" id="customerList">
|
|
<div style="padding:40px;text-align:center;color:#999;font-size:13px">
|
|
加载中...
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- 中间聊天区域 -->
|
|
<div class="chat-area" style="position:relative">
|
|
<div class="chat-header">
|
|
<div class="chat-header-left">
|
|
<div class="customer-name" id="chatCustomerName">请选择客户</div>
|
|
<div class="customer-status" id="chatCustomerStatus"></div>
|
|
</div>
|
|
<div class="chat-header-right">
|
|
<div class="conn-status connecting" id="connStatus">连接中</div>
|
|
</div>
|
|
</div>
|
|
<div class="chat-messages" id="chatMessages">
|
|
<div class="empty-chat">
|
|
<div class="empty-chat-icon">💬</div>
|
|
<div class="empty-chat-text">选择一个客户开始对话</div>
|
|
</div>
|
|
</div>
|
|
<div class="chat-input-area">
|
|
<div class="input-toolbar">
|
|
<button class="toolbar-btn" onclick="toggleQuickReply()">快捷回复</button>
|
|
<button class="toolbar-btn" onclick="document.getElementById('imageUploadInput').click()">图片</button>
|
|
<button class="toolbar-btn" onclick="insertQuickReply('您好,请问有什么可以帮您?')">问候</button>
|
|
<button class="toolbar-btn" onclick="insertQuickReply('好的,请稍等,我为您查询。')">稍等</button>
|
|
<button class="toolbar-btn" onclick="insertQuickReply('感谢您的咨询,祝您生活愉快!')">结束</button>
|
|
</div>
|
|
<div class="input-wrapper">
|
|
<textarea id="messageInput" placeholder="输入消息,按 Enter 发送,Shift+Enter 换行..." rows="2" onkeydown="onMessageKeydown(event)" oninput="autoResize(this)"></textarea>
|
|
<button class="btn-send" id="btnSend" onclick="sendMessage()">发送</button>
|
|
</div>
|
|
<input type="file" id="imageUploadInput" class="image-upload" accept="image/*" onchange="onImageSelected(event)">
|
|
</div>
|
|
|
|
<!-- 快捷回复面板 -->
|
|
<div class="quick-reply-panel" id="quickReplyPanel">
|
|
<h4>快捷回复</h4>
|
|
<div class="quick-reply-category">常用</div>
|
|
<div class="quick-reply-item" onclick="insertQuickReply('您好,欢迎咨询!请问有什么可以帮您?')">您好,欢迎咨询!请问有什么可以帮您?</div>
|
|
<div class="quick-reply-item" onclick="insertQuickReply('好的,我这就为您处理。')">好的,我这就为您处理。</div>
|
|
<div class="quick-reply-item" onclick="insertQuickReply('请问还有其他问题吗?')">请问还有其他问题吗?</div>
|
|
<div class="quick-reply-item" onclick="insertQuickReply('非常抱歉给您带来不便。')">非常抱歉给您带来不便。</div>
|
|
<div class="quick-reply-item" onclick="insertQuickReply('感谢您的理解与支持!')">感谢您的理解与支持!</div>
|
|
<div class="quick-reply-item" onclick="insertQuickReply('祝您购物愉快!')">祝您购物愉快!</div>
|
|
<div class="quick-reply-category">物流</div>
|
|
<div class="quick-reply-item" onclick="insertQuickReply('您的订单已发货,预计1-3天到达。')">您的订单已发货,预计1-3天到达。</div>
|
|
<div class="quick-reply-item" onclick="insertQuickReply('请提供您的订单号,我帮您查询物流信息。')">请提供您的订单号,我帮您查询物流信息。</div>
|
|
<div class="quick-reply-item" onclick="insertQuickReply('物流显示已签收,请问您收到商品了吗?')">物流显示已签收,请问您收到商品了吗?</div>
|
|
<div class="quick-reply-category">售后</div>
|
|
<div class="quick-reply-item" onclick="insertQuickReply('如需退换货,请在7天内申请,我们会尽快处理。')">如需退换货,请在7天内申请,我们会尽快处理。</div>
|
|
<div class="quick-reply-item" onclick="insertQuickReply('退款已提交,预计1-3个工作日到账。')">退款已提交,预计1-3个工作日到账。</div>
|
|
</div>
|
|
|
|
<!-- 图片预览 -->
|
|
<div class="image-preview-container" id="imagePreviewContainer">
|
|
<img id="imagePreview" />
|
|
<span class="btn-cancel" onclick="cancelImageUpload()">取消</span>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- 右侧信息面板 -->
|
|
<div class="info-panel">
|
|
<h3>客户信息</h3>
|
|
<div id="customerInfo">
|
|
<div style="padding:20px;text-align:center;color:#999;font-size:13px">
|
|
选择客户查看详细信息
|
|
</div>
|
|
</div>
|
|
|
|
<h3 style="margin-top:24px">今日统计</h3>
|
|
<div class="stats-grid" id="statsGrid">
|
|
<div class="stat-card">
|
|
<div class="stat-value" id="statMessages">0</div>
|
|
<div class="stat-label">今日消息</div>
|
|
</div>
|
|
<div class="stat-card">
|
|
<div class="stat-value" id="statConversations">0</div>
|
|
<div class="stat-label">会话总数</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- 图片查看器 -->
|
|
<div class="image-viewer" id="imageViewer" style="display:none" onclick="closeImageViewer()">
|
|
<img id="imageViewerImg" />
|
|
</div>
|
|
|
|
<!-- 通知 -->
|
|
<div class="toast" id="toast"></div>
|
|
|
|
<script>
|
|
// ============ 配置 ============
|
|
var CONFIG = {
|
|
appId: '<%= agentInfo.app_id %>',
|
|
agentId: '<%= agentInfo.agent_id || "" %>',
|
|
wssHost: (location.protocol === 'https:' ? 'wss://' : 'ws://') + (location.hostname === 'localhost' ? 'localhost:9502' : 'wss.cnsaa.cn'),
|
|
};
|
|
|
|
// ============ 状态 ============
|
|
var ws = null;
|
|
var currentCustomer = null;
|
|
var customers = new Map();
|
|
var messageCache = new Map(); // clientid -> [messages]
|
|
var reconnectTimer = null;
|
|
var pingTimer = null;
|
|
var agentClientId = '';
|
|
var oldestMsgId = new Map(); // clientid -> oldest loaded msg id
|
|
var isLoadingHistory = false;
|
|
|
|
// ============ 生成 clientid ============
|
|
function generateClientId() {
|
|
var agentId = CONFIG.agentId || ('agent_' + Date.now() + '_' + Math.random().toString(36).substring(2, 8));
|
|
return 'type_weapp_' + CONFIG.appId + '_1_employee_' + agentId;
|
|
}
|
|
|
|
// ============ 从服务器获取签名并连接 WSS ============
|
|
function connectWebSocket() {
|
|
if (ws && (ws.readyState === WebSocket.CONNECTING || ws.readyState === WebSocket.OPEN)) {
|
|
return;
|
|
}
|
|
|
|
updateConnStatus('connecting');
|
|
|
|
// 从服务器 API 获取签名(避免在前端暴露 appSecret)
|
|
var xhr = new XMLHttpRequest();
|
|
xhr.open('GET', '/agent/api/wss-config');
|
|
xhr.onload = function() {
|
|
if (xhr.status === 200) {
|
|
var resp = JSON.parse(xhr.responseText);
|
|
if (resp.success && resp.data) {
|
|
doConnect(resp.data);
|
|
} else {
|
|
updateConnStatus('disconnected');
|
|
scheduleReconnect();
|
|
}
|
|
} else if (xhr.status === 401) {
|
|
window.location.href = '/agent';
|
|
} else {
|
|
updateConnStatus('disconnected');
|
|
scheduleReconnect();
|
|
}
|
|
};
|
|
xhr.onerror = function() {
|
|
updateConnStatus('disconnected');
|
|
scheduleReconnect();
|
|
};
|
|
xhr.send();
|
|
}
|
|
|
|
function doConnect(authData) {
|
|
agentClientId = generateClientId();
|
|
|
|
var wsUrl = CONFIG.wssHost + '?appId=' + authData.appId +
|
|
'&signature=' + authData.signature +
|
|
'&nonceStr=' + authData.nonceStr +
|
|
'×tamp=' + authData.timestamp +
|
|
'&clientid=' + agentClientId +
|
|
'&agent_id=' + (CONFIG.agentId || '');
|
|
|
|
try {
|
|
ws = new WebSocket(wsUrl);
|
|
} catch (e) {
|
|
updateConnStatus('disconnected');
|
|
scheduleReconnect();
|
|
return;
|
|
}
|
|
|
|
ws.onopen = function() {
|
|
console.log('[WSS] Connected');
|
|
updateConnStatus('connected');
|
|
startPing();
|
|
showToast('已连接到服务器', 'success');
|
|
};
|
|
|
|
ws.onmessage = function(event) {
|
|
try {
|
|
var data = JSON.parse(event.data);
|
|
handleMessage(data);
|
|
} catch (e) {
|
|
console.log('[WSS] Non-JSON message:', event.data);
|
|
}
|
|
};
|
|
|
|
ws.onclose = function() {
|
|
console.log('[WSS] Disconnected');
|
|
updateConnStatus('disconnected');
|
|
stopPing();
|
|
scheduleReconnect();
|
|
};
|
|
|
|
ws.onerror = function(error) {
|
|
console.error('[WSS] Error:', error);
|
|
updateConnStatus('disconnected');
|
|
};
|
|
}
|
|
|
|
function updateConnStatus(status) {
|
|
var dot = document.getElementById('connDot');
|
|
var text = document.getElementById('connText');
|
|
var statusEl = document.getElementById('connStatus');
|
|
|
|
if (status === 'connected') {
|
|
dot.className = 'status-dot online';
|
|
text.textContent = '已连接';
|
|
statusEl.textContent = '在线';
|
|
statusEl.className = 'conn-status';
|
|
} else if (status === 'connecting') {
|
|
dot.className = 'status-dot busy';
|
|
text.textContent = '连接中...';
|
|
statusEl.textContent = '连接中';
|
|
statusEl.className = 'conn-status connecting';
|
|
} else {
|
|
dot.className = 'status-dot offline';
|
|
text.textContent = '已断开';
|
|
statusEl.textContent = '离线';
|
|
statusEl.className = 'conn-status disconnected';
|
|
}
|
|
}
|
|
|
|
function startPing() {
|
|
stopPing();
|
|
pingTimer = setInterval(function() {
|
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
ws.send(JSON.stringify({ type: 'ping' }));
|
|
}
|
|
}, 25000);
|
|
}
|
|
|
|
function stopPing() {
|
|
if (pingTimer) {
|
|
clearInterval(pingTimer);
|
|
pingTimer = null;
|
|
}
|
|
}
|
|
|
|
function scheduleReconnect() {
|
|
if (reconnectTimer) return;
|
|
reconnectTimer = setTimeout(function() {
|
|
reconnectTimer = null;
|
|
connectWebSocket();
|
|
}, 3000);
|
|
}
|
|
|
|
// ============ 消息处理 ============
|
|
function handleMessage(data) {
|
|
console.log('[WSS] Received:', data);
|
|
|
|
if (data.type === 'pong') return;
|
|
|
|
if (data.type === 'init') {
|
|
console.log('[WSS] Init received:', data.clientid);
|
|
return;
|
|
}
|
|
|
|
if (data.type === 'offline_messages') {
|
|
// 离线消息同步
|
|
handleOfflineMessages(data.data || []);
|
|
return;
|
|
}
|
|
|
|
if (data.type === 'chat') {
|
|
handleIncomingChat(data);
|
|
return;
|
|
}
|
|
|
|
if (data.type === 'chat_ack') {
|
|
// 发送回执
|
|
handleChatAck(data);
|
|
return;
|
|
}
|
|
|
|
if (data.type === 'read_receipt') {
|
|
// 已读回执
|
|
handleReadReceipt(data);
|
|
return;
|
|
}
|
|
|
|
if (data.type === 'agent_status') {
|
|
// 坐席状态变更(客户侧)
|
|
return;
|
|
}
|
|
}
|
|
|
|
function handleIncomingChat(data) {
|
|
var from = data.from;
|
|
var content = data.data || data.content || '';
|
|
var msgType = data.msg_type || 'text';
|
|
var msgId = data.msg_id;
|
|
var time = data.time || new Date().toISOString().replace('T', ' ').substring(0, 19);
|
|
|
|
// 解析 from clientid 提取客户信息
|
|
var parsed = parseClientIdLocal(from);
|
|
if (!parsed) return;
|
|
|
|
var customerClientid = from;
|
|
var customerName = '客户 ' + (parsed.uid || from.split('_').pop().substring(0, 6));
|
|
|
|
// 确保客户在列表中
|
|
if (!customers.has(customerClientid)) {
|
|
customers.set(customerClientid, {
|
|
clientid: customerClientid,
|
|
name: customerName,
|
|
online: true,
|
|
unread: 0,
|
|
lastMessage: null,
|
|
});
|
|
messageCache.set(customerClientid, []);
|
|
}
|
|
|
|
// 添加到消息缓存
|
|
var msg = {
|
|
id: msgId,
|
|
type: msgType,
|
|
content: content,
|
|
from: from,
|
|
self: false,
|
|
time: time,
|
|
is_read: 0,
|
|
};
|
|
messageCache.get(customerClientid).push(msg);
|
|
|
|
// 更新客户信息
|
|
var customer = customers.get(customerClientid);
|
|
customer.lastMessage = msg;
|
|
customer.online = true;
|
|
|
|
// 如果不是当前选中的客户,增加未读数
|
|
if (!currentCustomer || currentCustomer.clientid !== customerClientid) {
|
|
customer.unread = (customer.unread || 0) + 1;
|
|
} else {
|
|
// 当前客户,自动标记已读
|
|
markMessagesRead(customerClientid);
|
|
}
|
|
|
|
renderCustomerList();
|
|
if (currentCustomer && currentCustomer.clientid === customerClientid) {
|
|
renderMessages(customerClientid);
|
|
}
|
|
}
|
|
|
|
function handleOfflineMessages(msgs) {
|
|
for (var i = 0; i < msgs.length; i++) {
|
|
var m = msgs[i];
|
|
var customerClientid = m.from_clientid || m.clientid;
|
|
|
|
if (!customers.has(customerClientid)) {
|
|
customers.set(customerClientid, {
|
|
clientid: customerClientid,
|
|
name: '客户 ' + customerClientid.split('_').pop().substring(0, 6),
|
|
online: false,
|
|
unread: 0,
|
|
lastMessage: null,
|
|
});
|
|
messageCache.set(customerClientid, []);
|
|
}
|
|
|
|
var msg = {
|
|
id: m.id,
|
|
type: m.msg_type,
|
|
content: m.content,
|
|
from: m.from_clientid,
|
|
self: false,
|
|
time: new Date(m.created_at * 1000).toISOString().replace('T', ' ').substring(0, 19),
|
|
is_read: m.is_read,
|
|
};
|
|
messageCache.get(customerClientid).push(msg);
|
|
|
|
var customer = customers.get(customerClientid);
|
|
customer.lastMessage = msg;
|
|
if (!currentCustomer || currentCustomer.clientid !== customerClientid) {
|
|
customer.unread = (customer.unread || 0) + 1;
|
|
}
|
|
}
|
|
|
|
renderCustomerList();
|
|
if (msgs.length > 0) {
|
|
showToast('收到 ' + msgs.length + ' 条离线消息', 'success');
|
|
}
|
|
}
|
|
|
|
function handleChatAck(data) {
|
|
// 更新对应消息的状态为已送达
|
|
var msgId = data.msg_id;
|
|
var toClientid = data.to;
|
|
var msgs = messageCache.get(toClientid);
|
|
if (msgs) {
|
|
for (var i = msgs.length - 1; i >= 0; i--) {
|
|
if (msgs[i].pending && !msgs[i].ack_id) {
|
|
msgs[i].ack_id = msgId;
|
|
msgs[i].pending = false;
|
|
msgs[i].time = data.time;
|
|
break;
|
|
}
|
|
}
|
|
if (currentCustomer && currentCustomer.clientid === toClientid) {
|
|
renderMessages(toClientid);
|
|
}
|
|
}
|
|
}
|
|
|
|
function handleReadReceipt(data) {
|
|
// 客户已读了坐席发的消息
|
|
var clientid = data.clientid;
|
|
var msgs = messageCache.get(clientid);
|
|
if (msgs) {
|
|
for (var i = 0; i < msgs.length; i++) {
|
|
if (msgs[i].self) {
|
|
msgs[i].is_read = 1;
|
|
}
|
|
}
|
|
if (currentCustomer && currentCustomer.clientid === clientid) {
|
|
renderMessages(clientid);
|
|
}
|
|
}
|
|
}
|
|
|
|
// ============ 发送消息 ============
|
|
function sendMessage() {
|
|
var input = document.getElementById('messageInput');
|
|
var content = input.value.trim();
|
|
|
|
if (!content) return;
|
|
if (!currentCustomer) {
|
|
showToast('请先选择一个客户', 'error');
|
|
return;
|
|
}
|
|
if (!ws || ws.readyState !== WebSocket.OPEN) {
|
|
showToast('WebSocket 未连接', 'error');
|
|
return;
|
|
}
|
|
|
|
var msg = {
|
|
type: 'chat',
|
|
to: currentCustomer.clientid,
|
|
data: content,
|
|
msg_type: 'text',
|
|
};
|
|
|
|
ws.send(JSON.stringify(msg));
|
|
|
|
// 添加到本地显示
|
|
var localMsg = {
|
|
type: 'text',
|
|
content: content,
|
|
from: agentClientId,
|
|
self: true,
|
|
time: new Date().toISOString().replace('T', ' ').substring(0, 19),
|
|
is_read: 0,
|
|
pending: true,
|
|
};
|
|
messageCache.get(currentCustomer.clientid).push(localMsg);
|
|
|
|
// 更新客户预览
|
|
var customer = customers.get(currentCustomer.clientid);
|
|
if (customer) customer.lastMessage = localMsg;
|
|
|
|
input.value = '';
|
|
input.style.height = '44px';
|
|
renderMessages(currentCustomer.clientid);
|
|
renderCustomerList();
|
|
}
|
|
|
|
// ============ 图片消息 ============
|
|
function onImageSelected(event) {
|
|
var file = event.target.files[0];
|
|
if (!file) return;
|
|
|
|
if (file.size > 2 * 1024 * 1024) {
|
|
showToast('图片大小不能超过 2MB', 'error');
|
|
event.target.value = '';
|
|
return;
|
|
}
|
|
|
|
var reader = new FileReader();
|
|
reader.onload = function(e) {
|
|
var base64 = e.target.result;
|
|
|
|
// 显示预览
|
|
var container = document.getElementById('imagePreviewContainer');
|
|
var img = document.getElementById('imagePreview');
|
|
img.src = base64;
|
|
container.classList.add('show');
|
|
|
|
// 如果有当前客户,发送图片
|
|
if (currentCustomer && ws && ws.readyState === WebSocket.OPEN) {
|
|
sendImageMessage(base64);
|
|
container.classList.remove('show');
|
|
} else {
|
|
showToast('请先选择客户', 'error');
|
|
container.classList.remove('show');
|
|
}
|
|
};
|
|
reader.readAsDataURL(file);
|
|
event.target.value = '';
|
|
}
|
|
|
|
function sendImageMessage(base64Data) {
|
|
var msg = {
|
|
type: 'chat',
|
|
to: currentCustomer.clientid,
|
|
data: base64Data,
|
|
msg_type: 'image',
|
|
};
|
|
|
|
ws.send(JSON.stringify(msg));
|
|
|
|
var localMsg = {
|
|
type: 'image',
|
|
content: base64Data,
|
|
from: agentClientId,
|
|
self: true,
|
|
time: new Date().toISOString().replace('T', ' ').substring(0, 19),
|
|
is_read: 0,
|
|
pending: true,
|
|
};
|
|
messageCache.get(currentCustomer.clientid).push(localMsg);
|
|
|
|
var customer = customers.get(currentCustomer.clientid);
|
|
if (customer) customer.lastMessage = { content: '[图片]', self: true, time: localMsg.time };
|
|
|
|
renderMessages(currentCustomer.clientid);
|
|
renderCustomerList();
|
|
}
|
|
|
|
function cancelImageUpload() {
|
|
document.getElementById('imagePreviewContainer').classList.remove('show');
|
|
}
|
|
|
|
// ============ 消息渲染 ============
|
|
function renderMessages(clientid) {
|
|
var container = document.getElementById('chatMessages');
|
|
var msgs = messageCache.get(clientid) || [];
|
|
|
|
if (msgs.length === 0) {
|
|
container.innerHTML = '<div class="empty-chat"><div class="empty-chat-icon">💬</div><div class="empty-chat-text">还没有消息,发送第一条消息吧</div></div>';
|
|
return;
|
|
}
|
|
|
|
var html = '';
|
|
var lastDate = null;
|
|
var oldestId = 0;
|
|
|
|
// 加载更多按钮
|
|
if (msgs.length > 0 && oldestMsgId.get(clientid)) {
|
|
html += '<div class="load-more" onclick="loadMoreHistory(\'' + clientid + '\')">加载更多消息</div>';
|
|
}
|
|
|
|
for (var i = 0; i < msgs.length; i++) {
|
|
var msg = msgs[i];
|
|
if (msg.id && (oldestId === 0 || msg.id < oldestId)) oldestId = msg.id;
|
|
|
|
var msgDate = new Date(msg.time).toDateString();
|
|
if (msgDate !== lastDate) {
|
|
html += '<div class="message-date">' + formatDate(msg.time) + '</div>';
|
|
lastDate = msgDate;
|
|
}
|
|
|
|
var isSelf = msg.self;
|
|
var avatarText = isSelf ? '客服' : (currentCustomer ? (currentCustomer.name || '客').charAt(0) : '客');
|
|
|
|
html += '<div class="message ' + (isSelf ? 'self' : '') + '">';
|
|
html += '<div class="message-avatar">' + escapeHtml(avatarText) + '</div>';
|
|
|
|
if (msg.type === 'image') {
|
|
html += '<div class="message-content" style="padding:4px">';
|
|
html += '<img class="message-image" src="' + msg.content + '" onclick="viewImage(this.src)" />';
|
|
html += '</div>';
|
|
} else {
|
|
html += '<div class="message-content">' + escapeHtml(msg.content) + '</div>';
|
|
}
|
|
|
|
html += '</div>';
|
|
|
|
// 时间和已读状态
|
|
if (isSelf) {
|
|
var readStatus = msg.is_read ? '<span class="message-read">已读</span>' : '<span class="message-unread">未读</span>';
|
|
html += '<div class="message-time-stamp" style="text-align:right">' + formatTime(msg.time) + ' ' + readStatus + '</div>';
|
|
}
|
|
}
|
|
|
|
oldestMsgId.set(clientid, oldestId);
|
|
container.innerHTML = html;
|
|
container.scrollTop = container.scrollHeight;
|
|
}
|
|
|
|
// ============ 聊天历史加载 ============
|
|
function loadHistory(clientid) {
|
|
var xhr = new XMLHttpRequest();
|
|
xhr.open('GET', '/agent/api/messages/history?clientid=' + encodeURIComponent(clientid) + '&limit=50');
|
|
xhr.onload = function() {
|
|
if (xhr.status === 200) {
|
|
var resp = JSON.parse(xhr.responseText);
|
|
if (resp.success && resp.data) {
|
|
var msgs = resp.data.map(function(m) {
|
|
return {
|
|
id: m.id,
|
|
type: m.msg_type,
|
|
content: m.content,
|
|
from: m.from_clientid,
|
|
self: m.from_role === 'agent',
|
|
time: new Date(m.created_at * 1000).toISOString().replace('T', ' ').substring(0, 19),
|
|
is_read: m.is_read,
|
|
};
|
|
});
|
|
messageCache.set(clientid, msgs);
|
|
|
|
// 更新 oldestMsgId
|
|
if (msgs.length > 0) {
|
|
oldestMsgId.set(clientid, msgs[0].id);
|
|
}
|
|
|
|
renderMessages(clientid);
|
|
}
|
|
}
|
|
};
|
|
xhr.send();
|
|
}
|
|
|
|
function loadMoreHistory(clientid) {
|
|
if (isLoadingHistory) return;
|
|
isLoadingHistory = true;
|
|
|
|
var beforeId = oldestMsgId.get(clientid) || 0;
|
|
var xhr = new XMLHttpRequest();
|
|
xhr.open('GET', '/agent/api/messages/history?clientid=' + encodeURIComponent(clientid) + '&before_id=' + beforeId + '&limit=50');
|
|
xhr.onload = function() {
|
|
isLoadingHistory = false;
|
|
if (xhr.status === 200) {
|
|
var resp = JSON.parse(xhr.responseText);
|
|
if (resp.success && resp.data && resp.data.length > 0) {
|
|
var olderMsgs = resp.data.map(function(m) {
|
|
return {
|
|
id: m.id,
|
|
type: m.msg_type,
|
|
content: m.content,
|
|
from: m.from_clientid,
|
|
self: m.from_role === 'agent',
|
|
time: new Date(m.created_at * 1000).toISOString().replace('T', ' ').substring(0, 19),
|
|
is_read: m.is_read,
|
|
};
|
|
});
|
|
|
|
// 合并到缓存前面
|
|
var existing = messageCache.get(clientid) || [];
|
|
messageCache.set(clientid, olderMsgs.concat(existing));
|
|
|
|
if (olderMsgs.length > 0) {
|
|
oldestMsgId.set(clientid, olderMsgs[0].id);
|
|
}
|
|
|
|
// 保持滚动位置
|
|
var container = document.getElementById('chatMessages');
|
|
var prevScrollHeight = container.scrollHeight;
|
|
renderMessages(clientid);
|
|
container.scrollTop = container.scrollHeight - prevScrollHeight;
|
|
} else {
|
|
showToast('没有更多消息了', 'info');
|
|
}
|
|
}
|
|
};
|
|
xhr.send();
|
|
}
|
|
|
|
// ============ 已读标记 ============
|
|
function markMessagesRead(clientid) {
|
|
var xhr = new XMLHttpRequest();
|
|
xhr.open('POST', '/agent/api/messages/read');
|
|
xhr.setRequestHeader('Content-Type', 'application/json');
|
|
xhr.onload = function() {
|
|
if (xhr.status === 200) {
|
|
var resp = JSON.parse(xhr.responseText);
|
|
if (resp.success) {
|
|
// 更新本地未读数
|
|
var customer = customers.get(clientid);
|
|
if (customer) {
|
|
customer.unread = 0;
|
|
renderCustomerList();
|
|
}
|
|
}
|
|
}
|
|
};
|
|
xhr.send(JSON.stringify({ clientid: clientid }));
|
|
}
|
|
|
|
// ============ 客户列表 ============
|
|
function selectCustomer(customer) {
|
|
currentCustomer = customer;
|
|
|
|
// 更新 UI
|
|
document.querySelectorAll('.customer-item').forEach(function(el) {
|
|
el.classList.remove('active');
|
|
});
|
|
var el = document.querySelector('[data-clientid="' + customer.clientid + '"]');
|
|
if (el) el.classList.add('active');
|
|
|
|
// 更新聊天头部
|
|
document.getElementById('chatCustomerName').textContent = customer.name || '未知客户';
|
|
var statusEl = document.getElementById('chatCustomerStatus');
|
|
statusEl.textContent = customer.online ? '在线' : '离线';
|
|
statusEl.className = customer.online ? 'customer-status' : 'customer-status offline';
|
|
|
|
// 更新客户信息面板
|
|
renderCustomerInfo(customer);
|
|
|
|
// 加载聊天历史
|
|
loadHistory(customer.clientid);
|
|
|
|
// 标记已读
|
|
if (customer.unread > 0) {
|
|
markMessagesRead(customer.clientid);
|
|
}
|
|
}
|
|
|
|
function renderCustomerInfo(customer) {
|
|
var container = document.getElementById('customerInfo');
|
|
var msgCount = (messageCache.get(customer.clientid) || []).length;
|
|
container.innerHTML =
|
|
'<div class="info-item"><label>客户名称</label><span>' + escapeHtml(customer.name || '未知') + '</span></div>' +
|
|
'<div class="info-item"><label>客户ID</label><span style="font-size:11px;font-family:monospace;word-break:break-all">' + escapeHtml(customer.clientid) + '</span></div>' +
|
|
'<div class="info-item"><label>在线状态</label><span class="tag ' + (customer.online ? 'online' : 'offline') + '">' + (customer.online ? '在线' : '离线') + '</span></div>' +
|
|
'<div class="info-item"><label>消息数量</label><span>' + msgCount + ' 条</span></div>';
|
|
}
|
|
|
|
function renderCustomerList() {
|
|
var container = document.getElementById('customerList');
|
|
var searchTerm = (document.getElementById('searchInput').value || '').toLowerCase();
|
|
|
|
var list = Array.from(customers.values()).filter(function(c) {
|
|
return (c.name || '').toLowerCase().indexOf(searchTerm) >= 0 ||
|
|
c.clientid.toLowerCase().indexOf(searchTerm) >= 0;
|
|
});
|
|
|
|
// 按最后消息时间排序
|
|
list.sort(function(a, b) {
|
|
var aTime = a.lastMessage ? new Date(a.lastMessage.time).getTime() : 0;
|
|
var bTime = b.lastMessage ? new Date(b.lastMessage.time).getTime() : 0;
|
|
return bTime - aTime;
|
|
});
|
|
|
|
if (list.length === 0) {
|
|
container.innerHTML = '<div style="padding:40px;text-align:center;color:#999;font-size:13px">' +
|
|
(searchTerm ? '未找到匹配的客户' : '暂无会话,等待客户接入...') + '</div>';
|
|
return;
|
|
}
|
|
|
|
var html = '';
|
|
for (var i = 0; i < list.length; i++) {
|
|
var c = list[i];
|
|
var isActive = currentCustomer && currentCustomer.clientid === c.clientid;
|
|
var lastContent = c.lastMessage ? (c.lastMessage.type === 'image' ? '[图片]' : c.lastMessage.content.substring(0, 20)) : '暂无消息';
|
|
var lastTime = c.lastMessage ? formatTime(c.lastMessage.time) : '';
|
|
|
|
html += '<div class="customer-item ' + (isActive ? 'active' : '') + '" data-clientid="' + c.clientid + '" onclick=\'selectCustomer(' + JSON.stringify(c).replace(/'/g, "'") + ')\'>';
|
|
html += '<div class="customer-avatar ' + (c.online ? '' : 'offline') + '">' + escapeHtml((c.name || '客').charAt(0));
|
|
html += '<span class="online-dot ' + (c.online ? '' : 'offline') + '"></span>';
|
|
html += '</div>';
|
|
html += '<div class="customer-info">';
|
|
html += '<div class="customer-name">' + escapeHtml(c.name || '未知') + '</div>';
|
|
html += '<div class="customer-preview">' + escapeHtml(lastContent) + '</div>';
|
|
html += '</div>';
|
|
html += '<div class="customer-meta">';
|
|
html += '<div class="customer-time">' + lastTime + '</div>';
|
|
if (c.unread > 0) {
|
|
html += '<div class="customer-badge">' + c.unread + '</div>';
|
|
}
|
|
html += '</div>';
|
|
html += '</div>';
|
|
}
|
|
container.innerHTML = html;
|
|
}
|
|
|
|
// ============ 快捷回复 ============
|
|
function toggleQuickReply() {
|
|
var panel = document.getElementById('quickReplyPanel');
|
|
panel.classList.toggle('show');
|
|
}
|
|
|
|
function insertQuickReply(text) {
|
|
var input = document.getElementById('messageInput');
|
|
if (input.value) {
|
|
input.value += '\n' + text;
|
|
} else {
|
|
input.value = text;
|
|
}
|
|
input.focus();
|
|
autoResize(input);
|
|
document.getElementById('quickReplyPanel').classList.remove('show');
|
|
}
|
|
|
|
// ============ 坐席状态 ============
|
|
function changeAgentStatus(status) {
|
|
var dot = document.getElementById('agentStatusDot');
|
|
dot.className = 'status-dot ' + status;
|
|
|
|
// 通过 WebSocket 发送状态变更
|
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
ws.send(JSON.stringify({ type: 'status', status: status }));
|
|
}
|
|
|
|
// 同时通过 API 保存
|
|
var xhr = new XMLHttpRequest();
|
|
xhr.open('POST', '/agent/api/status');
|
|
xhr.setRequestHeader('Content-Type', 'application/json');
|
|
xhr.onload = function() {
|
|
if (xhr.status === 200) {
|
|
showToast('状态已更新为: ' + ({ online: '在线', busy: '忙碌', offline: '离线' }[status]), 'success');
|
|
}
|
|
};
|
|
xhr.send(JSON.stringify({ status: status }));
|
|
}
|
|
|
|
// ============ 统计 ============
|
|
function loadStats() {
|
|
var xhr = new XMLHttpRequest();
|
|
xhr.open('GET', '/agent/api/stats');
|
|
xhr.onload = function() {
|
|
if (xhr.status === 200) {
|
|
var resp = JSON.parse(xhr.responseText);
|
|
if (resp.success && resp.data) {
|
|
document.getElementById('statMessages').textContent = resp.data.today_messages || 0;
|
|
document.getElementById('statConversations').textContent = resp.data.total_conversations || 0;
|
|
}
|
|
}
|
|
};
|
|
xhr.send();
|
|
}
|
|
|
|
// ============ 会话列表加载 ============
|
|
function loadConversations() {
|
|
var xhr = new XMLHttpRequest();
|
|
xhr.open('GET', '/agent/api/conversations');
|
|
xhr.onload = function() {
|
|
if (xhr.status === 200) {
|
|
var resp = JSON.parse(xhr.responseText);
|
|
if (resp.success && resp.data) {
|
|
for (var i = 0; i < resp.data.length; i++) {
|
|
var conv = resp.data[i];
|
|
if (!customers.has(conv.clientid)) {
|
|
customers.set(conv.clientid, {
|
|
clientid: conv.clientid,
|
|
name: '客户 ' + conv.clientid.split('_').pop().substring(0, 6),
|
|
online: conv.online || false,
|
|
unread: conv.unread_count || 0,
|
|
lastMessage: conv.last_msg_content ? {
|
|
content: conv.last_msg_content,
|
|
type: conv.last_msg_type,
|
|
time: new Date(conv.last_msg_time * 1000).toISOString().replace('T', ' ').substring(0, 19),
|
|
} : null,
|
|
});
|
|
messageCache.set(conv.clientid, []);
|
|
} else {
|
|
var c = customers.get(conv.clientid);
|
|
c.online = conv.online || false;
|
|
if (conv.unread_count !== undefined) c.unread = conv.unread_count;
|
|
}
|
|
}
|
|
renderCustomerList();
|
|
}
|
|
} else {
|
|
// 如果 session 过期,跳转登录
|
|
if (xhr.status === 401) {
|
|
window.location.href = '/agent';
|
|
}
|
|
}
|
|
};
|
|
xhr.send();
|
|
}
|
|
|
|
// ============ 工具函数 ============
|
|
function parseClientIdLocal(clientid) {
|
|
if (!clientid || typeof clientid !== 'string') return null;
|
|
var parts = clientid.split('_');
|
|
if (parts.length < 6 || parts[0] !== 'type') return null;
|
|
var channel = parts[1], appId = parts[2], uniacid = parts[3], role = parts[4];
|
|
if (role === 'customer' && parts.length >= 7) {
|
|
return { type: 'type', channel: channel, appId: appId, uniacid: uniacid, role: 'customer', uid: parts[5], agentId: parts[6] };
|
|
} else if (role === 'employee') {
|
|
return { type: 'type', channel: channel, appId: appId, uniacid: uniacid, role: 'employee', uid: null, agentId: parts[5] };
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function escapeHtml(text) {
|
|
var div = document.createElement('div');
|
|
div.textContent = text;
|
|
return div.innerHTML;
|
|
}
|
|
|
|
function formatDate(date) {
|
|
var d = new Date(date);
|
|
var now = new Date();
|
|
var isToday = d.toDateString() === now.toDateString();
|
|
if (isToday) {
|
|
return d.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
|
|
}
|
|
var yesterday = new Date(now - 86400000);
|
|
if (d.toDateString() === yesterday.toDateString()) {
|
|
return '昨天 ' + d.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
|
|
}
|
|
return d.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' }) + ' ' + d.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
|
|
}
|
|
|
|
function formatTime(date) {
|
|
return new Date(date).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
|
|
}
|
|
|
|
function autoResize(textarea) {
|
|
textarea.style.height = '44px';
|
|
textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px';
|
|
}
|
|
|
|
function onMessageKeydown(event) {
|
|
if (event.key === 'Enter' && !event.shiftKey) {
|
|
event.preventDefault();
|
|
sendMessage();
|
|
}
|
|
}
|
|
|
|
function viewImage(src) {
|
|
var viewer = document.getElementById('imageViewer');
|
|
var img = document.getElementById('imageViewerImg');
|
|
img.src = src;
|
|
viewer.style.display = 'flex';
|
|
}
|
|
|
|
function closeImageViewer() {
|
|
document.getElementById('imageViewer').style.display = 'none';
|
|
}
|
|
|
|
var toastTimer = null;
|
|
function showToast(msg, type) {
|
|
var toast = document.getElementById('toast');
|
|
toast.textContent = msg;
|
|
toast.className = 'toast show ' + (type || '');
|
|
if (toastTimer) clearTimeout(toastTimer);
|
|
toastTimer = setTimeout(function() {
|
|
toast.classList.remove('show');
|
|
}, 3000);
|
|
}
|
|
|
|
// ============ 初始化 ============
|
|
function init() {
|
|
connectWebSocket();
|
|
loadConversations();
|
|
loadStats();
|
|
|
|
// 定期刷新会话列表和统计
|
|
setInterval(loadConversations, 30000);
|
|
setInterval(loadStats, 60000);
|
|
|
|
// 定期尝试重连
|
|
setInterval(function() {
|
|
if (!ws || ws.readyState === WebSocket.CLOSED) {
|
|
connectWebSocket();
|
|
}
|
|
}, 10000);
|
|
}
|
|
|
|
window.addEventListener('DOMContentLoaded', init);
|
|
window.addEventListener('beforeunload', function() {
|
|
stopPing();
|
|
if (ws) ws.close();
|
|
});
|
|
</script>
|
|
</body>
|
|
</html>
|