message-consult.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. interface ConsultMessage {
  2. id: string; // 咨询记录详情ID
  3. consultRecordId: number; //咨询记录ID
  4. sender: "user" | "agent" | "human" | "system";
  5. sendType: string; // 发送类型 1-患者 2-医生 3-系统 4-AI
  6. messageType: "1" | "2"; // 1文本 2 图片
  7. messageContent?: string; // 消息内容
  8. sendTime?: string; // 发送消息的时间
  9. }
  10. import { Post } from "../../../../lib/request/method";
  11. import { upload } from "../../../../lib/request/upload";
  12. import dayjs from "dayjs";
  13. // sendType映射: 1-患者 2-医生 3-系统 4-AI
  14. const sendTypeMap: Record<string, "user" | "agent" | "human" | "system"> = {
  15. "1": "user", // 患者
  16. "2": "human", // 医生
  17. "3": "system", // 系统
  18. "4": "agent", // AI
  19. };
  20. // 计算底部安全区位置(rpx)
  21. function calculateSafeBottomRpx(): number {
  22. const systemInfo = wx.getSystemInfoSync();
  23. // 获取窗口的高度
  24. const windowHeight = systemInfo.windowHeight;
  25. // 获取安全区底部的高度
  26. const safeAreaBottom = systemInfo.safeArea?.bottom ?? windowHeight;
  27. const safeBottom = windowHeight - safeAreaBottom;
  28. //将px转为rpx
  29. return (750 / systemInfo.windowWidth) * safeBottom;
  30. }
  31. // 判断消息是否为真正的咨询结束消息(排除30分钟提醒消息)
  32. function isConsultEndMessage(msg: ConsultMessage): boolean {
  33. if (msg.sendType !== "3" || !msg.messageContent) {
  34. return false;
  35. }
  36. const content = msg.messageContent;
  37. // 排除30分钟提醒消息(包含"30分钟"和"5分钟后")
  38. const isReminder =
  39. content.includes("30分钟") &&
  40. (content.includes("5分钟后") || content.includes("将在"));
  41. // 判断是否为真正的咨询结束消息
  42. const isRealEnd = content.includes("咨询结束") && !isReminder;
  43. return isRealEnd;
  44. }
  45. // 转义 HTML 特殊字符
  46. function escapeHtml(text: string): string {
  47. return text
  48. .replace(/&/g, "&amp;")
  49. .replace(/</g, "&lt;")
  50. .replace(/>/g, "&gt;")
  51. .replace(/"/g, "&quot;")
  52. .replace(/'/g, "&#39;");
  53. }
  54. // 将 Markdown 格式文本转换为 HTML(支持基本的 Markdown 语法)
  55. function parseMarkdown(text: string): string {
  56. if (!text) return "";
  57. // 先处理代码块(三个反引号),提取出来避免被其他规则匹配
  58. const codeBlocks: string[] = [];
  59. let codeBlockIndex = 0;
  60. let html = text.replace(/```([\s\S]*?)```/g, (_, code) => {
  61. const placeholder = `__CODE_BLOCK_${codeBlockIndex}__`;
  62. codeBlocks[codeBlockIndex] = escapeHtml(code);
  63. codeBlockIndex++;
  64. return placeholder;
  65. });
  66. // 处理行内代码(一个反引号),也要先提取出来
  67. const inlineCodes: string[] = [];
  68. let inlineCodeIndex = 0;
  69. html = html.replace(/`([^`\n]+)`/g, (_, code) => {
  70. const placeholder = `__INLINE_CODE_${inlineCodeIndex}__`;
  71. inlineCodes[inlineCodeIndex] = escapeHtml(code);
  72. inlineCodeIndex++;
  73. return placeholder;
  74. });
  75. // 先处理列表(在处理加粗之前,避免 split 时分割 strong 标签)
  76. // 处理列表:支持无序列表(以 - 或 * 开头的行)
  77. const lines = html.split("\n");
  78. let inList = false;
  79. let result: string[] = [];
  80. for (let i = 0; i < lines.length; i++) {
  81. const line = lines[i];
  82. // 匹配以空格+减号或星号开头的行(列表项)
  83. const listMatch = line.match(/^(\s*)[-*]\s+(.+)$/);
  84. if (listMatch) {
  85. if (!inList) {
  86. result.push("<ul>");
  87. inList = true;
  88. }
  89. result.push(`<li>${listMatch[2]}</li>`);
  90. } else {
  91. if (inList) {
  92. result.push("</ul>");
  93. inList = false;
  94. }
  95. if (line.trim()) {
  96. result.push(line);
  97. } else {
  98. result.push("<br>");
  99. }
  100. }
  101. }
  102. if (inList) {
  103. result.push("</ul>");
  104. }
  105. html = result.join("\n");
  106. // 处理加粗:两个※※(优先处理,避免与单个※冲突)
  107. // 使用 span 标签配合 style,确保是行内元素
  108. html = html.replace(/※※([^\n]+?)※※/g, (_, content) => {
  109. return `<span style="font-weight:bold;display:inline;">${escapeHtml(content.trim())}</span>`;
  110. });
  111. // 处理加粗:两个星号 **
  112. html = html.replace(/\*\*([^\n]+?)\*\*/g, (_, content) => {
  113. return `<span style="font-weight:bold;display:inline;">${escapeHtml(content.trim())}</span>`;
  114. });
  115. // 处理斜体:一个※(但要排除已经是加粗标记的)
  116. html = html.replace(/(?<!※)※(?!※)([^※\n]+?)※(?!※)/g, (_, content) => {
  117. return `<span style="font-style:italic;display:inline;">${escapeHtml(content.trim())}</span>`;
  118. });
  119. // 处理斜体:一个星号 *(但要排除已经是加粗标记的)
  120. html = html.replace(/(?<!\*)\*(?!\*)([^\*\n]+?)\*(?!\*)/g, (_, content) => {
  121. return `<span style="font-style:italic;display:inline;">${escapeHtml(content.trim())}</span>`;
  122. });
  123. // 恢复行内代码
  124. for (let i = 0; i < inlineCodes.length; i++) {
  125. html = html.replace(`__INLINE_CODE_${i}__`, `<code>${inlineCodes[i]}</code>`);
  126. }
  127. // 恢复代码块
  128. for (let i = 0; i < codeBlocks.length; i++) {
  129. html = html.replace(`__CODE_BLOCK_${i}__`, `<pre><code>${codeBlocks[i]}</code></pre>`);
  130. }
  131. // 转义剩余文本中的 HTML 特殊字符(但保留已经生成的 HTML 标签)
  132. const tagPlaceholders: string[] = [];
  133. let tagIndex = 0;
  134. // 现在使用 span 标签,所以需要匹配 span 和 code、pre、ul、li、br
  135. html = html.replace(/<(\/?)(span|code|pre|ul|li|br)[^>]*>/gi, (match) => {
  136. const placeholder = `__TAG_${tagIndex}__`;
  137. tagPlaceholders[tagIndex] = match;
  138. tagIndex++;
  139. return placeholder;
  140. });
  141. // 转义剩余的 HTML 特殊字符
  142. html = escapeHtml(html);
  143. // 恢复 HTML 标签
  144. for (let i = 0; i < tagPlaceholders.length; i++) {
  145. html = html.replace(`__TAG_${i}__`, tagPlaceholders[i]);
  146. }
  147. // 统一清理所有 HTML 标签之间的空白字符
  148. // 关键:加粗标签后绝对不能有任何空白字符,包括换行符、空格、制表符等
  149. // 第一步:清理所有标签之间的空白
  150. html = html.replace(/>[\s\n\r\t]+</g, "><");
  151. // 第二步:特别处理加粗标签 - 移除后面所有空白字符(包括换行符)
  152. html = html.replace(/(<\/span[^>]*style="[^"]*font-weight:bold[^"]*"[^>]*>)[\s\n\r\t\u00A0\u2000-\u200B\u2028\u2029\u3000]+/g, "$1");
  153. // 第三步:清理其他 span 标签前后的空白
  154. html = html.replace(/(<\/span[^>]*>)[\s\n\r\t]+/g, "$1");
  155. html = html.replace(/[\s\n\r\t]+(<span[^>]*>)/g, "$1");
  156. // 第四步:清理其他标签前后的空白
  157. html = html.replace(/>[\s\n\r\t]+/g, ">");
  158. html = html.replace(/[\s\n\r\t]+</g, "<");
  159. // 第五步:将换行符转换为 <br>(加粗标签后的换行已经被移除了)
  160. html = html.replace(/\n/g, "<br>");
  161. // 第六步:最后再次确保加粗标签后没有任何空白字符
  162. html = html.replace(/(<\/span[^>]*style="[^"]*font-weight:bold[^"]*"[^>]*>)[\s\u00A0\u2000-\u200B\u2028\u2029\u3000]+/g, "$1");
  163. return html;
  164. }
  165. // 获取的聊天消息为ConsultMessage格式 提取为一个公共的方法
  166. function transformMessage(item: AnyObject): ConsultMessage {
  167. const sender = sendTypeMap[item.sendType];
  168. return {
  169. id: `msg-${item.id}`,
  170. consultRecordId: item.consultRecordId,
  171. sender,
  172. sendTime: item.sendTime || "",
  173. sendType: item.sendType,
  174. messageType: item.messageType as "1" | "2",
  175. messageContent: item.messageContent || "",
  176. };
  177. }
  178. Component({
  179. properties: {},
  180. data: {
  181. messages: [] as ConsultMessage[],
  182. inputText: "",
  183. inputFocus: true,
  184. inputBoxBottom: 0,
  185. baseInputBottom: 0,
  186. keepFocus: true,
  187. _keyboardHeight: 0, // 当前键盘高度
  188. isTransferredToHuman: false, // 是否已转人工
  189. consultEnded: false, // 是否已结束咨询
  190. _pollTimer: 0 as any, // 5秒轮询最新消息定时器
  191. textareaHeight: 80, // textarea 高度(rpx),初始值与 min-height 一致
  192. },
  193. lifetimes: {
  194. async attached() {
  195. const safeBottomRpx = calculateSafeBottomRpx();
  196. const tabBarHeight = 100; // rpx
  197. const baseBottom = safeBottomRpx + tabBarHeight;
  198. console.log("baseBottom==输入框的位置", baseBottom);
  199. // 获取咨询中的id
  200. const consultId = wx.getStorageSync("consultId");
  201. let messages: ConsultMessage[] = [];
  202. if (consultId) {
  203. try {
  204. // 获取所有消息的数据
  205. const res = await Post(`/consultManage/getAllMsgs/${consultId}`);
  206. if (res.data && res.data.length > 0) {
  207. messages = res.data.map((item: AnyObject) => {
  208. const msg = transformMessage(item);
  209. // 对 AI 和医生的文本消息进行 Markdown 解析
  210. if (
  211. (msg.sender === "agent" || msg.sender === "human") &&
  212. msg.messageType === "1" &&
  213. msg.messageContent
  214. ) {
  215. msg.messageContent = parseMarkdown(msg.messageContent);
  216. }
  217. return msg;
  218. });
  219. }
  220. } catch (error: any) {
  221. wx.showToast({
  222. title: error?.errMsg || "获取历史消息失败",
  223. icon: "none",
  224. });
  225. }
  226. }
  227. // 检查历史消息中是否有真正的咨询结束消息(排除30分钟提醒消息)
  228. const hasEndMessage = messages.some((msg: ConsultMessage) =>
  229. isConsultEndMessage(msg)
  230. );
  231. const consultEnded = hasEndMessage || wx.getStorageSync("consultEnded");
  232. console.log(
  233. "安全区的距离",
  234. safeBottomRpx,
  235. "consultEnded==是否已结束咨询",
  236. consultEnded
  237. );
  238. this.setData({
  239. baseInputBottom: baseBottom,
  240. inputBoxBottom: baseBottom,
  241. messages,
  242. consultEnded: !!consultEnded,
  243. });
  244. console.log("baseBottom==输入框的位置", baseBottom);
  245. this.triggerEvent("boxBottom", { inputBoxBottom: baseBottom });
  246. // 监听键盘高度变化事件
  247. // 每次键盘高度变化时直接更新位置
  248. const kbHandler = (res: any) => {
  249. const height = res?.height ?? 0;
  250. // 键盘收起时,直接更新位置
  251. if (height === 0) {
  252. this._updateInputPosition(0);
  253. return;
  254. }
  255. // 键盘弹起时的处理:
  256. // 1. 如果输入框已聚焦,直接更新位置
  257. // 2. 如果输入框未聚焦但 keepFocus 为 true,说明正在等待聚焦(第一次打开的情况),也应该更新位置
  258. // 这样可以解决鸿蒙系统第一次打开时键盘先弹起但输入框未聚焦的问题
  259. if (this.data.inputFocus || this.data.keepFocus) {
  260. // 直接更新位置,每次键盘高度变化时都更新
  261. this._updateInputPosition(height);
  262. }
  263. };
  264. wx.onKeyboardHeightChange?.(kbHandler);
  265. (this as any)._kbHandler = kbHandler;
  266. // 渲染完成后再触发一次聚焦,确保键盘弹起
  267. this._ensureFocus();
  268. // 鸿蒙系统兼容:延迟检查键盘高度,确保第一次打开时能正确更新位置
  269. // 在 _ensureFocus 延迟聚焦之后,再延迟一点时间检查键盘高度
  270. const systemInfo = wx.getSystemInfoSync();
  271. // 判断是否是鸿蒙系统:通过 system 字段判断,鸿蒙系统通常包含 "HarmonyOS"
  272. const isHarmonyOS = systemInfo.system && systemInfo.system.toLowerCase().includes('harmony');
  273. console.log("isHarmonyOS==是否是鸿蒙系统", isHarmonyOS);
  274. const delayTime = isHarmonyOS ? 300 : 0;
  275. if (delayTime > 0) {
  276. setTimeout(() => {
  277. // 如果此时键盘高度已记录但位置未更新,强制更新一次
  278. if (this.data._keyboardHeight > 0 && this.data.keepFocus) {
  279. this._updateInputPosition(this.data._keyboardHeight);
  280. }
  281. }, delayTime);
  282. }
  283. // 如果咨询未结束,启动轮询最新消息
  284. if (!consultEnded) {
  285. this._startPolling();
  286. }
  287. },
  288. detached() {
  289. // 清理监听
  290. if ((this as any)._kbHandler) {
  291. wx.offKeyboardHeightChange?.((this as any)._kbHandler);
  292. }
  293. // 清理轮询定时器
  294. this._stopPolling();
  295. },
  296. },
  297. methods: {
  298. // 滚动到底部-
  299. _scrollToBottom() {
  300. this.triggerEvent("scroll", { id: "bottom" });
  301. },
  302. // 收起键盘并更新位置
  303. _hideKeyboardAndUpdatePosition() {
  304. wx.hideKeyboard?.();
  305. this.setData({
  306. inputFocus: false,
  307. keepFocus: false,
  308. });
  309. this._updateInputPosition(0);
  310. },
  311. // 统一的位置更新方法
  312. _updateInputPosition(keyboardHeight: number) {
  313. const systemInfo = wx.getSystemInfoSync();
  314. const rpx2px = systemInfo.windowWidth / 750;
  315. // 键盘高度是 px,转换为 rpx
  316. const keyboardHeightRpx =
  317. keyboardHeight > 0 ? keyboardHeight / rpx2px : 0;
  318. // 计算输入框底部位置
  319. // 键盘展开时:面板紧贴键盘(bottom = 键盘高度),确保没有空隙
  320. // 键盘收起时:保留 tabbar 距离(baseInputBottom 已包含安全区 + 100rpx tabbar)
  321. const nextBottom =
  322. keyboardHeight > 0 ? keyboardHeightRpx : this.data.baseInputBottom;
  323. // 避免重复更新相同位置(容差1rpx)
  324. if (Math.abs(nextBottom - this.data.inputBoxBottom) < 1) {
  325. // 位置已经正确,只更新键盘高度记录
  326. if (keyboardHeight !== this.data._keyboardHeight) {
  327. this.setData({ _keyboardHeight: keyboardHeight });
  328. }
  329. return;
  330. }
  331. // 更新位置和键盘高度
  332. this.setData({
  333. inputBoxBottom: nextBottom,
  334. _keyboardHeight: keyboardHeight,
  335. });
  336. // 通知父组件更新底部 padding
  337. this.triggerEvent("boxBottom", { inputBoxBottom: nextBottom });
  338. // 键盘弹出时平滑滚动到底部
  339. if (keyboardHeight > 0) {
  340. this.triggerEvent("scroll", { id: "bottom" });
  341. }
  342. },
  343. _ensureFocus() {
  344. if (!this.data.keepFocus) return;
  345. this.setData({ inputFocus: false });
  346. wx.nextTick?.(() => {
  347. setTimeout(() => {
  348. if (this.data.keepFocus) {
  349. this.setData({ inputFocus: true });
  350. // 鸿蒙系统兼容:在聚焦后延迟检查键盘高度并更新位置
  351. // 这样可以确保即使键盘在聚焦前弹起,也能在聚焦后正确更新位置
  352. setTimeout(() => {
  353. if (this.data._keyboardHeight > 0 && this.data.inputFocus) {
  354. this._updateInputPosition(this.data._keyboardHeight);
  355. }
  356. }, 150);
  357. }
  358. }, 120);
  359. });
  360. },
  361. tapPanel() {
  362. if (!this.data.inputFocus && this.data.keepFocus) {
  363. this._ensureFocus();
  364. }
  365. },
  366. endConsult() {
  367. // 收起键盘并更新位置
  368. this._hideKeyboardAndUpdatePosition();
  369. wx.showModal({
  370. title: "",
  371. content: "确定要结束本次咨询?",
  372. cancelText: "继续咨询",
  373. confirmText: "结束",
  374. }).then((res: any) => {
  375. if (res.confirm) {
  376. // 确认结束
  377. this._endConsult();
  378. } else {
  379. // 继续咨询,恢复聚焦
  380. this.setData({ keepFocus: true });
  381. this._ensureFocus();
  382. }
  383. });
  384. },
  385. async _endConsult() {
  386. // 格式化日期时间,格式:MM-DD HH:mm:ss(与系统消息格式一致)
  387. const endDate = dayjs().format("MM-DD HH:mm:ss");
  388. // 手动添加系统消息样式的结束时间
  389. const consultId = wx.getStorageSync("consultId");
  390. this._appendMessage({
  391. id: `end-time-${Date.now()}`,
  392. consultRecordId: consultId || 0,
  393. sender: "system",
  394. sendType: "3",
  395. messageType: "1",
  396. messageContent: "咨询结束",
  397. sendTime: endDate,
  398. });
  399. // 调用结束咨询接口
  400. if (consultId) {
  401. try {
  402. await Post(`/consultManage/end/${consultId}`);
  403. } catch (error: any) {
  404. wx.showToast({
  405. title: error?.errMsg || "结束咨询失败",
  406. icon: "none",
  407. });
  408. }
  409. }
  410. // 设置结束状态
  411. this.setData({ consultEnded: true });
  412. // 更新本地存储:标记咨询已结束
  413. wx.setStorageSync("consultEnded", true);
  414. //咨询结束之后 需要清除咨询id
  415. wx.removeStorageSync("consultId");
  416. // 停止轮询最新消息
  417. this._stopPolling();
  418. // 收起键盘
  419. wx.hideKeyboard?.();
  420. // 重置底部位置为正常值(tabbar 高度 + 安全区高度)
  421. const safeBottomRpx = calculateSafeBottomRpx();
  422. const tabBarHeight = 100; // rpx
  423. const normalBottom = tabBarHeight + safeBottomRpx;
  424. // 通知父组件重置 paddingBottom,避免菜单下方有大的距离
  425. this.triggerEvent("boxBottom", { inputBoxBottom: normalBottom });
  426. // 通知父组件显示guide菜单组件
  427. this.triggerEvent("consultEvent", { type: "end" });
  428. // 滚动到底部
  429. this._scrollToBottom();
  430. },
  431. handleInput(event: any) {
  432. const value = event.detail.value;
  433. this.setData({ inputText: value });
  434. // 内容为空时,立即重置为最小高度
  435. if (!value || value.trim() === "") {
  436. if (this.data.textareaHeight !== 80) {
  437. this.setData({ textareaHeight: 80 });
  438. }
  439. }
  440. },
  441. onLineChange(event: any) {
  442. const minHeight = 80; // 最小高度(rpx)
  443. const maxHeight = 200; // 最大高度(rpx)
  444. const lineCount = event.detail.lineCount || 1;
  445. // 如果输入框为空,直接设置为最小高度
  446. if (!this.data.inputText || this.data.inputText.trim() === "") {
  447. if (this.data.textareaHeight !== minHeight) {
  448. this.setData({ textareaHeight: minHeight });
  449. }
  450. return;
  451. }
  452. // 单行时保持最小高度,不更新
  453. if (lineCount === 1) {
  454. // 只有当当前高度不是最小高度时才更新
  455. if (this.data.textareaHeight !== minHeight) {
  456. this.setData({ textareaHeight: minHeight });
  457. }
  458. return;
  459. }
  460. // 多行时才动态计算高度
  461. // 字体大小 28rpx,行高 1.9,所以每行实际高度约为 28 * 1.9 ≈ 53rpx
  462. const lineHeight = 53; // 每行高度(rpx)
  463. const padding = 24; // 上下 padding 总和(12rpx * 2 = 24rpx)
  464. // 计算高度:行数 * 行高 + 上下 padding
  465. const calculatedHeight = lineCount * lineHeight + padding;
  466. // 限制在 minHeight 和 maxHeight 之间
  467. const finalHeight = Math.max(
  468. minHeight,
  469. Math.min(maxHeight, calculatedHeight)
  470. );
  471. // 只在高度确实需要变化时更新(阈值设为 3rpx,减少频繁更新和跳动)
  472. if (Math.abs(this.data.textareaHeight - finalHeight) > 3) {
  473. this.setData({ textareaHeight: finalHeight });
  474. }
  475. },
  476. onInputFocus(event: any) {
  477. const keyboardHeight = event.detail.height ?? 0;
  478. // 设置 focus 状态
  479. this.setData({
  480. inputFocus: true,
  481. keepFocus: true,
  482. });
  483. // 如果从 focus 事件获取到有效的键盘高度,立即更新位置
  484. if (keyboardHeight > 0) {
  485. this._updateInputPosition(keyboardHeight);
  486. } else {
  487. // 如果键盘高度为0,但之前已经记录了键盘高度(可能是鸿蒙系统的问题)
  488. // 尝试使用已记录的键盘高度来更新位置
  489. if (this.data._keyboardHeight > 0) {
  490. // 延迟一点时间,等待键盘完全弹起后再更新
  491. setTimeout(() => {
  492. if (this.data.inputFocus && this.data._keyboardHeight > 0) {
  493. this._updateInputPosition(this.data._keyboardHeight);
  494. }
  495. }, 100);
  496. }
  497. }
  498. },
  499. onInputBlur() {
  500. console.log("onInputBlur==输入框失焦");
  501. // 设置 focus 状态
  502. this.setData({
  503. inputFocus: false,
  504. });
  505. // 延迟恢复位置,确保键盘完全收起
  506. setTimeout(() => {
  507. // 只有当前没有聚焦时,才恢复位置(避免在快速切换时出现问题)
  508. if (!this.data.inputFocus) {
  509. this._updateInputPosition(0);
  510. }
  511. }, 100);
  512. },
  513. // 启动轮询最新消息
  514. _startPolling() {
  515. // 如果咨询已结束,不启动轮询
  516. if (this.data.consultEnded) return;
  517. // 清除之前的轮询定时器
  518. this._stopPolling();
  519. // 每5秒轮询一次
  520. const timer = setInterval(() => {
  521. // 如果咨询已结束,停止轮询
  522. if (this.data.consultEnded) {
  523. this._stopPolling();
  524. return;
  525. }
  526. this._getLatestMessages();
  527. }, 5000);
  528. this.setData({ _pollTimer: timer });
  529. },
  530. // 停止轮询最新消息
  531. _stopPolling() {
  532. if (this.data._pollTimer) {
  533. clearInterval(this.data._pollTimer);
  534. this.setData({ _pollTimer: 0 });
  535. }
  536. },
  537. // 获取最新消息
  538. async _getLatestMessages() {
  539. const consultId = wx.getStorageSync("consultId");
  540. if (!consultId) return;
  541. try {
  542. // 获取最新消息
  543. const res = await Post(`/consultManage/getLatestMsgs/${consultId}`);
  544. // 如果有最新消息要追加到消息列表
  545. if (res.data && Array.isArray(res.data) && res.data.length > 0) {
  546. const newMessages = res.data.map((item: AnyObject) => {
  547. const msg = transformMessage(item);
  548. // 对 AI 和医生的文本消息进行 Markdown 解析
  549. if (
  550. (msg.sender === "agent" || msg.sender === "human") &&
  551. msg.messageType === "1" &&
  552. msg.messageContent
  553. ) {
  554. msg.messageContent = parseMarkdown(msg.messageContent);
  555. }
  556. return msg;
  557. });
  558. const allMessages = [...this.data.messages, ...newMessages];
  559. this.setData({ messages: allMessages });
  560. // 检查是否有真正的咨询结束消息(排除30分钟提醒消息)
  561. const hasEndMessage = newMessages.some((msg: ConsultMessage) =>
  562. isConsultEndMessage(msg)
  563. );
  564. // 如果收到真正的咨询结束消息,更新状态并停止轮询
  565. // 注意:30分钟提醒消息不会触发此逻辑,会继续轮询等待真正的结束消息
  566. if (hasEndMessage && !this.data.consultEnded) {
  567. this.setData({ consultEnded: true });
  568. wx.setStorageSync("consultEnded", true);
  569. this._stopPolling();
  570. // 收起键盘
  571. wx.hideKeyboard?.();
  572. // 重置底部位置为正常值(tabbar 高度 + 安全区高度)
  573. const safeBottomRpx = calculateSafeBottomRpx();
  574. const tabBarHeight = 100; // rpx
  575. const normalBottom = tabBarHeight + safeBottomRpx;
  576. // 通知父组件重置 paddingBottom
  577. this.triggerEvent("boxBottom", { inputBoxBottom: normalBottom });
  578. // 通知父组件显示guide菜单组件
  579. this.triggerEvent("consultEvent", { type: "end" });
  580. }
  581. //如果有最新消息要滚动到底部
  582. this._scrollToBottom();
  583. }
  584. } catch (error: any) {
  585. wx.showToast({
  586. title: error?.errMsg || "获取最新消息失败",
  587. icon: "none",
  588. });
  589. }
  590. },
  591. // 发送消息到后端
  592. async _sendMessage(messageType: "1" | "2", messageContent: string) {
  593. const consultId = wx.getStorageSync("consultId");
  594. if (!consultId) {
  595. wx.showToast({ title: "咨询ID不存在", icon: "none" });
  596. return;
  597. }
  598. try {
  599. await Post(`/consultManage/sendConsultMsg`, {
  600. consultRecordId: consultId,
  601. messageType,
  602. messageContent,
  603. }).then(() => {
  604. // 发送成功后获取最新消息
  605. // 重置轮询定时器,避免短时间内重复调用
  606. this._stopPolling();
  607. this._getLatestMessages();
  608. // 重新启动轮询,避免重复调用
  609. setTimeout(() => {
  610. if (!this.data.consultEnded) {
  611. this._startPolling();
  612. }
  613. }, 5000);
  614. });
  615. } catch (error: any) {
  616. wx.showToast({
  617. title: error?.errMsg || "发送失败,请重试",
  618. icon: "none",
  619. });
  620. }
  621. },
  622. async sendText() {
  623. const text = this.data.inputText.trim();
  624. // 至少要有一个内容才能发送
  625. if (!text) {
  626. wx.showToast({ title: "发送内容不能为空", icon: "none" });
  627. // 如果键盘未展开(inputFocus 为 false),不应该聚焦输入框和展开键盘
  628. // 只显示提示即可
  629. return;
  630. }
  631. const consultId = wx.getStorageSync("consultId");
  632. // 先添加用户消息到界面
  633. const messageId = `user-text-${Date.now()}`;
  634. this._appendMessage({
  635. id: messageId,
  636. consultRecordId: consultId || 0,
  637. sender: "user",
  638. sendType: "1",
  639. messageType: "1",
  640. messageContent: text,
  641. });
  642. // 平滑滚动到底部,确保新消息可见
  643. this._scrollToBottom();
  644. // 发送信息
  645. this._sendMessage("1", text);
  646. // 保存当前键盘状态
  647. const wasFocused = this.data.inputFocus;
  648. const currentKeyboardHeight = this.data._keyboardHeight;
  649. // 清空输入框,保持键盘展开状态(只有在键盘已展开时才保持)
  650. // 同时重置高度为最小高度,确保立即恢复
  651. this.setData({
  652. inputText: "",
  653. textareaHeight: 80, // 重置为最小高度
  654. });
  655. // 如果之前键盘是展开的,保持键盘展开状态;如果键盘是收起的,不要聚焦
  656. if (!wasFocused) {
  657. // 键盘未展开,不需要聚焦,保持当前状态即可
  658. this.setData({
  659. inputFocus: false,
  660. keepFocus: false,
  661. });
  662. } else {
  663. // 键盘已展开,保持聚焦状态
  664. // 但不需要手动触发聚焦,因为已经聚焦了
  665. // 只需要确保键盘位置正确
  666. if (currentKeyboardHeight > 0) {
  667. this._updateInputPosition(currentKeyboardHeight);
  668. }
  669. }
  670. },
  671. async chooseImage() {
  672. // 保存当前焦点状态,选择图片后恢复
  673. const wasFocused = this.data.inputFocus;
  674. const currentKeyboardHeight = this.data._keyboardHeight;
  675. // 临时收起键盘,选择图片需要系统界面
  676. this._hideKeyboardAndUpdatePosition();
  677. try {
  678. const res = await wx.chooseMedia({
  679. count: 1,
  680. mediaType: ["image"],
  681. sourceType: ["album", "camera"],
  682. });
  683. const files = res.tempFiles ?? [];
  684. const file = files[0];
  685. if (!file?.tempFilePath) return;
  686. const imagePath = file.tempFilePath;
  687. // 直接发送图片
  688. await this._sendImageMessage(imagePath);
  689. // 如果之前键盘是展开的,选择图片后恢复键盘
  690. if (wasFocused) {
  691. wx.nextTick?.(() => {
  692. setTimeout(() => {
  693. this.setData({
  694. inputFocus: true,
  695. keepFocus: true,
  696. });
  697. // 恢复键盘位置
  698. if (currentKeyboardHeight > 0) {
  699. this._updateInputPosition(currentKeyboardHeight);
  700. }
  701. }, 200);
  702. });
  703. }
  704. } catch (error: any) {
  705. // 用户取消选择图片时不提示错误
  706. if (error.errMsg && !error.errMsg.includes("cancel")) {
  707. console.error("选择图片失败", error);
  708. }
  709. // 取消时也恢复键盘(如果之前是展开的)
  710. if (wasFocused) {
  711. wx.nextTick?.(() => {
  712. setTimeout(() => {
  713. this.setData({
  714. inputFocus: true,
  715. keepFocus: true,
  716. });
  717. // 恢复键盘位置
  718. if (currentKeyboardHeight > 0) {
  719. this._updateInputPosition(currentKeyboardHeight);
  720. }
  721. }, 200);
  722. });
  723. }
  724. }
  725. },
  726. // 发送图片
  727. async _sendImageMessage(imagePath: string) {
  728. const consultId = wx.getStorageSync("consultId");
  729. try {
  730. // 先添加图片消息到界面(显示本地路径)
  731. const messageId = `user-image-${Date.now()}`;
  732. this._appendMessage({
  733. id: messageId,
  734. consultRecordId: consultId || 0,
  735. sender: "user",
  736. sendType: "1",
  737. messageType: "2",
  738. messageContent: imagePath, // 先用本地路径,上传后更新
  739. });
  740. // 上传图片
  741. const imageUrl = await upload({
  742. params: { name: "file", file: imagePath },
  743. transform({ data }: any) {
  744. return data?.url || data;
  745. },
  746. });
  747. // 发送图片消息
  748. await this._sendMessage("2", imageUrl);
  749. // 更新消息中的图片URL(从本地路径更新为服务器URL)
  750. const messages = this.data.messages;
  751. const messageIndex = messages.findIndex(
  752. (msg: ConsultMessage) => msg.id === messageId
  753. );
  754. if (messageIndex !== -1) {
  755. messages[messageIndex].messageContent = imageUrl;
  756. this.setData({ messages });
  757. }
  758. // 平滑滚动到底部,确保新消息可见
  759. this._scrollToBottom();
  760. } catch (error: any) {
  761. wx.showToast({
  762. title: error?.errMsg || "图片上传失败",
  763. icon: "none",
  764. });
  765. }
  766. },
  767. // 预览图片
  768. previewImage(e: any) {
  769. const currentUrl = e.currentTarget.dataset.url;
  770. // 获取所有图片消息的 URL 列表
  771. const urls = this.data.messages
  772. .filter(
  773. (msg: ConsultMessage) => msg.messageType === "2" && msg.messageContent
  774. )
  775. .map((msg: ConsultMessage) => msg.messageContent!);
  776. wx.previewImage({
  777. current: currentUrl, // 当前显示图片的链接
  778. urls: urls.length > 0 ? urls : [currentUrl], // 需要预览的图片链接列表
  779. fail: (err) => {
  780. wx.showToast({
  781. title: err?.errMsg || "预览图片失败",
  782. icon: "none",
  783. });
  784. },
  785. });
  786. },
  787. _appendMessage(message: ConsultMessage) {
  788. // 把获取的最新的消息追加到所有消息后面
  789. const messages = [...this.data.messages, message];
  790. this.setData({ messages });
  791. },
  792. },
  793. });