index.vue 29 KB

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