/**
* 首页悬浮智能客服(流式输出、会话保持、空闲超时、新对话)
*/
(function (global) {
'use strict';
var SNAPSHOT_KEY = 'cs_chat_snapshot_v1';
var CS_CSS_VER = '4.4';
global.__CS_CHAT_BUILD = '4.4';
var _csToolsLoading = null;
var _idleTimer = null;
var _currentCfg = null;
/** 动态加载客服样式(避免旧版 base.html 未包含新 CSS 时按钮无样式) */
function ensureCsChatStyles() {
if (document.getElementById('cs-chat-stylesheet')) return;
var link = document.createElement('link');
link.id = 'cs-chat-stylesheet';
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = '/static/css/customer_service_chat.css?v=' + CS_CSS_VER;
document.head.appendChild(link);
}
function boot() {
return global.__CS_CHAT_BOOT || {};
}
function escapeChatHtml(text) {
if (!text) return '';
var d = document.createElement('div');
d.textContent = text;
return d.innerHTML;
}
function formatWelcomeHtml(text) {
return escapeChatHtml(text || '').replace(/\n/g, '
');
}
function getIdleMinutes(cfg) {
var n = parseInt((cfg && cfg.idle_timeout_minutes) || 4, 10);
if (isNaN(n) || n < 3) return 4;
return Math.min(60, n);
}
function touchActivity() {
sessionStorage.setItem('cs_last_activity', String(Date.now()));
}
function isIdleExpired(idleMinutes) {
var ts = parseInt(sessionStorage.getItem('cs_last_activity') || '0', 10);
if (!ts) return false;
return (Date.now() - ts) > idleMinutes * 60 * 1000;
}
function clearConversationState() {
sessionStorage.removeItem('chat_session_id');
sessionStorage.removeItem('dify_conversation_id');
sessionStorage.removeItem('cs_last_activity');
sessionStorage.removeItem(SNAPSHOT_KEY);
}
global.clearCsConversationState = clearConversationState;
function loadLocalSnapshot() {
try {
var raw = sessionStorage.getItem(SNAPSHOT_KEY);
if (!raw) return null;
return JSON.parse(raw);
} catch (e) {
return null;
}
}
function collectMessagesFromDom() {
var chatBody = document.getElementById('ai-chat-body');
if (!chatBody) return [];
var msgs = [];
chatBody.querySelectorAll('.ai-chat-message').forEach(function (el) {
if (el.classList.contains('ai-typing')) return;
var textEl = el.querySelector('.cs-msg-text');
if (!textEl) return;
var content = (textEl.textContent || '').trim();
if (!content) return;
if (el.classList.contains('user-message')) {
msgs.push({ message_type: 'user', content: content });
} else if (el.classList.contains('ai-message')) {
msgs.push({ message_type: 'ai', content: content });
}
});
return msgs;
}
function saveLocalSnapshot() {
var msgs = collectMessagesFromDom();
if (!msgs.length) return;
try {
sessionStorage.setItem(SNAPSHOT_KEY, JSON.stringify({
session_id: global.getChatSessionId(),
conversation_id: global.getDifyConversationId(),
messages: msgs,
saved_at: Date.now()
}));
} catch (e) { /* quota */ }
}
global.saveLocalSnapshot = saveLocalSnapshot;
global.touchCsActivity = touchActivity;
function getUserAvatarInner() {
var b = boot();
var cfg = global._csPublicConfig || {};
var url = b.userAvatar || cfg.user_avatar_url || '';
var initial = b.userInitial || cfg.user_initial || '访';
if (url) {
return '
' +
'' + escapeChatHtml(initial) + '';
}
return '' + escapeChatHtml(initial) + '';
}
function getAiAvatarInner() {
return '';
}
global.getChatSessionId = function () {
var sessionId = sessionStorage.getItem('chat_session_id');
if (!sessionId) {
sessionId = 'chat_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
sessionStorage.setItem('chat_session_id', sessionId);
touchActivity();
}
return sessionId;
};
global.getDifyConversationId = function () {
return sessionStorage.getItem('dify_conversation_id') || '';
};
global.setDifyConversationId = function (id) {
if (id) sessionStorage.setItem('dify_conversation_id', id);
else sessionStorage.removeItem('dify_conversation_id');
};
function clearIdleTimer() {
if (_idleTimer) {
clearTimeout(_idleTimer);
_idleTimer = null;
}
}
function scheduleIdleTimer(cfg) {
clearIdleTimer();
if (!document.getElementById('ai-chat-body')) return;
var idleMin = getIdleMinutes(cfg || _currentCfg);
var ts = parseInt(sessionStorage.getItem('cs_last_activity') || '0', 10);
if (!ts) return;
var remain = idleMin * 60 * 1000 - (Date.now() - ts);
if (remain <= 0) {
global.startNewCsConversation({ reason: 'idle' });
return;
}
_idleTimer = setTimeout(function () {
global.startNewCsConversation({ reason: 'idle' });
}, remain);
}
global.appendCsSuggestions = function (questions) {
if (!questions || !questions.length) return;
var chatBody = document.getElementById('ai-chat-body');
if (!chatBody) return;
var old = document.getElementById('ai-chat-suggestions');
if (old) old.remove();
var box = document.createElement('div');
box.id = 'ai-chat-suggestions';
box.className = 'ai-chat-suggestions';
questions.forEach(function (q) {
var btn = document.createElement('button');
btn.type = 'button';
btn.className = 'ai-chat-suggestion-btn';
btn.textContent = q;
btn.onclick = function () {
var inp = document.getElementById('ai-chat-input');
if (inp) inp.value = q;
global.sendAIMessage();
};
box.appendChild(btn);
});
chatBody.appendChild(box);
chatBody.scrollTop = chatBody.scrollHeight;
};
function appendUserMessage(text) {
var chatBody = document.getElementById('ai-chat-body');
var el = document.createElement('div');
el.className = 'ai-chat-message user-message';
el.innerHTML =
'
' + escapeChatHtml(text) + '
' +
'' + getUserAvatarInner() + '
';
chatBody.appendChild(el);
return el;
}
global.appendUserMessage = appendUserMessage;
function appendUserMessageRich(text, imageUrl) {
var chatBody = document.getElementById('ai-chat-body');
var imgHtml = imageUrl
? ''
: '';
var el = document.createElement('div');
el.className = 'ai-chat-message user-message';
el.innerHTML =
'' + escapeChatHtml(text) + '
' + imgHtml + '
' +
'' + getUserAvatarInner() + '
';
chatBody.appendChild(el);
return el;
}
function appendAiMessage(text) {
var chatBody = document.getElementById('ai-chat-body');
var el = document.createElement('div');
el.className = 'ai-chat-message ai-message';
el.innerHTML =
'' + getAiAvatarInner() + '
' +
'' + formatWelcomeHtml(text) + '
';
chatBody.appendChild(el);
return el;
}
global.appendAiMessage = appendAiMessage;
function createAiMessageBubble() {
var chatBody = document.getElementById('ai-chat-body');
var el = document.createElement('div');
el.className = 'ai-chat-message ai-message';
el.innerHTML =
'' + getAiAvatarInner() + '
' +
'';
chatBody.appendChild(el);
return el.querySelector('.cs-msg-text');
}
function showTyping() {
var chatBody = document.getElementById('ai-chat-body');
var el = document.createElement('div');
el.className = 'ai-chat-message ai-message ai-typing';
el.id = 'ai-typing';
el.innerHTML =
'' + getAiAvatarInner() + '
' +
'' +
'' +
'
';
chatBody.appendChild(el);
chatBody.scrollTop = chatBody.scrollHeight;
}
function removeTyping() {
var t = document.getElementById('ai-typing');
if (t) t.remove();
}
function renderWelcomeOnly(cfg) {
var chatBody = document.getElementById('ai-chat-body');
if (!chatBody) return;
chatBody.innerHTML = '';
var welcome = cfg.welcome_message || '您好!我是智能客服助手,有什么可以帮助您的吗?';
appendAiMessage(welcome);
global.appendCsSuggestions(cfg.suggested_questions || []);
}
function renderHistoryMessages(messages) {
var chatBody = document.getElementById('ai-chat-body');
if (!chatBody) return;
chatBody.innerHTML = '';
(messages || []).forEach(function (m) {
var t = (m.message_type || '').toLowerCase();
var c = m.content || '';
if (!c) return;
if (t === 'user') appendUserMessage(c);
else appendAiMessage(c);
});
chatBody.scrollTop = chatBody.scrollHeight;
}
function fetchChatHistory(sessionId) {
return fetch('/api/ai/customer-service/history?session_id=' + encodeURIComponent(sessionId))
.then(function (r) {
if (!r.ok) return null;
return r.json();
})
.then(function (res) {
if (res && res.success && res.data) return res.data;
return null;
})
.catch(function () { return null; });
}
function resolveRestoreData(cfg, sessionId) {
var idleMin = getIdleMinutes(cfg);
var localSnap = loadLocalSnapshot();
var snapFresh = localSnap && localSnap.session_id === sessionId && localSnap.saved_at &&
(Date.now() - localSnap.saved_at) < idleMin * 60 * 1000;
return fetchChatHistory(sessionId).then(function (hist) {
if (!hist) hist = { messages: [], conversation_id: '', expired: false };
var serverExpired = !!hist.expired;
var clientIdle = isIdleExpired(idleMin);
if ((serverExpired || clientIdle) && snapFresh && localSnap.messages && localSnap.messages.length) {
hist = {
messages: localSnap.messages,
conversation_id: localSnap.conversation_id || hist.conversation_id || '',
expired: false
};
} else if (serverExpired || clientIdle) {
clearConversationState();
sessionId = global.getChatSessionId();
touchActivity();
return { messages: [], conversation_id: '', expired: false };
}
if ((!hist.messages || !hist.messages.length) && snapFresh && localSnap.messages.length) {
hist = {
messages: localSnap.messages,
conversation_id: localSnap.conversation_id || hist.conversation_id || global.getDifyConversationId(),
expired: false
};
}
var conv = hist.conversation_id || (localSnap && localSnap.session_id === sessionId ? localSnap.conversation_id : '') || '';
if (conv) global.setDifyConversationId(conv);
else if (localSnap && localSnap.session_id === sessionId && localSnap.conversation_id) {
global.setDifyConversationId(localSnap.conversation_id);
}
return hist;
});
}
global.startNewCsConversation = function (opts) {
opts = opts || {};
var cfg = _currentCfg || global._csPublicConfig || {};
clearConversationState();
clearIdleTimer();
global.getChatSessionId();
touchActivity();
var chatBody = document.getElementById('ai-chat-body');
if (chatBody) {
renderWelcomeOnly(cfg);
if (opts.reason === 'idle') {
var idleMin = getIdleMinutes(cfg);
appendAiMessage('已超过 ' + idleMin + ' 分钟无新消息,已为您开启新对话。');
}
saveLocalSnapshot();
var inp = document.getElementById('ai-chat-input');
if (inp) inp.focus();
}
scheduleIdleTimer(cfg);
};
global._showAIChatWindow = function (cfg, restore) {
ensureCsChatStyles();
cfg = cfg || {};
_currentCfg = cfg;
restore = restore || { messages: [], conversation_id: '', expired: false };
if (restore.conversation_id) {
global.setDifyConversationId(restore.conversation_id);
}
var title = cfg.app_title || '慧研 · 智能客服';
var idleMin = getIdleMinutes(cfg);
if (document.getElementById('ai-chat-overlay')) {
global.closeAIChat();
}
var overlay = document.createElement('div');
overlay.className = 'ai-chat-overlay';
overlay.id = 'ai-chat-overlay';
overlay.onclick = function (e) {
if (e.target === overlay) global.closeAIChat();
};
var chatWindow = document.createElement('div');
chatWindow.className = 'ai-chat-window';
chatWindow.innerHTML =
'' +
'' +
'' +
'';
document.body.appendChild(overlay);
document.body.appendChild(chatWindow);
var msgs = restore.messages || [];
var hasChat = msgs.some(function (m) { return (m.message_type || '').toLowerCase() === 'user'; });
if (hasChat) {
renderHistoryMessages(msgs);
} else {
renderWelcomeOnly(cfg);
}
chatWindow.querySelector('.ai-chat-close').onclick = function () { global.closeAIChat(); };
chatWindow.querySelector('.ai-chat-new-btn').onclick = function () {
if (window.confirm('确定开启新对话?当前记录将不再延续到下一轮。')) {
global.startNewCsConversation({});
}
};
var inp = document.getElementById('ai-chat-input');
if (inp) {
inp.onkeypress = function (e) {
if (e.key === 'Enter') global.sendAIMessage();
};
inp.focus();
}
chatWindow.querySelector('.ai-chat-send').onclick = function () { global.sendAIMessage(); };
mountCsChatToolbar(chatWindow, cfg);
saveLocalSnapshot();
touchActivity();
scheduleIdleTimer(cfg);
};
function mountCsChatToolbar(chatWindow, cfg) {
function runInit() {
if (global.initCsChatToolbar) {
global.initCsChatToolbar(chatWindow);
return;
}
bindCsToolbarFallback(chatWindow);
}
if (global.initCsChatToolbar) {
runInit();
return;
}
if (!_csToolsLoading) {
_csToolsLoading = new Promise(function (resolve) {
var s = document.createElement('script');
s.src = '/static/js/customer_service_chat_tools.js?v=' + CS_CSS_VER;
s.async = false;
s.onload = function () { resolve(true); };
s.onerror = function () { resolve(false); };
document.head.appendChild(s);
});
}
_csToolsLoading.then(function () { runInit(); });
}
function bindCsToolbarFallback(chatWindow) {
if (!chatWindow || chatWindow.getAttribute('data-cs-toolbar-bound') === '1') return;
chatWindow.setAttribute('data-cs-toolbar-bound', '1');
function tip(msg) {
var el = chatWindow.querySelector('#cs-tool-toast');
if (!el) return;
el.textContent = msg;
el.classList.add('show');
setTimeout(function () { el.classList.remove('show'); }, 2600);
}
chatWindow.addEventListener('click', function (e) {
var t = e.target;
if (t.closest('#cs-btn-image')) {
e.preventDefault();
var imgIn = chatWindow.querySelector('#cs-image-input');
if (imgIn) imgIn.click();
else tip('图片组件未加载,请 Ctrl+F5 强刷');
} else if (t.closest('#cs-btn-file')) {
e.preventDefault();
var fIn = chatWindow.querySelector('#cs-file-input');
if (fIn) fIn.click();
else tip('文件组件未加载,请 Ctrl+F5 强刷');
} else if (t.closest('#cs-btn-order')) {
e.preventDefault();
var panel = chatWindow.querySelector('#cs-order-panel');
if (panel) panel.classList.toggle('open');
} else if (t.closest('#cs-btn-voice')) {
e.preventDefault();
tip('语音需加载完整脚本,请 Ctrl+F5 强刷');
}
});
tip('工具栏备用模式:请强刷页面以加载完整功能');
}
global.openAIChat = function () {
ensureCsChatStyles();
var cfg = { welcome_message: '您好!我是智能客服助手,有什么可以帮助您的吗?', idle_timeout_minutes: 4 };
fetch('/api/ai/customer-service/config')
.then(function (r) { return r.json(); })
.then(function (res) {
if (res.success && res.data) {
global._csPublicConfig = res.data;
cfg = res.data;
}
var sessionId = global.getChatSessionId();
var capsLoad = Promise.resolve();
if (!cfg.capabilities) {
capsLoad = fetch('/api/ai/customer-service/capabilities', { cache: 'no-store' })
.then(function (r2) { return r2.ok ? r2.json() : null; })
.then(function (cres) {
if (cres && cres.success && cres.data) {
cfg.capabilities = cres.data;
if (global._csPublicConfig) global._csPublicConfig.capabilities = cres.data;
}
});
}
return capsLoad.then(function () { return resolveRestoreData(cfg, sessionId); });
})
.then(function (hist) {
global._showAIChatWindow(cfg, hist);
})
.catch(function () {
var sessionId = global.getChatSessionId();
var snap = loadLocalSnapshot();
var hist = { messages: [], conversation_id: '', expired: false };
if (snap && snap.session_id === sessionId && snap.messages && snap.messages.length) {
hist = { messages: snap.messages, conversation_id: snap.conversation_id || '', expired: false };
}
global._showAIChatWindow(cfg, hist);
});
};
global.closeAIChat = function () {
saveLocalSnapshot();
touchActivity();
clearIdleTimer();
var overlay = document.getElementById('ai-chat-overlay');
var chatWindow = document.querySelector('.ai-chat-window');
if (overlay) overlay.remove();
if (chatWindow) chatWindow.remove();
};
global.handleAIChatKeyPress = function (event) {
if (event.key === 'Enter') global.sendAIMessage();
};
global.sendAIMessage = function (opts) {
opts = opts || {};
var input = document.getElementById('ai-chat-input');
var message = (opts.message != null ? opts.message : (input ? input.value.trim() : ''));
var files = opts.files || [];
if (!message && !files.length) return;
if (input && opts.message == null) input.value = '';
var chatBody = document.getElementById('ai-chat-body');
var displayText = opts.displayText || message;
if (opts.imageUrl) appendUserMessageRich(displayText, opts.imageUrl);
else appendUserMessage(displayText);
chatBody.scrollTop = chatBody.scrollHeight;
saveLocalSnapshot();
touchActivity();
scheduleIdleTimer(_currentCfg);
var sugBox = document.getElementById('ai-chat-suggestions');
if (sugBox) sugBox.remove();
showTyping();
var sessionId = global.getChatSessionId();
var convId = global.getDifyConversationId();
fetch('/api/ai/customer-service/chat/stream', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query: message,
session_id: sessionId,
conversation_id: convId || undefined,
files: files
})
}).then(function (response) {
if (!response.ok) {
return response.json().then(function (d) {
throw new Error(d.message || '请求失败');
});
}
var reader = response.body.getReader();
var decoder = new TextDecoder('utf-8');
var buffer = '';
var textEl = null;
var gotFirstChunk = false;
function pump() {
return reader.read().then(function (result) {
if (result.done) return;
buffer += decoder.decode(result.value, { stream: true });
var parts = buffer.split('\n\n');
buffer = parts.pop() || '';
parts.forEach(function (block) {
block.split('\n').forEach(function (line) {
line = line.trim();
if (!line.startsWith('data:')) return;
var jsonStr = line.slice(5).trim();
if (!jsonStr) return;
try {
var ev = JSON.parse(jsonStr);
if (ev.type === 'chunk' && ev.text) {
if (!gotFirstChunk) {
removeTyping();
textEl = createAiMessageBubble();
gotFirstChunk = true;
}
if (textEl) {
textEl.textContent += ev.text;
chatBody.scrollTop = chatBody.scrollHeight;
}
} else if (ev.type === 'done') {
if (!gotFirstChunk) {
removeTyping();
textEl = createAiMessageBubble();
textEl.textContent = ev.answer || '';
gotFirstChunk = true;
} else if (textEl && ev.answer) {
textEl.textContent = ev.answer;
}
if (ev.conversation_id) global.setDifyConversationId(ev.conversation_id);
saveLocalSnapshot();
touchActivity();
scheduleIdleTimer(_currentCfg);
if (ev.suggested_questions && ev.suggested_questions.length) {
global.appendCsSuggestions(ev.suggested_questions);
}
} else if (ev.type === 'error') {
removeTyping();
textEl = createAiMessageBubble();
textEl.textContent = ev.message || '出错了';
gotFirstChunk = true;
saveLocalSnapshot();
touchActivity();
scheduleIdleTimer(_currentCfg);
}
} catch (e) { /* ignore parse */ }
});
});
return pump();
});
}
return pump();
}).catch(function (err) {
removeTyping();
var textEl = createAiMessageBubble();
textEl.textContent = err.message || '网络异常,请稍后重试';
chatBody.scrollTop = chatBody.scrollHeight;
saveLocalSnapshot();
touchActivity();
scheduleIdleTimer(_currentCfg);
});
};
})(window);