index.vue 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  1. <template>
  2. <view class="container">
  3. <!-- 聊天记录区域 -->
  4. <scroll-view class="chat-container" scroll-y :scroll-top="scrollTop" :scroll-with-animation="true"
  5. @scroll="onScroll" :style="{ height: `calc(100vh - ${inputHeight}px)`,marginTop: '0'}">
  6. <view class="chat-list">
  7. <view v-for="(message, index) in chatMessages" :key="index" class="message-item" :class="{ 'message-ai': message.sender === 'ai', 'message-user': message.sender === 'user' }">
  8. <!-- AI消息 -->
  9. <template v-if="message.sender === 'ai'">
  10. <view class="avatar-container">
  11. <image class="avatar" src="/static/icons/ai.png" mode="aspectFill"></image>
  12. </view>
  13. <view class="message-content">
  14. <view class="message-bubble ai-bubble"
  15. :class="{'typing': message.isTyping, 'welcome': message.isWelcome || index === 0}">
  16. <!-- 正在输入指示器 -->
  17. <view v-if="message.isTyping" class="typing-indicator">
  18. <view class="typing-dot"></view>
  19. <view class="typing-dot"></view>
  20. <view class="typing-dot"></view>
  21. </view>
  22. <!-- 消息内容 -->
  23. <text v-else-if="message.content" class="message-text"
  24. :class="{'highlight': containsKeywords(message.content)}">
  25. {{ message.content }}
  26. </text>
  27. </view>
  28. <!-- 操作按钮区域(仅最后一条AI消息显示) -->
  29. <view v-if="index === chatMessages.length - 1 && message.sender === 'ai' && !message.isTyping" class="message-actions">
  30. <view class="action-button" @click="regenerateMessage" hover-class="action-button-hover">
  31. <text class="action-icon">🔄</text>
  32. <text class="action-text">重新生成</text>
  33. </view>
  34. </view>
  35. <text class="message-time">{{ message.time }}</text>
  36. </view>
  37. </template>
  38. <!-- 用户消息 -->
  39. <template v-else>
  40. <view class="message-content user-content">
  41. <text class="message-time">{{ message.time }}</text>
  42. <view class="message-bubble user-bubble">
  43. <text class="message-text">{{ message.content }}</text>
  44. </view>
  45. </view>
  46. <view class="avatar-container">
  47. <image class="avatar" src="/static/images/user-avatar.svg" mode="aspectFill"></image>
  48. </view>
  49. </template>
  50. </view>
  51. </view>
  52. </scroll-view>
  53. <!-- 底部输入区 -->
  54. <view class="input-container" :style="{ paddingBottom: `${isIOS ? safeAreaBottom : 20}rpx` }">
  55. <!-- 问题建议区 -->
  56. <scroll-view v-if="chatMessages.length <= 3 && !inputMessage && !isProcessing" class="suggested-questions" scroll-x>
  57. <view v-for="(question, index) in suggestedQuestions" :key="index" class="question-chip"
  58. @click="useQuestion(question)">
  59. <text>{{ question }}</text>
  60. </view>
  61. </scroll-view>
  62. <view class="input-wrapper">
  63. <textarea class="message-input" v-model="inputMessage" placeholder="请输入您的问题..." :disabled="isProcessing"
  64. auto-height :maxlength="300" :style="{ maxHeight: '120rpx' }" @focus="onInputFocus"
  65. @confirm="submitQuestion" />
  66. <!-- 中止按钮(流式输出时显示) -->
  67. <view v-if="isProcessing" class="stop-button" @click="stopStreaming" hover-class="button-hover">
  68. <text class="stop-icon">⏹</text>
  69. </view>
  70. <!-- 发送按钮 -->
  71. <view v-else class="send-button" :class="{ 'disabled': !inputMessage.trim() }"
  72. @click="submitQuestion" hover-class="button-hover">
  73. <image class="send-icon-image"
  74. :src="inputMessage.trim() ? '/static/icons/chat.png' : '/static/icons/chat_off.png'"
  75. mode="aspectFit"></image>
  76. </view>
  77. </view>
  78. </view>
  79. <!-- renderjs 模块容器(用于 H5/App 端 SSE 流式连接) -->
  80. <view
  81. :change:prop="renderModule.onDataChange"
  82. :prop="renderjsData"
  83. :onStreamData="onStreamData"
  84. class="renderjs-container"
  85. ></view>
  86. </view>
  87. </template>
  88. <script setup>
  89. import { ref, reactive, computed, onMounted, onBeforeUnmount, nextTick, getCurrentInstance } from 'vue'
  90. import api from "@/config/api.js";
  91. import storage from "@/utils/storage.js";
  92. import { chatStreamSuggested } from "@/api/services/chart.js";
  93. // 响应式数据
  94. const inputMessage = ref('') // 输入框消息
  95. // 初始化函数,用于获取初始时间
  96. const getInitialFormattedTime = () => {
  97. const date = new Date()
  98. const hours = date.getHours().toString().padStart(2, '0')
  99. const minutes = date.getMinutes().toString().padStart(2, '0')
  100. return `${hours}:${minutes}`
  101. }
  102. const chatMessages = ref([{
  103. sender: 'ai',
  104. content: '您好!我是农小禹,您的智能农业助手🌱 我可以帮您解答农业种植、病虫害防治、农产品管理等方面的问题。有什么可以帮助您的吗?',
  105. time: getInitialFormattedTime(),
  106. timestamp: Date.now(),
  107. isWelcome: true
  108. }])
  109. const scrollTop = ref(0)
  110. const inputHeight = ref(110)
  111. const isProcessing = ref(false)
  112. const currentTypingMessage = ref(null) // 当前正在输入的消息索引
  113. const lastUserQuestion = ref('') // 保存最后一个用户问题,用于重新生成
  114. const suggestedQuestions = ref([
  115. '水稻插秧后如何管理?',
  116. '果树夏季修剪技巧?',
  117. '如何防治蔬菜常见病虫害?',
  118. '农药使用注意事项?',
  119. '有机肥和化肥怎么搭配使用?'
  120. ])
  121. const statusBarHeight = ref(20)
  122. const safeAreaBottom = ref(34)
  123. const isIOS = ref(false)
  124. // renderjs 通信数据
  125. const renderjsData = ref({
  126. action: '', // start, stop
  127. url: '',
  128. data: {},
  129. timestamp: 0
  130. })
  131. // 消息队列和打字机效果
  132. const messageQueue = ref([])
  133. const isTypingEffect = ref(false)
  134. const typingTimer = ref(null)
  135. // Thinking 模式追踪
  136. const isInThinkingMode = ref(false)
  137. const sessionId = ref(null)
  138. const messageId = ref(null) // 消息ID,用于标识当前消息
  139. const thinkingBuffer = ref('') // 临时存储 Thinking 内容
  140. // 防抖函数引用
  141. let debouncedSubmitQuestion = null
  142. // uni-app 生命周期
  143. const onNavigationBarButtonTap = (e) => {
  144. console.log("导航栏按钮点击:", e);
  145. }
  146. // ========== renderjs 通信方法 ==========
  147. // renderjs 回调:接收流式数据
  148. const onStreamData = (data) => {
  149. console.log('=== Vue收到流式数据 ===', data);
  150. console.log('数据类型:', data.type);
  151. console.log('当前输入消息索引:', currentTypingMessage.value);
  152. if (data.type === 'thinking') {
  153. console.log('进入 Thinking 模式');
  154. // 第一个 thinking 类型,开启 Thinking 模式
  155. isInThinkingMode.value = true;
  156. thinkingBuffer.value = data.content;
  157. processThinkingContent();
  158. } else if (data.type === 'message') {
  159. console.log('收到消息内容:', data.content);
  160. // 判断是否在 Thinking 模式中
  161. if (isInThinkingMode.value) {
  162. console.log('仍在 Thinking 模式,累积内容');
  163. // 仍在 Thinking 区域内,累积内容
  164. thinkingBuffer.value += data.content;
  165. processThinkingContent();
  166. } else {
  167. console.log('普通消息,添加到队列');
  168. // 普通消息内容
  169. handleMessageData(data.content);
  170. }
  171. } else if (data.type === 'end') {
  172. // 流式结束
  173. console.log("流式结束,消息id:",data.id);
  174. finishStreaming(data.id);
  175. } else if (data.type === 'error') {
  176. // 错误处理
  177. console.error('流式错误:', data.error);
  178. handleStreamError(data.error);
  179. }
  180. }
  181. // 处理 Thinking 内容(跳过 Thinking,只处理后续内容)
  182. const processThinkingContent = () => {
  183. if (currentTypingMessage.value === null) return;
  184. // 检查是否包含 </details> 结束标签
  185. if (thinkingBuffer.value.includes('</details>')) {
  186. // Thinking 区域结束,提取 </details> 之后的内容
  187. isInThinkingMode.value = false;
  188. // 提取 </details> 后面的内容
  189. const detailsEndIndex = thinkingBuffer.value.indexOf('</details>');
  190. const contentAfterThinking = thinkingBuffer.value.substring(detailsEndIndex + '</details>'.length);
  191. // 如果有内容,添加到消息队列
  192. if (contentAfterThinking) {
  193. handleMessageData(contentAfterThinking);
  194. }
  195. // 清空缓冲区
  196. thinkingBuffer.value = '';
  197. }
  198. // 如果还在 Thinking 区域内,不做任何显示,继续累积
  199. }
  200. // 处理消息数据(添加到队列)
  201. const handleMessageData = (text) => {
  202. console.log('handleMessageData 被调用,文本长度:', text ? text.length : 0);
  203. if (!text) return;
  204. // 将文本按字符添加到队列
  205. for (let char of text) {
  206. messageQueue.value.push(char);
  207. }
  208. console.log('消息队列长度:', messageQueue.value.length);
  209. // 如果打字机效果未启动,则启动
  210. if (!isTypingEffect.value) {
  211. console.log('启动打字机效果');
  212. startTypingEffect();
  213. }
  214. }
  215. // 启动打字机效果
  216. const startTypingEffect = () => {
  217. console.log('startTypingEffect 被调用');
  218. console.log('isTypingEffect:', isTypingEffect.value);
  219. console.log('currentTypingMessage:', currentTypingMessage.value);
  220. if (isTypingEffect.value || currentTypingMessage.value === null) {
  221. console.log('打字机效果已在运行或没有当前消息,退出');
  222. return;
  223. }
  224. isTypingEffect.value = true;
  225. chatMessages.value[currentTypingMessage.value].isTyping = false;
  226. console.log('开始打字机效果,消息索引:', currentTypingMessage.value);
  227. const processQueue = () => {
  228. if (messageQueue.value.length > 0 && currentTypingMessage.value !== null) {
  229. // 每次取出一个字符
  230. const char = messageQueue.value.shift();
  231. const currentContent = chatMessages.value[currentTypingMessage.value].content || '';
  232. chatMessages.value[currentTypingMessage.value].content = currentContent + char;
  233. // 每20个字符滚动一次,优化性能
  234. if (currentContent.length % 20 === 0) {
  235. scrollToBottom();
  236. }
  237. // 继续处理队列
  238. typingTimer.value = setTimeout(processQueue, 10);
  239. } else if (messageQueue.value.length === 0) {
  240. // 队列为空,等待新数据
  241. typingTimer.value = setTimeout(processQueue, 50);
  242. }
  243. };
  244. processQueue();
  245. }
  246. // 停止打字机效果
  247. const stopTypingEffect = () => {
  248. isTypingEffect.value = false;
  249. if (typingTimer.value) {
  250. clearTimeout(typingTimer.value);
  251. typingTimer.value = null;
  252. }
  253. // 清空队列,将剩余内容一次性显示
  254. if (messageQueue.value.length > 0 && currentTypingMessage.value !== null) {
  255. const remainingText = messageQueue.value.join('');
  256. const currentContent = chatMessages.value[currentTypingMessage.value].content || '';
  257. chatMessages.value[currentTypingMessage.value].content = currentContent + remainingText;
  258. messageQueue.value = [];
  259. }
  260. }
  261. // 完成流式输出
  262. const finishStreaming = (id) => {
  263. console.log("消息id2:",id);
  264. stopTypingEffect();
  265. if (currentTypingMessage.value !== null) {
  266. chatMessages.value[currentTypingMessage.value].isTyping = false;
  267. currentTypingMessage.value = null;
  268. }
  269. // 重置 Thinking 模式状态
  270. isInThinkingMode.value = false;
  271. thinkingBuffer.value = '';
  272. isProcessing.value = false;
  273. scrollToBottom();
  274. // 获取下一轮建议问题
  275. // fetchSuggestedQuestions({user: sessionId.value, messageId: id});
  276. }
  277. // 处理流式错误
  278. const handleStreamError = (error) => {
  279. console.error('流式错误:', error);
  280. stopTypingEffect();
  281. // 移除正在输入的消息
  282. if (currentTypingMessage.value !== null) {
  283. chatMessages.value.splice(currentTypingMessage.value, 1);
  284. currentTypingMessage.value = null;
  285. }
  286. // 重置 Thinking 模式状态
  287. isInThinkingMode.value = false;
  288. thinkingBuffer.value = '';
  289. isProcessing.value = false;
  290. handleError({ message: error || '网络异常,请稍后重试' });
  291. }
  292. // ========== 用户交互方法 ==========
  293. // 发送消息
  294. const submitQuestion = () => {
  295. if (!storage.getHasLogin()) {
  296. uni.showModal({
  297. title: '提示',
  298. content: '您还未登录,请先登录',
  299. confirmText: '去登录',
  300. cancelText: '取消',
  301. success: function(res) {
  302. if (res.confirm) {
  303. uni.navigateTo({
  304. url: '/pages/login/index'
  305. });
  306. }
  307. },
  308. });
  309. return;
  310. }
  311. if (!inputMessage.value.trim() || isProcessing.value) return;
  312. const question = inputMessage.value.trim();
  313. lastUserQuestion.value = question; // 保存问题用于重新生成
  314. inputMessage.value = '';
  315. // 添加用户消息
  316. chatMessages.value.push({
  317. sender: 'user',
  318. content: question,
  319. time: getCurrentTime(),
  320. timestamp: Date.now()
  321. });
  322. // 添加 AI 正在输入的消息
  323. const typingMessageIndex = chatMessages.value.push({
  324. sender: 'ai',
  325. content: '',
  326. time: getCurrentTime(),
  327. timestamp: Date.now(),
  328. isTyping: true
  329. }) - 1;
  330. currentTypingMessage.value = typingMessageIndex;
  331. isProcessing.value = true;
  332. scrollToBottom();
  333. // 通过 renderjs 发起 SSE 请求
  334. startSSERequest(question);
  335. }
  336. // 启动 SSE 请求(通过 renderjs)
  337. const startSSERequest = (question) => {
  338. const url = api.serve + '/uniapp/dify/chat/stream';
  339. sessionId.value = Date.now().toString()
  340. const requestData = {
  341. query: question,
  342. user: 'user_' + sessionId.value
  343. };
  344. // 更新 renderjs 数据,触发 SSE 连接
  345. renderjsData.value = {
  346. action: 'start',
  347. url: url,
  348. data: requestData,
  349. token: storage.getAccessToken(),
  350. timestamp: Date.now()
  351. };
  352. }
  353. // 停止流式输出
  354. const stopStreaming = () => {
  355. console.log('用户中止流式输出');
  356. // 通知 renderjs 停止
  357. renderjsData.value = {
  358. action: 'stop',
  359. timestamp: Date.now()
  360. };
  361. // 立即停止打字机效果并完成
  362. finishStreaming();
  363. uni.showToast({
  364. title: '已中止',
  365. icon: 'none',
  366. duration: 1500
  367. });
  368. }
  369. // 重新生成回复
  370. const regenerateMessage = () => {
  371. if (!lastUserQuestion.value || isProcessing.value) return;
  372. // 删除最后一条 AI 消息
  373. if (chatMessages.value.length > 0 && chatMessages.value[chatMessages.value.length - 1].sender === 'ai') {
  374. chatMessages.value.pop();
  375. }
  376. // 添加新的正在输入消息
  377. const typingMessageIndex = chatMessages.value.push({
  378. sender: 'ai',
  379. content: '',
  380. time: getCurrentTime(),
  381. timestamp: Date.now(),
  382. isTyping: true
  383. }) - 1;
  384. currentTypingMessage.value = typingMessageIndex;
  385. isProcessing.value = true;
  386. messageQueue.value = [];
  387. // 重置 Thinking 模式状态
  388. isInThinkingMode.value = false;
  389. thinkingBuffer.value = '';
  390. scrollToBottom();
  391. // 重新发起请求
  392. startSSERequest(lastUserQuestion.value);
  393. }
  394. // ========== 工具方法 ==========
  395. // 错误处理
  396. const handleError = (error) => {
  397. let errorMessage = '发生错误';
  398. if (error.errMsg) {
  399. errorMessage = error.errMsg;
  400. } else if (error.message) {
  401. errorMessage = error.message;
  402. }
  403. uni.showToast({
  404. title: errorMessage,
  405. icon: 'none',
  406. duration: 2000
  407. });
  408. }
  409. // 防抖函数
  410. const debounce = (func, wait) => {
  411. let timeout;
  412. return (...args) => {
  413. clearTimeout(timeout);
  414. timeout = setTimeout(() => {
  415. func.apply(null, args);
  416. }, wait);
  417. };
  418. }
  419. // 输入框获取焦点
  420. const onInputFocus = () => {
  421. nextTick(() => {
  422. scrollToBottom();
  423. });
  424. }
  425. // 滚动到底部
  426. const scrollToBottom = () => {
  427. nextTick(() => {
  428. const query = uni.createSelectorQuery();
  429. query.select('.chat-list').boundingClientRect(data => {
  430. if (data) {
  431. scrollTop.value = data.height + 1000;
  432. }
  433. }).exec();
  434. });
  435. }
  436. const onScroll = (e) => {
  437. // 可以添加滚动事件处理
  438. }
  439. const getCurrentTime = () => {
  440. return getFormattedTime(new Date());
  441. }
  442. const getFormattedTime = (date) => {
  443. const hours = date.getHours().toString().padStart(2, '0');
  444. const minutes = date.getMinutes().toString().padStart(2, '0');
  445. return `${hours}:${minutes}`;
  446. }
  447. const useQuestion = (question) => {
  448. inputMessage.value = question;
  449. }
  450. const containsKeywords = (text) => {
  451. const keywords = ['水稻', '小麦', '玉米', '病虫害', '农药', '化肥', '有机肥', '种植技术'];
  452. return keywords.some(keyword => text.includes(keyword));
  453. }
  454. const formatMessage = (text) => {
  455. // 将文本中的换行符转换为<br>标签
  456. return text.replace(/\n/g, '<br>');
  457. }
  458. const initMessages = () => {
  459. // 确保消息有时间戳
  460. chatMessages.value.forEach(msg => {
  461. if (!msg.timestamp) {
  462. msg.timestamp = new Date().getTime();
  463. }
  464. });
  465. // 按时间排序
  466. chatMessages.value.sort((a, b) => a.timestamp - b.timestamp);
  467. }
  468. const showDateSeparator = (index) => {
  469. // 判断是否需要显示日期分割线
  470. if (index === 0) return true;
  471. const currentMsg = chatMessages.value[index];
  472. const prevMsg = chatMessages.value[index - 1];
  473. // 如果两条消息相隔超过30分钟,或者是不同日期,显示日期分割线
  474. return isDifferentDay(currentMsg.timestamp, prevMsg.timestamp) ||
  475. (currentMsg.timestamp - prevMsg.timestamp > 30 * 60 * 1000);
  476. }
  477. const isDifferentDay = (timestamp1, timestamp2) => {
  478. const date1 = new Date(timestamp1);
  479. const date2 = new Date(timestamp2);
  480. return date1.getDate() !== date2.getDate() ||
  481. date1.getMonth() !== date2.getMonth() ||
  482. date1.getFullYear() !== date2.getFullYear();
  483. }
  484. const formatDateSeparator = (timestamp) => {
  485. const now = new Date();
  486. const msgDate = new Date(timestamp);
  487. // 今天
  488. if (isSameDay(msgDate, now)) {
  489. return '今天 ' + getFormattedTime(msgDate);
  490. }
  491. // 昨天
  492. const yesterday = new Date(now);
  493. yesterday.setDate(now.getDate() - 1);
  494. if (isSameDay(msgDate, yesterday)) {
  495. return '昨天 ' + getFormattedTime(msgDate);
  496. }
  497. // 一周内
  498. const oneWeekAgo = new Date(now);
  499. oneWeekAgo.setDate(now.getDate() - 7);
  500. if (msgDate >= oneWeekAgo) {
  501. const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  502. return weekdays[msgDate.getDay()] + ' ' + getFormattedTime(msgDate);
  503. }
  504. // 其他日期
  505. return msgDate.getFullYear() + '年' + (msgDate.getMonth() + 1) + '月' + msgDate.getDate() + '日 ' + getFormattedTime(msgDate);
  506. }
  507. const isSameDay = (date1, date2) => {
  508. return date1.getDate() === date2.getDate() &&
  509. date1.getMonth() === date2.getMonth() &&
  510. date1.getFullYear() === date2.getFullYear();
  511. }
  512. // 获取下一轮建议问题列表
  513. const fetchSuggestedQuestions = async (data) => {
  514. console.log("获取下一轮建议问题参数",data);
  515. try {
  516. const response = await chatStreamSuggested(data);
  517. if (response && response.data) {
  518. // 假设接口返回的数据格式为 { data: ["问题1", "问题2", ...] }
  519. if (Array.isArray(response.data) && response.data.length > 0) {
  520. suggestedQuestions.value = response.data;
  521. } else if (response.data.questions && Array.isArray(response.data.questions)) {
  522. // 或者接口返回 { data: { questions: [...] } }
  523. suggestedQuestions.value = response.data.questions;
  524. }
  525. }
  526. } catch (error) {
  527. console.error('获取建议问题失败:', error);
  528. // 失败时保持默认建议问题,不影响用户体验
  529. }
  530. }
  531. // 生命周期钩子
  532. onMounted(() => {
  533. // 初始化防抖函数
  534. debouncedSubmitQuestion = debounce(submitQuestion, 300)
  535. // 获取系统信息
  536. const systemInfo = uni.getSystemInfoSync();
  537. statusBarHeight.value = systemInfo.statusBarHeight || 20;
  538. isIOS.value = systemInfo.platform === 'ios';
  539. safeAreaBottom.value = systemInfo.safeAreaInsets ? (systemInfo.safeAreaInsets.bottom || 0) : 0;
  540. // 初始化消息
  541. initMessages();
  542. // 滚动到底部
  543. nextTick(() => {
  544. scrollToBottom();
  545. });
  546. // 监听来自 renderjs 的自定义事件
  547. window.addEventListener('renderjs-stream-data', (event) => {
  548. console.log('通过事件接收到数据:', event.detail);
  549. onStreamData(event.detail);
  550. });
  551. })
  552. // 组件销毁时清理资源
  553. onBeforeUnmount(() => {
  554. // 停止打字机效果
  555. stopTypingEffect();
  556. // 通知 renderjs 停止连接
  557. if (isProcessing.value) {
  558. renderjsData.value = {
  559. action: 'stop',
  560. timestamp: Date.now()
  561. };
  562. }
  563. // 清理消息队列
  564. messageQueue.value = [];
  565. // 移除事件监听器
  566. window.removeEventListener('renderjs-stream-data', onStreamData);
  567. })
  568. </script>
  569. <script module="renderModule" lang="renderjs">
  570. // renderjs 模块状态
  571. let eventSource = null;
  572. let reader = null;
  573. let isReading = false;
  574. let eventType = '';
  575. let dataBuffer = [];
  576. let messageIdS = null;
  577. // 启动 SSE 连接
  578. async function startSSE(config, ownerInstance) {
  579. // 先停止之前的连接
  580. stopSSE();
  581. const { url, data, token } = config;
  582. try {
  583. // 使用 fetch API 建立 SSE 连接
  584. const response = await fetch(url, {
  585. method: 'POST',
  586. headers: {
  587. 'Content-Type': 'application/json',
  588. 'Accept': 'text/event-stream',
  589. 'Authorization': `Bearer ${token}`
  590. },
  591. body: JSON.stringify(data)
  592. });
  593. if (!response.ok) {
  594. throw new Error(`HTTP error! status: ${response.status}`);
  595. }
  596. // 获取 reader
  597. reader = response.body.getReader();
  598. const decoder = new TextDecoder('utf-8');
  599. isReading = true;
  600. let buffer = '';
  601. eventType = ''; // 当前事件名
  602. dataBuffer = []; // 当前事件的所有 data 行
  603. // 读取流式数据
  604. while (isReading) {
  605. const { done, value } = await reader.read();
  606. if (done) {
  607. console.log('SSE 流结束');
  608. window.dispatchEvent(new CustomEvent('renderjs-stream-data', {
  609. detail: { type: 'end', id: messageIdS }
  610. }));
  611. break;
  612. }
  613. // 解码数据
  614. buffer += decoder.decode(value, { stream: true });
  615. // 按行处理
  616. const lines = buffer.split('\n');
  617. buffer = lines.pop() || ''; // 保留最后不完整的行
  618. for (const line of lines) {
  619. processLine(line, ownerInstance);
  620. }
  621. }
  622. } catch (error) {
  623. console.error('SSE 连接错误:', error);
  624. window.dispatchEvent(new CustomEvent('renderjs-stream-data', {
  625. detail: {
  626. type: 'error',
  627. error: error.message || '连接失败'
  628. }
  629. }));
  630. } finally {
  631. stopSSE();
  632. }
  633. }
  634. // 处理单行数据
  635. function processLine(line, ownerInstance) {
  636. if (!line.trim()) return;
  637. console.log('[renderjs] 处理行数据:', line);
  638. // 解析 SSE 格式
  639. if (line.startsWith('event:')) {
  640. // event: message
  641. return;
  642. }
  643. if (line.startsWith('data:') || line !== '') {
  644. let data = line;
  645. if (line.startsWith('data:')) {
  646. data = data.substring(5).trim();
  647. }
  648. if (!data || data.includes("ping")) return;
  649. console.log('[renderjs] 解析后的数据:', data);
  650. // 过滤掉 MESSAGE_END 等元数据事件(JSON 格式)
  651. if (data.startsWith('{') && data.includes('"eventType"')) {
  652. try {
  653. const jsonData = JSON.parse(data);
  654. console.log('[renderjs] JSON 事件:', jsonData);
  655. // 如果是 MESSAGE_END 事件,通知结束
  656. if (jsonData.eventType === 'MESSAGE_END' || jsonData.event === 'message_end') {
  657. console.log('[renderjs] 收到 MESSAGE_END 事件,流式结束');
  658. messageIdS = jsonData.id;
  659. window.dispatchEvent(new CustomEvent('renderjs-stream-data', {
  660. detail: { type: 'end', id: messageIdS }
  661. }));
  662. return;
  663. }
  664. // 其他元数据事件也忽略
  665. return;
  666. } catch (e) {
  667. console.log('[renderjs] JSON 解析失败,作为普通文本处理');
  668. // 不是 JSON,继续处理
  669. }
  670. }
  671. // 检查是否是 Thinking 内容
  672. if (data.includes('<details') && data.includes('<summary>')) {
  673. console.log('[renderjs] 发送 thinking 类型数据');
  674. // 使用自定义事件发送数据
  675. window.dispatchEvent(new CustomEvent('renderjs-stream-data', {
  676. detail: {
  677. type: 'thinking',
  678. content: data
  679. }
  680. }));
  681. } else {
  682. console.log('[renderjs] 发送 message 类型数据,长度:', data.length);
  683. // 普通消息内容
  684. window.dispatchEvent(new CustomEvent('renderjs-stream-data', {
  685. detail: {
  686. type: 'message',
  687. content: data
  688. }
  689. }));
  690. }
  691. }
  692. }
  693. // 停止 SSE 连接
  694. function stopSSE() {
  695. isReading = false;
  696. if (reader) {
  697. try {
  698. reader.cancel();
  699. } catch (e) {
  700. console.error('关闭 reader 失败:', e);
  701. }
  702. reader = null;
  703. }
  704. if (eventSource) {
  705. eventSource.close();
  706. eventSource = null;
  707. }
  708. }
  709. // 导出方法供 Vue 调用
  710. export default {
  711. methods: {
  712. // 监听 prop 变化
  713. onDataChange(newValue, oldValue, ownerInstance) {
  714. if (!newValue || !newValue.action) return;
  715. if (newValue.action === 'start') {
  716. startSSE(newValue, ownerInstance);
  717. } else if (newValue.action === 'stop') {
  718. stopSSE();
  719. }
  720. }
  721. }
  722. };
  723. </script>
  724. <style>
  725. /* 容器样式 */
  726. .container {
  727. position: relative;
  728. min-height: 100vh;
  729. background-color: #f5f5f5;
  730. overflow: hidden;
  731. /* 防止内容溢出 */
  732. }
  733. /* 聊天容器 */
  734. .chat-container {
  735. padding: 20rpx 30rpx;
  736. box-sizing: border-box;
  737. background-color: #f8f8f8;
  738. background-image: url('/static/images/chat-bg-pattern.png');
  739. background-size: 300rpx;
  740. background-blend-mode: overlay;
  741. background-opacity: 0.05;
  742. -webkit-overflow-scrolling: touch;
  743. /* 增强iOS滚动体验 */
  744. }
  745. .chat-list {
  746. padding-bottom: 30rpx;
  747. }
  748. /* 消息项 */
  749. .message-item {
  750. display: flex;
  751. margin-bottom: 30rpx;
  752. position: relative;
  753. }
  754. .message-ai {
  755. justify-content: flex-start;
  756. }
  757. .message-user {
  758. justify-content: flex-end;
  759. }
  760. /* 头像 */
  761. .avatar-container {
  762. width: 90rpx;
  763. height: 90rpx;
  764. flex-shrink: 0;
  765. }
  766. .avatar {
  767. width: 90rpx;
  768. height: 90rpx;
  769. border-radius: 50%;
  770. background-color: #e0e0e0;
  771. box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  772. object-fit: cover;
  773. }
  774. /* 消息内容 */
  775. .message-content {
  776. max-width: 70%;
  777. margin: 0 20rpx;
  778. display: flex;
  779. flex-direction: column;
  780. }
  781. .user-content {
  782. align-items: flex-end;
  783. }
  784. .message-bubble {
  785. padding: 24rpx;
  786. border-radius: 24rpx;
  787. position: relative;
  788. margin-bottom: 10rpx;
  789. word-wrap: break-word;
  790. min-width: 80rpx;
  791. box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
  792. transition: all 0.3s ease;
  793. max-width: 100%;
  794. }
  795. .ai-bubble {
  796. background-color: #e8f5e9;
  797. border-top-left-radius: 4rpx;
  798. }
  799. .user-bubble {
  800. background-color: #e3f2fd;
  801. border-top-right-radius: 4rpx;
  802. }
  803. .message-text {
  804. font-size: 28rpx;
  805. color: #333;
  806. line-height: 1.5;
  807. word-break: break-all;
  808. }
  809. .message-time {
  810. font-size: 22rpx;
  811. color: #999;
  812. }
  813. /* 消息操作按钮 */
  814. .message-actions {
  815. display: flex;
  816. gap: 16rpx;
  817. margin-top: 12rpx;
  818. }
  819. .action-button {
  820. display: flex;
  821. align-items: center;
  822. padding: 8rpx 16rpx;
  823. background-color: #f5f5f5;
  824. border-radius: 20rpx;
  825. border: 1rpx solid #e0e0e0;
  826. transition: all 0.2s;
  827. }
  828. .action-button-hover {
  829. background-color: #e8f5e9;
  830. border-color: #a5d6a7;
  831. }
  832. .action-icon {
  833. font-size: 24rpx;
  834. margin-right: 6rpx;
  835. }
  836. .action-text {
  837. font-size: 24rpx;
  838. color: #666;
  839. }
  840. /* 输入区域 */
  841. .input-container {
  842. position: fixed;
  843. bottom: 90rpx;
  844. left: 0;
  845. right: 0;
  846. background-color: #fff;
  847. padding: 20rpx 30rpx;
  848. box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  849. display: flex;
  850. flex-direction: column;
  851. z-index: 10;
  852. }
  853. .input-wrapper {
  854. display: flex;
  855. align-items: flex-end;
  856. }
  857. .message-input {
  858. flex: 1;
  859. min-height: 70rpx;
  860. max-height: 120rpx;
  861. border-radius: 35rpx;
  862. background-color: #f5f5f5;
  863. padding: 15rpx 30rpx;
  864. font-size: 28rpx;
  865. color: #333;
  866. border: 1rpx solid #e0e0e0;
  867. line-height: 1.4;
  868. }
  869. .send-button {
  870. margin-left: 16rpx;
  871. width: 76rpx;
  872. height: 76rpx;
  873. border-radius: 50%;
  874. background-color: transparent;
  875. background-image: none;
  876. display: flex;
  877. align-items: center;
  878. justify-content: center;
  879. transition: all 0.2s ease;
  880. position: relative;
  881. align-self: center;
  882. }
  883. .send-button.disabled {
  884. background-color: transparent;
  885. background-image: none;
  886. opacity: 1;
  887. }
  888. /* 中止按钮 */
  889. .stop-button {
  890. margin-left: 16rpx;
  891. width: 76rpx;
  892. height: 76rpx;
  893. border-radius: 50%;
  894. background-color: #ff5252;
  895. display: flex;
  896. align-items: center;
  897. justify-content: center;
  898. transition: all 0.2s ease;
  899. align-self: center;
  900. }
  901. .stop-icon {
  902. font-size: 36rpx;
  903. color: white;
  904. }
  905. .button-hover {
  906. transform: scale(0.95);
  907. }
  908. @keyframes pulse {
  909. 0% {
  910. transform: scale(1);
  911. }
  912. 50% {
  913. transform: scale(0.95);
  914. }
  915. 100% {
  916. transform: scale(1);
  917. }
  918. }
  919. .send-button:active:not(.disabled) {
  920. animation: pulse 0.3s ease-in-out;
  921. }
  922. /* 删除或注释掉之前的样式 */
  923. .send-icon {
  924. display: none;
  925. }
  926. .send-icon:before {
  927. display: none;
  928. }
  929. .send-icon-text {
  930. display: none;
  931. }
  932. /* 推荐问题区域 */
  933. .suggested-questions {
  934. display: flex;
  935. white-space: nowrap;
  936. margin-bottom: 15rpx;
  937. padding: 5rpx 0;
  938. }
  939. .question-chip {
  940. display: inline-block;
  941. padding: 12rpx 20rpx;
  942. margin-right: 15rpx;
  943. background-color: #e8f5e9;
  944. color: #4CAF50;
  945. font-size: 24rpx;
  946. border-radius: 30rpx;
  947. border: 1rpx solid #a5d6a7;
  948. }
  949. /* AI正在输入的样式 */
  950. .message-bubble.ai-bubble.typing {
  951. background-color: #f0f0f0;
  952. }
  953. .typing-indicator {
  954. display: flex;
  955. align-items: center;
  956. justify-content: center;
  957. height: 40rpx;
  958. padding: 0 20rpx;
  959. }
  960. .typing-dot {
  961. width: 10rpx;
  962. height: 10rpx;
  963. margin: 0 5rpx;
  964. background-color: #4CAF50;
  965. border-radius: 50%;
  966. opacity: 0.5;
  967. animation: typingAnimation 1.4s infinite both;
  968. }
  969. .typing-dot:nth-child(2) {
  970. animation-delay: 0.2s;
  971. }
  972. .typing-dot:nth-child(3) {
  973. animation-delay: 0.4s;
  974. }
  975. @keyframes typingAnimation {
  976. 0% {
  977. opacity: 0.3;
  978. transform: translateY(0);
  979. }
  980. 50% {
  981. opacity: 1;
  982. transform: translateY(-5rpx);
  983. }
  984. 100% {
  985. opacity: 0.3;
  986. transform: translateY(0);
  987. }
  988. }
  989. /* 关键词高亮 */
  990. .message-text.highlight {
  991. color: #2E7D32;
  992. font-weight: 500;
  993. }
  994. /* 欢迎消息特殊样式 */
  995. .welcome {
  996. background-color: #e3f2fd !important;
  997. border-left: none !important;
  998. border-radius: 24rpx !important;
  999. }
  1000. /* 日期分割线样式 */
  1001. .date-separator {
  1002. display: flex;
  1003. align-items: center;
  1004. justify-content: center;
  1005. margin: 20rpx 0;
  1006. }
  1007. .date-separator text {
  1008. background-color: rgba(0, 0, 0, 0.1);
  1009. color: #666;
  1010. font-size: 24rpx;
  1011. padding: 4rpx 20rpx;
  1012. border-radius: 20rpx;
  1013. }
  1014. /* 纸飞机图标 */
  1015. .plane-svg {
  1016. display: none;
  1017. }
  1018. .send-icon-image {
  1019. width: 76rpx;
  1020. height: 76rpx;
  1021. }
  1022. .material-icon {
  1023. font-family: 'Material Icons';
  1024. font-weight: normal;
  1025. font-style: normal;
  1026. font-size: 48rpx;
  1027. line-height: 1;
  1028. letter-spacing: normal;
  1029. text-transform: none;
  1030. display: inline-block;
  1031. white-space: nowrap;
  1032. word-wrap: normal;
  1033. direction: ltr;
  1034. -webkit-font-smoothing: antialiased;
  1035. color: white;
  1036. }
  1037. /* 删除不需要的导航栏样式 */
  1038. .custom-navbar {
  1039. display: none;
  1040. }
  1041. .navbar-bg,
  1042. .navbar-content,
  1043. .navbar-left,
  1044. .navbar-title,
  1045. .navbar-right,
  1046. .back-icon,
  1047. .arrow-left {
  1048. display: none;
  1049. }
  1050. /* renderjs 容器(隐藏) */
  1051. .renderjs-container {
  1052. display: none;
  1053. width: 0;
  1054. height: 0;
  1055. opacity: 0;
  1056. position: absolute;
  1057. pointer-events: none;
  1058. }
  1059. </style>