/** * 客服工具栏:语音转文字、图片、文件、订单查询 */ (function (global) { 'use strict'; var _speechRec = null; var _listening = false; var MAX_MB = 15; function toastTip(msg) { var el = document.getElementById('cs-tool-toast'); if (!el) return; el.textContent = msg; el.classList.add('show'); clearTimeout(el._hideTimer); el._hideTimer = setTimeout(function () { el.classList.remove('show'); }, 2800); } function isImageFile(file) { if (!file) return false; if ((file.type || '').indexOf('image/') === 0) return true; var n = (file.name || '').toLowerCase(); return /\.(png|jpe?g|gif|webp|bmp|svg)$/.test(n); } function validateSize(file) { if (file.size > MAX_MB * 1024 * 1024) { toastTip('文件不能超过 ' + MAX_MB + 'MB'); return false; } return true; } var DEFAULT_CAP_HINT = '图片识图需在 Dify 开启视觉并选用 Vision 模型;若已开启仍提示,请重启 python run.py 后 Ctrl+F5。'; function getCaps() { var cfg = global._csPublicConfig || {}; return cfg.capabilities || null; } function showCapBanner(chatWindow, text, show) { var banner = chatWindow && chatWindow.querySelector('#cs-cap-banner'); if (!banner) return; if (show === false) { banner.hidden = true; return; } banner.textContent = text || DEFAULT_CAP_HINT; banner.hidden = false; } function applyCapabilities(chatWindow) { if (!chatWindow) return; var caps = getCaps(); var img = (caps && caps.image) || {}; var dify = (caps && caps.dify) || {}; if (caps && img.dify_vision_ready) { showCapBanner(chatWindow, '', false); } else if (caps) { var hint = img.hint || dify.setup_hint || DEFAULT_CAP_HINT; showCapBanner(chatWindow, '提示:' + hint, true); } else { showCapBanner(chatWindow, '', false); } if (!caps) return; var imageBtn = chatWindow.querySelector('#cs-btn-image'); var fileBtn = chatWindow.querySelector('#cs-btn-file'); if (imageBtn && img.hint) imageBtn.title = '发送图片 — ' + img.hint; var file = caps.file || {}; if (fileBtn && file.hint) fileBtn.title = '上传文档 — ' + file.hint; var orderBtn = chatWindow.querySelector('#cs-btn-order'); var order = caps.order || {}; if (orderBtn && order.hint) orderBtn.title = '订单查询 — ' + order.hint; } function refreshCapabilities(chatWindow) { var caps = getCaps(); if (caps) { applyCapabilities(chatWindow); return; } showCapBanner(chatWindow, '', false); fetch('/api/ai/customer-service/capabilities', { cache: 'no-store' }) .then(function (r) { if (r.status === 404) { return fetch('/api/ai/customer-service/config', { cache: 'no-store' }) .then(function (rc) { return rc.ok ? rc.json() : null; }); } return r.json(); }) .then(function (res) { if (!res || !res.success) return; var data = res.data || {}; if (data.capabilities) { global._csPublicConfig = global._csPublicConfig || {}; global._csPublicConfig.capabilities = data.capabilities; applyCapabilities(chatWindow); } }) .catch(function () { showCapBanner(chatWindow, '', false); }); } function csToast(msg, chatWindow) { var el = (chatWindow && chatWindow.querySelector('#cs-tool-toast')) || document.getElementById('cs-tool-toast'); if (!el) return; el.textContent = msg; el.classList.add('show'); clearTimeout(el._hideTimer); el._hideTimer = setTimeout(function () { el.classList.remove('show'); }, 2800); } global.initCsChatToolbar = function (chatWindow) { if (!chatWindow) return; if (chatWindow.getAttribute('data-cs-toolbar-bound') === '1') return; chatWindow.setAttribute('data-cs-toolbar-bound', '1'); applyCapabilities(chatWindow); refreshCapabilities(chatWindow); var voiceBtn = chatWindow.querySelector('#cs-btn-voice'); var imageBtn = chatWindow.querySelector('#cs-btn-image'); var fileBtn = chatWindow.querySelector('#cs-btn-file'); var imageInput = chatWindow.querySelector('#cs-image-input'); var fileInput = chatWindow.querySelector('#cs-file-input'); var orderBtn = chatWindow.querySelector('#cs-btn-order'); var orderPanel = chatWindow.querySelector('#cs-order-panel'); var orderInput = chatWindow.querySelector('#cs-order-input'); var orderSubmit = chatWindow.querySelector('#cs-order-submit'); var orderClose = chatWindow.querySelector('#cs-order-close'); var textInput = document.getElementById('ai-chat-input'); function bindBtn(el, handler) { if (!el) return; el.addEventListener('click', function (e) { e.preventDefault(); e.stopPropagation(); handler(e); }); } if (voiceBtn) { bindBtn(voiceBtn, function () { toggleVoiceInput(voiceBtn); }); } if (imageBtn && imageInput) { bindBtn(imageBtn, function () { imageInput.click(); }); imageInput.onchange = function () { if (!imageInput.files || !imageInput.files.length) return; var f = imageInput.files[0]; if (!isImageFile(f)) { toastTip('请选择图片文件'); imageInput.value = ''; return; } uploadAndSend(f, imageInput, 'image'); }; } if (fileBtn && fileInput) { bindBtn(fileBtn, function () { fileInput.click(); }); fileInput.onchange = function () { if (!fileInput.files || !fileInput.files.length) return; var f = fileInput.files[0]; if (isImageFile(f)) { toastTip('图片请使用「图片」按钮上传'); fileInput.value = ''; return; } uploadAndSend(f, fileInput, 'file'); }; } if (orderBtn && orderPanel) { bindBtn(orderBtn, function () { var open = orderPanel.classList.toggle('open'); orderBtn.classList.toggle('active', open); if (open && orderInput) orderInput.focus(); }); } if (orderClose && orderPanel) { bindBtn(orderClose, function () { orderPanel.classList.remove('open'); if (orderBtn) orderBtn.classList.remove('active'); }); } if (orderSubmit) { bindBtn(orderSubmit, function () { runOrderQuery(orderInput, orderPanel); }); } if (orderInput) { orderInput.onkeypress = function (e) { if (e.key === 'Enter') runOrderQuery(orderInput, orderPanel); }; } if (textInput) { textInput.addEventListener('paste', function (e) { var items = e.clipboardData && e.clipboardData.items; if (!items) return; for (var i = 0; i < items.length; i++) { if (items[i].type.indexOf('image') !== -1) { var blob = items[i].getAsFile(); if (blob) { e.preventDefault(); var name = '粘贴图片_' + Date.now() + '.png'; var file = new File([blob], name, { type: blob.type || 'image/png' }); uploadAndSend(file, null, 'image'); } break; } } }); } }; function toggleVoiceInput(btn) { var SpeechRecognition = global.SpeechRecognition || global.webkitSpeechRecognition; if (!SpeechRecognition) { toastTip('请使用 Chrome / Edge 浏览器以支持语音输入'); return; } var inp = document.getElementById('ai-chat-input'); if (!inp) return; if (_listening && _speechRec) { _speechRec.stop(); return; } _speechRec = new SpeechRecognition(); _speechRec.lang = 'zh-CN'; _speechRec.interimResults = true; _speechRec.continuous = true; _speechRec.maxAlternatives = 1; var finalText = ''; _speechRec.onstart = function () { _listening = true; btn.classList.add('active'); toastTip('正在聆听… 再次点击结束'); }; _speechRec.onend = function () { _listening = false; btn.classList.remove('active'); if (finalText.trim()) { inp.value = (inp.value ? inp.value + ' ' : '') + finalText.trim(); inp.focus(); toastTip('语音已写入输入框'); } }; _speechRec.onerror = function (ev) { _listening = false; btn.classList.remove('active'); if (ev.error === 'not-allowed') { toastTip('请允许麦克风权限'); } else if (ev.error !== 'aborted') { toastTip('语音识别失败:' + (ev.error || '未知')); } }; _speechRec.onresult = function (ev) { var interim = ''; for (var i = ev.resultIndex; i < ev.results.length; i++) { if (ev.results[i].isFinal) { finalText += ev.results[i][0].transcript; } else { interim += ev.results[i][0].transcript; } } inp.value = (finalText + interim).trim(); }; try { _speechRec.start(); } catch (e) { toastTip('无法启动麦克风'); } } function uploadAndSend(file, fileInput, kind) { if (!file || !validateSize(file)) { if (fileInput) fileInput.value = ''; return; } var sessionId = global.getChatSessionId(); var fd = new FormData(); fd.append('file', file); fd.append('session_id', sessionId); fd.append('kind', kind); toastTip(kind === 'image' ? '图片上传中…' : '文件上传中…'); fetch('/api/ai/customer-service/upload', { method: 'POST', body: fd }) .then(function (r) { if (r.status === 404) throw new Error('upload_api_missing'); return r.json(); }) .then(function (res) { if (fileInput) fileInput.value = ''; if (!res.success) throw new Error(res.message || '上传失败'); var d = res.data || {}; var name = d.name || file.name; var isImg = kind === 'image' || (d.file_type === 'image'); var label = isImg ? '[图片] ' + name : '[文件] ' + name; var prompt = isImg ? '我发送了一张图片「' + name + '」,请帮我识别/分析图片内容。' : '我上传了文件「' + name + '」,请根据文件内容回答我的问题。'; var difyFiles = []; if (d.dify_uploaded && d.file_id && String(d.file_id).indexOf('local_') !== 0) { difyFiles.push({ type: d.file_type || (isImg ? 'image' : 'document'), upload_file_id: d.file_id }); } else if (d.dify_message) { prompt += '(注:' + d.dify_message + ',当前仅本地预览)'; } if (isImg && d.dify_vision_warning) { toastTip(d.dify_vision_warning); } else if (isImg) { var caps = getCaps(); if (caps && caps.image && !caps.image.dify_vision_ready) { toastTip(caps.image.hint || 'Dify 未开启图片视觉'); } } if (!global.sendAIMessage) { toastTip('发送失败:客服脚本未加载'); return; } global.sendAIMessage({ message: prompt, displayText: label, imageUrl: isImg && d.local_url ? d.local_url : '', files: difyFiles }); toastTip(isImg ? '图片已发送' : '文件已发送'); }) .catch(function (err) { if (fileInput) fileInput.value = ''; var msg = err.message === 'upload_api_missing' ? '上传接口不可用,请在 IntelliIARPlatform-v1 目录执行 python run.py 后 Ctrl+F5' : (err.message || '上传失败'); toastTip(msg); }); } function runOrderQuery(orderInput, orderPanel) { var no = orderInput ? orderInput.value.trim() : ''; if (!no) { toastTip('请输入订单号'); return; } var sessionId = global.getChatSessionId ? global.getChatSessionId() : ''; toastTip('正在查询订单…'); fetch('/api/ai/customer-service/order-query', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ order_no: no, session_id: sessionId }) }) .then(function (r) { if (r.status === 404) throw new Error('order_api_missing'); return r.json().then(function (d) { return { ok: r.ok, d: d }; }); }) .then(function (pack) { if (orderPanel) orderPanel.classList.remove('open'); var ob = document.getElementById('cs-btn-order'); if (ob) ob.classList.remove('active'); if (orderInput) orderInput.value = ''; var chatBody = document.getElementById('ai-chat-body'); if (!chatBody) return; if (global.appendUserMessage) { global.appendUserMessage('查询订单:' + no); } if (pack.ok && pack.d.success && pack.d.data) { if (global.appendAiMessage) { global.appendAiMessage(pack.d.data.summary || '查询完成'); } toastTip('查询成功'); } else { var msg = (pack.d && pack.d.message) || '未找到该订单'; if (global.appendAiMessage) global.appendAiMessage(msg); toastTip(msg); } if (global.saveLocalSnapshot) global.saveLocalSnapshot(); if (global.touchCsActivity) global.touchCsActivity(); chatBody.scrollTop = chatBody.scrollHeight; }) .catch(function (err) { toastTip(err.message === 'order_api_missing' ? '订单接口不可用,请重启 python run.py 后刷新页面' : '查询失败,请检查网络'); }); } })(window);