var isHumanMode = false; // 当前是否为人工客服模式 var humanServiceOnline = false; // 客服是否在线 var serviceCheckInterval = null; // 客服状态检查定时器 var chatPollingInterval = null; // 聊天消息轮询定时器 var lastMsgId = 0; // 最后一条消息ID var dividerAdded = false; // 分隔线是否已添加标志 var isFirstLoad = true; // 是否第一次加载标志 var CHAT_DIVIDER_TIMEOUT = 1800; // 聊天分隔线显示的时间间隔阈值(秒),30分钟 // 获取当前时间戳(秒) function getCurrentTimestamp() { return Math.floor(Date.now() / 1000); } // 添加缺失的scrollToBottom函数 function scrollToBottom() { // 滚动到底部 setTimeout(() => { const chatBody = document.getElementById('chatBody'); if (chatBody) { chatBody.scrollTop = chatBody.scrollHeight; } }, 50); } // 页面加载完成后检查客服状态 document.addEventListener('DOMContentLoaded', function() { // 初始化客服 // initService(); }); // 初始化客服 function initService(){ // 检查客服状态 checkServiceStatus(); // 加载历史聊天记录 loadChatHistory(); } // 加载历史聊天记录 function loadChatHistory() { var xhr = new XMLHttpRequest(); xhr.open("GET", VG.root_dir + "/index.php?m=plugins&c=AiHelper&a=getChatHistory", true); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { try { var response = JSON.parse(xhr.responseText); if (response.code == 1 && response.data && response.data.data && response.data.data.length > 0) { var messageData = response.data.data; var lastMessageTime = response.data.last_message_time || 0; // 处理历史消息,先检查时间间隔 if (messageData.length > 0) { var currentTime = getCurrentTimestamp(); // 当前时间戳(秒) for (var i = 0; i < messageData.length; i++) { var msg = messageData[i]; var msgTime = msg.add_time || 0; var timeDiff = currentTime - msgTime; if (timeDiff < CHAT_DIVIDER_TIMEOUT && !dividerAdded) { addChatDivider(); dividerAdded = true; } if (msg.from_type === 'user') { addMessage("我", msg.content, "user", msg.add_time); } else if (msg.from_type === 'service') { addMessage(VG.nickname, msg.content, "ai", msg.add_time); } else if (msg.from_type === 'system') { addMessage(VG.nickname, msg.content, "ai", msg.add_time); } // 更新最后消息ID if (msg.id > lastMsgId) { lastMsgId = msg.id; } } // 如果需要添加分隔线 if (isFirstLoad) { var timeDiff = currentTime - lastMessageTime; if (lastMessageTime > 0 && timeDiff > CHAT_DIVIDER_TIMEOUT && !dividerAdded) { addChatDivider(); dividerAdded = true; } isFirstLoad = false; } } // 滚动到底部 scrollToBottom(); // 重新绑定常见问题点击事件 var subItems = document.querySelectorAll('.faq-bubble-item .sub-item'); for(var i = 0; i < subItems.length; i++) { subItems[i].addEventListener('click', function() { sendMessage(2, this.getAttribute('data-name')); }); } } } catch (e) { console.error("解析历史聊天记录失败:", e); } } }; xhr.send(); } // 转换到人工客服模式 function transferToHumanService() { if (VG.rg_mode != 1) { if (VG.rg_url && VG.rg_url.length > 0) { newWin_ai_helper(VG.rg_url, 'ai_helper_rg_url'); } return; } if (isHumanMode) { // 如果已经是人工模式,则不处理 return; } // 重置分隔线添加状态 dividerAdded = false; // 检查客服是否在线 checkServiceStatus(function(online, weapp_data) { if (online) { // 切换到人工客服模式 isHumanMode = true; // 更新UI显示 document.getElementById('serviceModeText').innerText = "人工客服"; document.getElementById('serviceStatus').style.display = 'inline-block'; document.getElementById('serviceStatus').className = 'service-status service-online'; // 发送系统消息通知用户 addMessage("系统", "已接入人工座席,客服马上为您提供服务", "ai", getCurrentTimestamp()); // 向后台发送转人工请求 var xhr = new XMLHttpRequest(); xhr.open("POST", VG.root_dir + "/index.php?m=plugins&c=AiHelper&a=transferToHuman", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status == 200) { try { var response = JSON.parse(xhr.responseText); if (response.code == 1) { var msgData = response.data.msg_data; // 更新最后消息ID lastMsgId = msgData.id; // 开始轮询获取消息 startChatPolling(); } else { addMessage("系统", response.msg || "人工客服暂时繁忙,请稍后再试", "ai", getCurrentTimestamp()); isHumanMode = false; document.getElementById('serviceModeText').innerText = VG.nickname; document.getElementById('serviceStatus').style.display = 'none'; } } catch (e) { console.error("解析转人工响应失败:", e); addMessage("系统", "转接人工客服失败,请稍后重试", "ai", getCurrentTimestamp()); isHumanMode = false; document.getElementById('serviceModeText').innerText = VG.nickname; document.getElementById('serviceStatus').style.display = 'none'; } } else { addMessage("系统", "网络连接失败,请稍后重试", "ai", getCurrentTimestamp()); isHumanMode = false; document.getElementById('serviceModeText').innerText = VG.nickname; document.getElementById('serviceStatus').style.display = 'none'; } } }; xhr.send("action=transfer"); } else { // 客服不在线,显示提示 addMessage("系统", weapp_data.human_service_offline_reply, "ai", getCurrentTimestamp()); } }); } // 检查客服状态 function checkServiceStatus(callback) { var xhr = new XMLHttpRequest(); xhr.open("GET", VG.root_dir + "/index.php?m=plugins&c=AiHelper&a=checkServiceStatus", true); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { try { var response = JSON.parse(xhr.responseText); humanServiceOnline = response.code == 1; /*if (document.getElementById('transferBtn')) { if (humanServiceOnline) { // 更新客服状态指示器 document.getElementById('transferBtn').style.opacity = "1"; } else { // 客服不在线 document.getElementById('transferBtn').style.opacity = "0.5"; } }*/ if (typeof callback === 'function') { callback(humanServiceOnline, response.data.weapp_data); } } catch (e) { console.error("解析客服状态响应失败:", e); if (typeof callback === 'function') { callback(false, {}); } } } }; xhr.send(); } // 开始轮询获取人工客服消息 function startChatPolling() { if (chatPollingInterval) { clearInterval(chatPollingInterval); } // 每3秒轮询一次新消息 chatPollingInterval = setInterval(function() { if (!isHumanMode) { clearInterval(chatPollingInterval); return; } fetchNewMessages(); }, 3000); } // 获取新消息 function fetchNewMessages() { var xhr = new XMLHttpRequest(); xhr.open("GET", VG.root_dir + "/index.php?m=plugins&c=AiHelper&a=getHumanMessages&last_id=" + lastMsgId, true); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { try { var response = JSON.parse(xhr.responseText); if (response.code == 1 && response.data && response.data.length > 0) { // 处理新消息 for (var i = 0; i < response.data.length; i++) { var msg = response.data[i]; if (msg.from_type === 'service') { addMessage(VG.nickname, msg.content, "ai", msg.add_time); } else if (msg.from_type === 'system') { addMessage(VG.nickname, msg.content, "ai", msg.add_time); } // 更新最后消息ID if (msg.id > lastMsgId) { lastMsgId = msg.id; } } // 收到消息后滚动到底部 scrollToBottom(); } // 实时检查客服状态,无论会话是否已接入 // 当客服变为离线时,显示提示并切换回AI模式 if (response.service_status === false) { addMessage("系统", "人工客服已结束服务,智能助手继续为您服务", "ai", getCurrentTimestamp()); isHumanMode = false; document.getElementById('serviceModeText').innerText = VG.nickname; document.getElementById('serviceStatus').style.display = 'none'; clearInterval(chatPollingInterval); } } catch (e) { console.error("解析新消息响应失败:", e); } } }; xhr.send(); } // 保存原始的sendMessage函数 var originalSendMessage = window.sendMessage; // 完全重写sendMessage函数 window.sendMessage = function(type, question) { // 如果是人工客服模式 if (isHumanMode) { // 获取用户输入 var input = document.getElementById('chatInput'); var message = input.value.trim(); if (type == 2 && question) { message = question; } if (!message) { return; } // 清空输入框 input.value = ''; // 显示用户消息 addMessage("我", message, "user", getCurrentTimestamp()); // 人工客服模式,发送消息到后端 var xhr = new XMLHttpRequest(); xhr.open("POST", VG.root_dir + "/index.php?m=plugins&c=AiHelper&a=sendToHumanService", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status == 200) { try { var response = JSON.parse(xhr.responseText); if (response.code != 1) { addMessage("系统", response.msg || "消息发送失败,请重试", "ai", getCurrentTimestamp()); } } catch (e) { console.error("解析发送消息响应失败:", e); addMessage("系统", "消息发送失败,请重试", "ai", getCurrentTimestamp()); } } else { addMessage("系统", "消息发送失败,请重试", "ai", getCurrentTimestamp()); } } }; xhr.send("message=" + encodeURIComponent(message)); } else { // AI模式 var result = originalSendMessage.apply(this, arguments); // 获取用户发送的消息内容 var input = document.getElementById('chatInput'); var message = input.value.trim(); if (type == 2 && question) { message = question; } if (!message) { return result; } // 额外发送到后端保存聊天记录 setTimeout(function() { // 获取AI回复的内容(最后一条消息) var messagesContainer = document.getElementById('chatMessages'); var allMessages = messagesContainer.querySelectorAll('.chat-message'); var lastAiMessage = ""; if (allMessages.length > 0) { var lastMessage = allMessages[allMessages.length - 1]; if (lastMessage.classList.contains('ai')) { var contentDiv = lastMessage.querySelector('.message-content'); if (contentDiv) { lastAiMessage = contentDiv.innerHTML; } } } // 发送到后端保存 var xhr = new XMLHttpRequest(); xhr.open("POST", VG.root_dir + "/index.php?m=plugins&c=AiHelper&a=saveAIChat", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send("user_message=" + encodeURIComponent(message) + "&ai_response=" + encodeURIComponent(lastAiMessage)); }, 1000); // 延迟1秒,确保AI回复已经生成 return result; } }; function addHumanMessage(msg) { } // 添加消息到聊天界面 function addMessage(sender, message, type, timestamp) { var messagesContainer = document.getElementById('chatMessages'); var messageDiv = document.createElement('div'); // 检查是否是转接中的消息 var isTransferMessage = message.indexOf("正在转接中") !== -1 || message.indexOf("正在为您转接") !== -1 || message.indexOf("正在为您连接") !== -1; if (isTransferMessage) { // 转接消息样式 messageDiv.className = 'chat-message transfer-message'; messageDiv.innerHTML = `
${message}
`; } else { messageDiv.className = 'chat-message ' + type; // 获取时间显示,优先使用传入的时间戳 if (!timestamp) { timestamp = getCurrentTimestamp(); } var timeStr = formatTimestamp(timestamp); // 检查消息内容是否包含"常见问题"列表 let processedMessage = message; if (message.indexOf("常见问题") !== -1 && message.indexOf("
${type === 'user' ? '' : ''}
${sender} ${timeStr}
${processMessageContent(processedMessage)}
`; } messagesContainer.appendChild(messageDiv); scrollToBottom(); } // 格式化时间戳为指定格式 function formatTimestamp(timestamp) { // 如果没有传入时间戳,使用当前时间 const date = timestamp ? new Date(timestamp * 1000) : new Date(); const today = new Date(); today.setHours(0, 0, 0, 0); // 格式化时间部分 (时:分:秒) const hours = date.getHours().toString().padStart(2, '0'); const minutes = date.getMinutes().toString().padStart(2, '0'); const seconds = date.getSeconds().toString().padStart(2, '0'); const timeStr = `${hours}:${minutes}:${seconds}`; // 判断是否是当天 if (date >= today && date < new Date(today.getTime() + 24 * 60 * 60 * 1000)) { // 当天只显示时间 return timeStr; } else { // 非当天显示日期和时间 const month = (date.getMonth() + 1).toString().padStart(2, '0'); const day = date.getDate().toString().padStart(2, '0'); return `${month}-${day} ${timeStr}`; } } // 添加处理消息内容的函数 function processMessageContent(content) { // 使用正则表达式匹配 标签 return content.replace(//g, ''); } // 添加聊天分隔线 function addChatDivider() { var messagesContainer = document.getElementById('chatMessages'); var dividerDiv = document.createElement('div'); dividerDiv.className = 'chat-divider'; dividerDiv.innerHTML = `
上次聊到这里
`; messagesContainer.appendChild(dividerDiv); // 添加欢迎消息 appendMessage(VG.welcome_str, false, 'welcome'); scrollToBottom(); } // 给输入框添加回车发送功能 document.getElementById('chatInput').addEventListener('keypress', function(e) { if (e.key === 'Enter') { sendMessage(1, ''); } });