chat.vue 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  1. <template>
  2. <view class="chat-container" :style="{ '--font-scale': fontScale }">
  3. <!-- 导航栏 -->
  4. <view class="chat-nav" :class="'mascot-' + mascotCode">
  5. <view class="nav-back" @click="goBack">
  6. <text class="nav-back-icon">‹</text>
  7. </view>
  8. <view class="nav-actions">
  9. <view class="mascot-badge" v-if="mascotCode && !isNutrition" @click="showConversations = !showConversations">
  10. <text class="mascot-badge-icon">{{ mascotIcon }}</text>
  11. <text class="mascot-badge-name">{{ mascotName }}</text>
  12. </view>
  13. <text class="nav-action" @click="showConversations = !showConversations" v-else>☰</text>
  14. </view>
  15. </view>
  16. <!-- 会员状态条:过期 / 临期时给出续费入口(T-F2) -->
  17. <view class="member-status-bar" v-if="memberStatusText" @click="goRenew">
  18. <text class="member-status-text">{{ memberStatusText }}</text>
  19. <text class="member-status-action">去续费 ›</text>
  20. </view>
  21. <!-- 会话列表(侧拉) -->
  22. <view class="conv-overlay" v-if="showConversations" @click="showConversations = false"></view>
  23. <view class="conv-sidebar" :class="{ 'conv-sidebar-open': showConversations }">
  24. <view class="conv-header">
  25. <text class="conv-header-title">会话列表</text>
  26. <text class="conv-header-new" @click="newConversation">+ 新会话</text>
  27. </view>
  28. <scroll-view class="conv-list" scroll-y>
  29. <view class="conv-item" v-for="conv in conversations" :key="conv.id"
  30. :class="{ 'conv-item-active': conv.id === currentConversationId }"
  31. @click="switchConversation(conv.id)">
  32. <text class="conv-item-name">{{ conv.name || '新会话' }}</text>
  33. <text class="conv-item-time">{{ formatTime(conv.updated_at) }}</text>
  34. </view>
  35. <BaseEmpty v-if="conversations.length === 0" text="暂无会话" icon="💬" />
  36. </scroll-view>
  37. </view>
  38. <!-- 消息列表 -->
  39. <scroll-view class="message-list" scroll-y :scroll-into-view="scrollToId" scroll-with-animation
  40. @scrolltoupper="loadMoreMessages" id="messageList">
  41. <view class="message-list-inner">
  42. <view class="welcome-card" v-if="messages.length === 0 && !sending">
  43. <view class="welcome-icon">{{ mascotIcon || (isNutrition ? '🥗' : (isHealthCoach ? '💡' : '🤖')) }}</view>
  44. <text class="welcome-title">{{ isNutrition ? '你好!我是营养助手' : (isHealthCoach ? ('你好!我是' + (mascotName || '健康教练')) : (isButler ? '你好!我是健康管家' : ('你好!我是' + (mascotName || '家庭助手')))) }}</text>
  45. <text class="welcome-desc">{{ welcomeSubtitle }}</text>
  46. <view class="welcome-suggestions">
  47. <view class="welcome-suggestion" v-if="!isNutrition && !isHealthCoach" @click="quickQuestion('小明最近任务完成怎么样?')">
  48. <text class="suggestion-icon">📋</text>
  49. <text class="suggestion-text">小明最近任务完成怎么样?</text>
  50. </view>
  51. <view class="welcome-suggestion" v-if="!isNutrition && !isHealthCoach" @click="quickQuestion('我家家庭成员的能量评分怎么样?')">
  52. <text class="suggestion-icon">⚡</text>
  53. <text class="suggestion-text">家庭成员的能量评分怎么样?</text>
  54. </view>
  55. <view class="welcome-suggestion" v-if="!isNutrition && !isHealthCoach" @click="quickQuestion('今天有什么需要我做的事情?')">
  56. <text class="suggestion-icon">✅</text>
  57. <text class="suggestion-text">今天有什么需要我做的事情?</text>
  58. </view>
  59. <view class="welcome-suggestion" v-if="isNutrition" @click="quickQuestion('根据报告,家庭成员需要补充哪些营养?')">
  60. <text class="suggestion-icon">🥦</text>
  61. <text class="suggestion-text">根据报告,家庭成员需要补充哪些营养?</text>
  62. </view>
  63. <view class="welcome-suggestion" v-if="isNutrition" @click="quickQuestion('有哪些食物或产品推荐?')">
  64. <text class="suggestion-icon">🛒</text>
  65. <text class="suggestion-text">有哪些食物或产品推荐?</text>
  66. </view>
  67. <view class="welcome-suggestion" v-if="isHealthCoach" @click="quickQuestion('家人挑食怎么办?')">
  68. <text class="suggestion-icon">🍽️</text>
  69. <text class="suggestion-text">家人挑食怎么办?</text>
  70. </view>
  71. <view class="welcome-suggestion" v-if="isHealthCoach" @click="quickQuestion('家人总生病,是不是抵抗力差?')">
  72. <text class="suggestion-icon">🤧</text>
  73. <text class="suggestion-text">家人总生病,是不是抵抗力差?</text>
  74. </view>
  75. <view class="welcome-suggestion" v-if="isHealthCoach" @click="quickQuestion('怎么知道家人是什么体质?')">
  76. <text class="suggestion-icon">🔍</text>
  77. <text class="suggestion-text">怎么知道家人是什么体质?</text>
  78. </view>
  79. <view class="welcome-suggestion" v-if="isButler" @click="quickQuestion('我家成员肠道菌群怎么样?')">
  80. <text class="suggestion-icon">🦠</text>
  81. <text class="suggestion-text">我家成员肠道菌群怎么样?</text>
  82. </view>
  83. <view class="welcome-suggestion" v-if="isButler" @click="quickQuestion('怎么改善家人挑食问题?')">
  84. <text class="suggestion-icon">🥗</text>
  85. <text class="suggestion-text">怎么改善家人挑食问题?</text>
  86. </view>
  87. <view class="welcome-suggestion" v-if="isButler" @click="quickQuestion('需要补充什么营养素?')">
  88. <text class="suggestion-icon">💊</text>
  89. <text class="suggestion-text">需要补充什么营养素?</text>
  90. </view>
  91. </view>
  92. </view>
  93. <view class="message-group" v-for="(msg, idx) in messages" :key="msg.id">
  94. <!-- 用户消息 -->
  95. <view class="message message-user" v-if="msg.query">
  96. <view class="message-bubble user-bubble">{{ msg.query }}</view>
  97. </view>
  98. <!-- 回复 -->
  99. <view class="message message-ai" v-if="msg.answer">
  100. <view class="message-avatar">{{ isHealthCoach ? '🎯' : (isButler ? '🏥' : (mascotIcon || '🤖')) }}</view>
  101. <view class="message-bubble ai-bubble">
  102. <text class="ai-answer-text">{{ msg.answer }}</text>
  103. <!-- 推荐卡片 -->
  104. <view class="rec-list" v-if="msg.recommendations && msg.recommendations.length > 0">
  105. <view class="rec-card" v-for="(rec, ri) in msg.recommendations" :key="ri" @click="gotoRec(rec)">
  106. <image class="rec-cover" v-if="rec.coverImage" :src="getImageUrl(rec.coverImage)" mode="aspectFill" />
  107. <view class="rec-info">
  108. <text class="rec-type-tag">{{ rec.type === 'product' ? '商品' : rec.type === 'activity' ? '活动' : '文章' }}</text>
  109. <text class="rec-name">{{ rec.name }}</text>
  110. <text class="rec-desc">{{ rec.description }}</text>
  111. <text class="rec-price" v-if="rec.price">¥{{ rec.price }}</text>
  112. </view>
  113. </view>
  114. </view>
  115. <!-- 任务卡片 -->
  116. <view class="task-list" v-if="msg.tasks && msg.tasks.length > 0">
  117. <TaskCard v-for="(task, ti) in msg.tasks" :key="ti" :task="task" :conversationId="currentConversationId" @accepted="onTaskAccepted" />
  118. </view>
  119. <!-- 报告来源标识 -->
  120. <view class="source-label" v-if="msg.sourceReport">
  121. 来源:{{ msg.sourceReport.type === 'nutrition' ? '营养报告' : '测评报告' }} #{{ msg.sourceReport.id }}
  122. </view>
  123. </view>
  124. </view>
  125. </view>
  126. <!-- 加载中 -->
  127. <view class="message message-ai" v-if="sending">
  128. <view class="message-avatar">{{ mascotIcon || '🤖' }}</view>
  129. <view class="message-bubble ai-bubble typing">
  130. <text class="typing-dot">.</text>
  131. <text class="typing-dot">.</text>
  132. <text class="typing-dot">.</text>
  133. </view>
  134. </view>
  135. <view id="scrollBottom"></view>
  136. </view>
  137. </scroll-view>
  138. <!-- 输入区 -->
  139. <view class="chat-input-area">
  140. <view class="chat-input-wrap">
  141. <input class="chat-input" v-model="inputText" :placeholder="inputPlaceholder"
  142. :disabled="sending || gateBlocked" @confirm="sendMessage" confirm-type="send" />
  143. </view>
  144. <view class="chat-voice-btn" :class="{ 'voice-recording': isRecording }" @touchstart="startVoiceRecord" @touchend="stopVoiceRecord">
  145. <text class="voice-icon">{{ isRecording ? '🔴' : '🎤' }}</text>
  146. </view>
  147. <view class="chat-send-btn" :class="{ 'chat-send-active': inputText.trim() }"
  148. @click="sendMessage">
  149. <text class="send-icon">➤</text>
  150. </view>
  151. </view>
  152. <view class="chat-disclaimer">本服务为生成内容,结果仅供参考</view>
  153. <!-- 配额进度条 -->
  154. <view class="quota-bar-wrapper" v-if="aiChatQuota && !aiChatQuota.unlimited">
  155. <quota-progress-bar :remaining="aiChatQuota.remaining || 0" :total="aiChatQuota.total || 3" name="今日AI对话剩余"></quota-progress-bar>
  156. </view>
  157. <!-- 升级引导弹窗 -->
  158. <upgrade-guide-modal ref="upgradeGuideModal"></upgrade-guide-modal>
  159. </view>
  160. </template>
  161. <script>
  162. import { aiSendMessage, aiGetConversations, aiGetMessages, aiDeleteConversation, aiSendNutritionMessage, aiSendHealthCoachMessage, aiSendHealthButlerMessage, aiGateStatus, getMyMembership, getAllQuotaStatus, reportAppEnter
  163. } from '../../utils/api.js'
  164. import { sttTranscribe } from '../../utils/api.js'
  165. import BaseEmpty from '../../components/BaseEmpty.vue'
  166. import TaskCard from '@/pages/ai/components/AITaskCard.vue'
  167. import QuotaProgressBar from '@/pages/ai/components/QuotaProgressBar.vue'
  168. import UpgradeGuideModal from '@/pages/ai/components/UpgradeGuideModal.vue'
  169. import config from '@/config.js'
  170. import { parseDate } from '../../utils/format.js'
  171. import fontScaleMixin from '@/mixins/font-scale.js'
  172. export default {
  173. mixins: [fontScaleMixin],
  174. components: { BaseEmpty, TaskCard, QuotaProgressBar, UpgradeGuideModal },
  175. data() {
  176. return {
  177. inputText: '',
  178. messages: [],
  179. conversations: [],
  180. currentConversationId: '',
  181. sending: false,
  182. showConversations: false,
  183. scrollToId: '',
  184. pageLoaded: false,
  185. pendingFirstMessage: '',
  186. fromPage: '',
  187. mode: '',
  188. reportId: '',
  189. recommendations: [],
  190. mascotCode: '',
  191. mascotName: '',
  192. mascotIcon: '',
  193. isRecording: false,
  194. recorderManager: null,
  195. aiChatQuota: null,
  196. // 会员门禁(/api/ai/gate 返回的 AiGateResult)
  197. memberGate: null,
  198. gateStatus: '',
  199. gateBlocked: false,
  200. // 临期提醒阈值(天),T-F2 状态条使用
  201. nearExpiryDays: 7
  202. }
  203. },
  204. computed: {
  205. isNutrition: function() {
  206. return this.mode === 'nutrition'
  207. },
  208. isHealthCoach: function() {
  209. return this.mode === 'health'
  210. },
  211. isButler: function() {
  212. return this.mode === 'butler'
  213. },
  214. welcomeSubtitle: function() {
  215. if (this.isNutrition) {
  216. return '我可以基于菌群检测报告,为你提供个性化的营养建议和推荐'
  217. }
  218. if (this.isHealthCoach) {
  219. return '陪伴家庭成员健康成长,用提问帮你找到答案'
  220. }
  221. if (this.isButler) {
  222. return '专属健康管家,基于知识库提供个性化健康建议'
  223. }
  224. if (this.fromPage) {
  225. var pageNames = {
  226. 'pages/body/index': '身',
  227. 'pages/wisdom/index': '智',
  228. 'pages/mind/index': '心',
  229. 'pages/index/index': '首页',
  230. 'pages/index/parent-index': '首页',
  231. 'pages/index/child-index': '首页',
  232. 'pages/profile/profile': '我的',
  233. 'pages/profile/children': '我的',
  234. 'pages/shop/index': '商城',
  235. 'pages/discover/index': '发现'
  236. }
  237. var pageName = pageNames[this.fromPage] || this.fromPage
  238. return '从 ' + pageName + ' 发起,我可以帮你了解:'
  239. }
  240. return '我可以帮你了解家庭成员的成长情况,比如:'
  241. },
  242. inputPlaceholder: function() {
  243. if (this.gateStatus === 'MEMBER_EXPIRED') return '会员已到期,续费后可继续对话'
  244. if (this.gateStatus === 'UPGRADE_REQUIRED') return '开通会员后即可对话'
  245. return '问我关于家庭和成员的问题...'
  246. },
  247. // T-F2 会员状态条:过期 / 临期才有文案
  248. memberStatusText: function() {
  249. if (!this.memberGate) return ''
  250. if (this.gateStatus === 'MEMBER_EXPIRED') {
  251. var end = this.memberGate.memberExpireTime || this.memberGate.endDate
  252. var day = this.formatGateDate(end)
  253. return day ? ('会员已于 ' + day + ' 到期') : '会员已到期'
  254. }
  255. if (this.gateStatus === 'ALLOW' && this.memberGate.isActive) {
  256. var remain = this.memberGate.daysRemaining
  257. if (typeof remain === 'number' && remain >= 0 && remain <= this.nearExpiryDays) {
  258. // 后端可能返回小数(按毫秒折算),展示向上取整,避免「剩余 0 天」却仍可用
  259. return '会员即将到期(剩余 ' + Math.ceil(remain) + ' 天)'
  260. }
  261. }
  262. return ''
  263. }
  264. },
  265. onLoad: function(options) {
  266. reportAppEnter('ai');
  267. this.mode = options.mode || ''
  268. this.fromPage = options.fromPage ? decodeURIComponent(options.fromPage) : ''
  269. this.reportId = options.reportId || ''
  270. if (options.firstMessage) {
  271. this.pendingFirstMessage = decodeURIComponent(options.firstMessage)
  272. }
  273. // 会员门禁:统一走 /api/ai/gate
  274. // ALLOW → 正常加载;UPGRADE_REQUIRED → 引导升级且不加载会话;MEMBER_EXPIRED → 可看历史但不可新建/发送
  275. this.checkMemberGate(true)
  276. // 加载 AI 配额(BASIC用户可见)
  277. var selfQuota = this
  278. getAllQuotaStatus().then(function(res) {
  279. if (res.data && res.data.AI_CHAT) {
  280. selfQuota.aiChatQuota = res.data.AI_CHAT
  281. }
  282. }).catch(function() {})
  283. },
  284. onShow() {
  285. if (this.pageLoaded) {
  286. // 从升级/续费页返回等场景:重新查门禁,按最新状态决定能否加载/继续对话
  287. this.checkMemberGate(false)
  288. }
  289. this.pageLoaded = true
  290. },
  291. methods: {
  292. goBack() {
  293. uni.navigateBack()
  294. },
  295. // 查询会员门禁;autoPrompt=true 时按 status 主动弹引导弹窗(首次进入)
  296. checkMemberGate(autoPrompt) {
  297. var self = this
  298. aiGateStatus().then(function(res) {
  299. self.applyMemberGate((res && res.data) || {}, autoPrompt)
  300. }).catch(function(e) {
  301. // 门禁接口不可用(后端未发布 / 网络异常)时回退旧口径,避免误伤有效会员。
  302. // 真实权限仍由后端 AI 端点兜底,这里只是展示层降级。
  303. console.warn('[AI] aiGateStatus 失败,回退 getMyMembership', e && e.code)
  304. getMyMembership().then(function(res) {
  305. self.applyMemberGate(self.buildLegacyGate((res && res.data) || {}), autoPrompt)
  306. }).catch(function() {
  307. self.applyMemberGate({ status: 'UPGRADE_REQUIRED', canUse: false }, autoPrompt)
  308. })
  309. })
  310. },
  311. // /api/ai/gate 不可用时的旧会员接口降级映射
  312. // 注意:旧接口不区分「从未付费 / 曾付费已过期」,也不能给出剩余天数,
  313. // 因此 daysRemaining / isActive 置空(状态条据此跳过临期提醒),避免展示假数据。
  314. buildLegacyGate(membership) {
  315. var level = membership.memberLevel || 'FREE'
  316. var allowed = level !== 'FREE'
  317. return {
  318. enabled: true,
  319. status: allowed ? 'ALLOW' : 'UPGRADE_REQUIRED',
  320. canUse: allowed,
  321. canViewHistory: false,
  322. memberLevel: level,
  323. isActive: null,
  324. memberExpireTime: membership.memberExpireTime || null,
  325. endDate: membership.endDate || membership.memberExpireTime || null,
  326. daysRemaining: null
  327. }
  328. },
  329. applyMemberGate(gate, autoPrompt) {
  330. // status 缺失(gate 接口返回空 data / 5001 无家庭兜底)时 fail-closed:
  331. // 不默认放行,沿用上一次已知状态;首次遇到则按未开通处理(不主动弹窗,避免误伤)。
  332. var status = gate.status
  333. if (!status) {
  334. if (gate.canUse === true) status = 'ALLOW'
  335. else if (gate.canUse === false) status = 'UPGRADE_REQUIRED'
  336. else status = this.gateStatus || 'UPGRADE_REQUIRED'
  337. }
  338. this.memberGate = gate
  339. this.gateStatus = status
  340. this.gateBlocked = status !== 'ALLOW'
  341. if (status === 'UPGRADE_REQUIRED') {
  342. // 从未付费:不加载会话,直接引导升级
  343. if (autoPrompt) this.showGateModal('hard')
  344. return
  345. }
  346. // ALLOW 与 MEMBER_EXPIRED 都可查看历史会话
  347. this.loadMascot()
  348. this.loadConversations()
  349. if (status === 'MEMBER_EXPIRED') {
  350. if (autoPrompt) this.showGateModal('expired')
  351. return
  352. }
  353. if (this.pendingFirstMessage) {
  354. var self = this
  355. this.$nextTick(function() {
  356. self.inputText = self.pendingFirstMessage
  357. self.pendingFirstMessage = ''
  358. self.sendMessage()
  359. })
  360. }
  361. },
  362. // 加载用户 mascot 设置(福宝/浠宝)
  363. loadMascot() {
  364. var userInfo = uni.getStorageSync('userInfo')
  365. if (!userInfo) return
  366. if (userInfo.mascot === 'xibao') {
  367. this.mascotCode = 'xibao'
  368. this.mascotName = '浠宝'
  369. this.mascotIcon = '🌟'
  370. } else if (userInfo.mascot === 'fubao') {
  371. this.mascotCode = 'fubao'
  372. this.mascotName = '福宝'
  373. this.mascotIcon = '💪'
  374. }
  375. },
  376. // type: soft | hard | expired
  377. showGateModal(type) {
  378. var self = this
  379. this.$nextTick(function() {
  380. var modal = self.$refs.upgradeGuideModal
  381. if (!modal) return
  382. modal.type = type
  383. modal.quotaType = ''
  384. modal.show()
  385. })
  386. },
  387. goRenew() {
  388. uni.navigateTo({ url: '/pages/membership/upgrade' })
  389. },
  390. // 门禁日期展示:yyyy-MM-dd(iOS 安全解析走 parseDate,兼容时间戳/ISO/Java 格式)
  391. formatGateDate(value) {
  392. var d = parseDate(value)
  393. if (!d) return ''
  394. var m = d.getMonth() + 1
  395. var day = d.getDate()
  396. return d.getFullYear() + '-' + (m < 10 ? '0' + m : m) + '-' + (day < 10 ? '0' + day : day)
  397. },
  398. startVoiceRecord() {
  399. if (this.isRecording) return
  400. if (this.gateBlocked) {
  401. this.showGateModal(this.gateStatus === 'MEMBER_EXPIRED' ? 'expired' : 'hard')
  402. return
  403. }
  404. this.recorderManager = uni.getRecorderManager()
  405. var self = this
  406. this.recorderManager.onStop(function(res) {
  407. self.isRecording = false
  408. uni.showLoading({ title: '语音识别中...', mask: true })
  409. sttTranscribe(res.tempFilePath).then(function(text) {
  410. uni.hideLoading()
  411. self.inputText = text
  412. }).catch(function(err) {
  413. uni.hideLoading()
  414. uni.showToast({ title: '语音识别失败', icon: 'none' })
  415. })
  416. })
  417. this.recorderManager.onError(function() {
  418. self.isRecording = false
  419. uni.showToast({ title: '录音失败', icon: 'none' })
  420. })
  421. this.recorderManager.start({ duration: 60000, format: 'mp3' })
  422. this.isRecording = true
  423. },
  424. stopVoiceRecord() {
  425. if (this.recorderManager) {
  426. this.recorderManager.stop()
  427. }
  428. },
  429. onTaskAccepted() {
  430. this.loadConversations()
  431. },
  432. async loadConversations() {
  433. try {
  434. const res = await aiGetConversations()
  435. this.conversations = res.data || []
  436. } catch (e) {
  437. console.log('加载会话列表失败', e)
  438. }
  439. },
  440. async switchConversation(convId) {
  441. this.currentConversationId = convId
  442. this.showConversations = false
  443. this.messages = []
  444. this.$nextTick(() => {
  445. this.scrollToBottom()
  446. })
  447. try {
  448. const res = await aiGetMessages({ conversationId: convId })
  449. this.messages = res.data || []
  450. this.$nextTick(() => {
  451. this.scrollToBottom()
  452. })
  453. } catch (e) {
  454. console.log('加载消息失败', e)
  455. }
  456. },
  457. newConversation() {
  458. // 过期 / 未开通:不可新建会话(历史仍可查看与删除)
  459. if (this.gateStatus === 'MEMBER_EXPIRED' || this.gateStatus === 'UPGRADE_REQUIRED') {
  460. this.showGateModal(this.gateStatus === 'MEMBER_EXPIRED' ? 'expired' : 'hard')
  461. return
  462. }
  463. this.currentConversationId = ''
  464. this.showConversations = false
  465. this.messages = []
  466. this.inputText = ''
  467. this.$nextTick(() => {
  468. this.scrollToBottom()
  469. })
  470. },
  471. async sendMessage() {
  472. const text = this.inputText.trim()
  473. if (!text || this.sending) return
  474. // 会员门禁拦截:ALLOW 以外不发请求,直接弹对应引导弹窗
  475. if (this.gateBlocked) {
  476. this.showGateModal(this.gateStatus === 'MEMBER_EXPIRED' ? 'expired' : 'hard')
  477. return
  478. }
  479. // BASIC 配额检查(unlimited=true 不拦截)
  480. if (this.aiChatQuota && !this.aiChatQuota.unlimited && this.aiChatQuota.remaining <= 0) {
  481. this.$refs.upgradeGuideModal.type = 'soft'
  482. this.$refs.upgradeGuideModal.quotaType = 'AI_CHAT'
  483. this.$refs.upgradeGuideModal.total = this.aiChatQuota.total
  484. this.$refs.upgradeGuideModal.show()
  485. return
  486. }
  487. // 立即显示用户消息
  488. const tempMsg = { id: 'temp_' + Date.now(), query: text, answer: '' }
  489. this.messages.push(tempMsg)
  490. this.inputText = ''
  491. this.sending = true
  492. this.$nextTick(() => {
  493. this.scrollToBottom()
  494. })
  495. try {
  496. var params = {
  497. query: text,
  498. conversationId: this.currentConversationId
  499. }
  500. if (this.reportId) {
  501. params.reportId = this.reportId
  502. }
  503. var res, data
  504. if (this.mode === 'nutrition') {
  505. res = await aiSendNutritionMessage(params)
  506. data = res.data || {}
  507. const lastMsg = this.messages[this.messages.length - 1]
  508. if (lastMsg) {
  509. lastMsg.answer = data.answer || ''
  510. lastMsg.recommendations = data.recommendations || []
  511. lastMsg.tasks = data.tasks || []
  512. if (this.reportId) {
  513. lastMsg.sourceReport = { id: this.reportId, type: 'nutrition' }
  514. }
  515. }
  516. } else if (this.mode === 'health') {
  517. res = await aiSendHealthCoachMessage(params)
  518. data = res.data || {}
  519. const lastMsg = this.messages[this.messages.length - 1]
  520. if (lastMsg) {
  521. lastMsg.answer = data.answer || ''
  522. lastMsg.recommendations = data.recommendations || []
  523. lastMsg.tasks = data.tasks || []
  524. }
  525. } else if (this.mode === 'butler') {
  526. // 传递 memberId 让健康管家能加载家庭上下文
  527. var butlerParams = Object.assign({}, params)
  528. butlerParams.memberId = uni.getStorageSync('currentChildId') || null
  529. res = await aiSendHealthButlerMessage(butlerParams)
  530. data = res.data || {}
  531. const butlerLastMsg = this.messages[this.messages.length - 1]
  532. if (butlerLastMsg) {
  533. butlerLastMsg.answer = data.answer || ''
  534. butlerLastMsg.recommendations = data.recommendations || []
  535. butlerLastMsg.tasks = data.tasks || []
  536. }
  537. } else {
  538. res = await aiSendMessage(params)
  539. data = res.data || {}
  540. const lastMsg = this.messages[this.messages.length - 1]
  541. if (lastMsg) {
  542. lastMsg.answer = data.answer || ''
  543. lastMsg.recommendations = data.recommendations || []
  544. lastMsg.tasks = data.tasks || []
  545. if (this.reportId) {
  546. lastMsg.sourceReport = { id: this.reportId, type: 'assessment' }
  547. }
  548. }
  549. }
  550. // 更新 conversationId(新建会话时 Dify 返回)
  551. if (data.conversationId && !this.currentConversationId) {
  552. this.currentConversationId = data.conversationId
  553. // 刷新会话列表
  554. this.loadConversations()
  555. }
  556. } catch (e) {
  557. var errCode = e && e.code
  558. if (errCode === 46003 || errCode === 46004) {
  559. // 会员门禁:撤掉未落库的乐观消息,把输入还给用户,改为弹专用引导弹窗
  560. const lastMsg = this.messages[this.messages.length - 1]
  561. if (lastMsg && String(lastMsg.id).indexOf('temp_') === 0) {
  562. this.messages.pop()
  563. }
  564. if (!this.inputText) this.inputText = text
  565. if (errCode === 46004) {
  566. this.gateStatus = 'MEMBER_EXPIRED'
  567. } else {
  568. this.gateStatus = 'UPGRADE_REQUIRED'
  569. }
  570. this.gateBlocked = true
  571. // 保证状态条依赖的 memberGate 不为空(会话中途降级时也能显示续费入口)
  572. // 用新对象覆盖,避免直接改写接口返回体(可能被 3 秒去重缓存共享)
  573. this.memberGate = Object.assign({}, this.memberGate || {}, {
  574. status: this.gateStatus,
  575. canUse: false
  576. })
  577. this.showGateModal(errCode === 46004 ? 'expired' : 'hard')
  578. return
  579. }
  580. // 显示错误(发送类走 _noToast,这里补回后端原话,避免只剩通用兜底)
  581. const lastMsg = this.messages[this.messages.length - 1]
  582. if (lastMsg) {
  583. lastMsg.answer = '抱歉,我暂时无法回答,请稍后再试。'
  584. }
  585. uni.showToast({ title: (e && e.message) || '发送失败,请稍后再试', icon: 'none' })
  586. } finally {
  587. this.sending = false
  588. this.$nextTick(() => {
  589. this.scrollToBottom()
  590. })
  591. }
  592. },
  593. quickQuestion(text) {
  594. this.inputText = text
  595. this.sendMessage()
  596. },
  597. gotoRec(rec) {
  598. if (rec.url) {
  599. uni.navigateTo({ url: rec.url })
  600. }
  601. },
  602. loadMoreMessages() {
  603. // 分页加载历史(当前简化)
  604. },
  605. scrollToBottom() {
  606. this.scrollToId = 'scrollBottom'
  607. },
  608. formatTime(timestamp) {
  609. if (!timestamp) return ''
  610. const d = new Date(timestamp * 1000)
  611. const now = new Date()
  612. const diff = now - d
  613. if (diff < 86400000) {
  614. return d.getHours().toString().padStart(2, '0') + ':' + d.getMinutes().toString().padStart(2, '0')
  615. }
  616. return (d.getMonth() + 1) + '/' + d.getDate()
  617. },
  618. getImageUrl: function(path) {
  619. if (!path || path === 'null' || path === 'undefined' || path === '/null') return ''
  620. var s = String(path).trim()
  621. if (!s || s === 'null' || s === '/null') return ''
  622. if (s.indexOf('http://') === 0 || s.indexOf('https://') === 0) return s
  623. return config.API_BASE_URL + (s.charAt(0) === '/' ? s : '/' + s)
  624. }
  625. }
  626. }
  627. </script>
  628. <style scoped lang="scss">
  629. .chat-container {
  630. display: flex;
  631. flex-direction: column;
  632. height: 100vh;
  633. background: var(--bg, $uni-primary-pale);
  634. position: relative;
  635. }
  636. /* 导航栏 */
  637. .chat-nav {
  638. display: flex;
  639. align-items: center;
  640. justify-content: space-between;
  641. padding: 88rpx 24rpx 16rpx;
  642. background: $app-surface;
  643. border-bottom: 1rpx solid var(--border-light, $uni-border-color-light);
  644. position: relative;
  645. z-index: 100;
  646. }
  647. .chat-nav.mascot-xibao {
  648. background: linear-gradient(135deg, $uni-primary-pale 0%, $tint-warm-edge 100%);
  649. border-bottom-color: $dim-body;
  650. }
  651. .chat-nav.mascot-xibao .chat-nav.mascot-fubao {
  652. background: linear-gradient(135deg, $dim-wealth-tint 0%, $status-warning-soft 100%);
  653. border-bottom-color: $dim-wealth;
  654. }
  655. .chat-nav.mascot-fubao .nav-back-icon {
  656. font-size: calc(40rpx * var(--font-scale, 1));
  657. color: var(--text, $uni-text-color);
  658. font-weight: 600;
  659. }
  660. .nav-actions {
  661. width: 60rpx;
  662. height: 60rpx;
  663. display: flex;
  664. align-items: center;
  665. justify-content: center;
  666. }
  667. .nav-action {
  668. font-size: calc(36rpx * var(--font-scale, 1));
  669. color: var(--text-secondary, $uni-text-color-secondary);
  670. }
  671. /* 会员状态条(过期 / 临期续费入口) */
  672. .member-status-bar {
  673. display: flex;
  674. align-items: center;
  675. justify-content: space-between;
  676. padding: 12rpx 24rpx;
  677. background: $status-warning-soft;
  678. border-bottom: 1rpx solid var(--border-light, $uni-border-color-light);
  679. }
  680. .member-status-text {
  681. font-size: calc(24rpx * var(--font-scale, 1));
  682. color: $facade-text-body;
  683. }
  684. .member-status-action {
  685. font-size: calc(24rpx * var(--font-scale, 1));
  686. color: $brand-primary;
  687. font-weight: 500;
  688. flex-shrink: 0;
  689. margin-left: 16rpx;
  690. }
  691. /* 会话列表侧拉 */
  692. .conv-overlay {
  693. position: fixed;
  694. top: 0;
  695. left: 0;
  696. right: 0;
  697. bottom: 0;
  698. background: rgba(0,0,0,0.3);
  699. z-index: 200;
  700. }
  701. .conv-sidebar {
  702. position: fixed;
  703. top: 0;
  704. right: -500rpx;
  705. width: 460rpx;
  706. height: 100vh;
  707. background: $app-surface;
  708. z-index: 210;
  709. transition: right 0.3s ease;
  710. display: flex;
  711. flex-direction: column;
  712. }
  713. .conv-sidebar-open {
  714. right: 0;
  715. }
  716. .conv-header {
  717. display: flex;
  718. justify-content: space-between;
  719. align-items: center;
  720. padding: 100rpx 24rpx 16rpx;
  721. border-bottom: 1rpx solid var(--border-light, $uni-border-color-light);
  722. }
  723. .conv-header-title {
  724. font-size: calc(28rpx * var(--font-scale, 1));
  725. font-weight: 600;
  726. color: var(--text, $uni-text-color);
  727. }
  728. .conv-header-new {
  729. font-size: calc(24rpx * var(--font-scale, 1));
  730. color: var(--color-primary, $brand-primary);
  731. font-weight: 500;
  732. }
  733. .conv-list {
  734. flex: 1;
  735. overflow-y: auto;
  736. }
  737. .conv-item {
  738. padding: 20rpx 24rpx;
  739. border-bottom: 1rpx solid var(--border-light, $uni-border-color-light);
  740. }
  741. .conv-item-active {
  742. background: rgba(249,115,22,0.06);
  743. }
  744. .conv-item-name {
  745. font-size: calc(26rpx * var(--font-scale, 1));
  746. color: var(--text, $uni-text-color);
  747. display: block;
  748. margin-bottom: 6rpx;
  749. overflow: hidden;
  750. text-overflow: ellipsis;
  751. white-space: nowrap;
  752. }
  753. .conv-item-time {
  754. font-size: calc(20rpx * var(--font-scale, 1));
  755. color: var(--muted, $app-text-subtle);
  756. }
  757. /* 消息列表 */
  758. .message-list {
  759. flex: 1;
  760. overflow-y: auto;
  761. padding: 20rpx 24rpx;
  762. }
  763. .message-list-inner {
  764. min-height: 100%;
  765. }
  766. /* 欢迎卡片 */
  767. .welcome-card {
  768. text-align: center;
  769. padding: 60rpx 20rpx 40rpx;
  770. }
  771. .welcome-icon {
  772. font-size: calc($uni-font-size-5xl * var(--font-scale, 1));
  773. margin-bottom: 20rpx;
  774. transition: transform 0.3s;
  775. }
  776. .mascot-xibao .welcome-icon {
  777. animation: welcomeFloat 3s ease-in-out infinite;
  778. }
  779. .mascot-fubao .welcome-icon {
  780. animation: welcomeFloat 3s ease-in-out infinite 0.5s;
  781. }
  782. @keyframes welcomeFloat {
  783. 0%, 100% { transform: translateY(0); }
  784. 50% { transform: translateY(-10rpx); }
  785. }
  786. .welcome-title {
  787. font-size: calc(32rpx * var(--font-scale, 1));
  788. font-weight: 600;
  789. color: var(--text, $uni-text-color);
  790. display: block;
  791. margin-bottom: 12rpx;
  792. }
  793. .welcome-desc {
  794. font-size: calc(24rpx * var(--font-scale, 1));
  795. color: var(--text-secondary, $uni-text-color-secondary);
  796. display: block;
  797. margin-bottom: 32rpx;
  798. }
  799. .welcome-suggestions {
  800. display: flex;
  801. flex-direction: column;
  802. gap: 16rpx;
  803. padding: 0 20rpx;
  804. }
  805. .welcome-suggestion {
  806. display: flex;
  807. align-items: center;
  808. background: $app-surface;
  809. padding: 20rpx 24rpx;
  810. border-radius: 16rpx;
  811. box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
  812. }
  813. .suggestion-icon {
  814. font-size: calc(28rpx * var(--font-scale, 1));
  815. margin-right: 12rpx;
  816. }
  817. .suggestion-text {
  818. font-size: calc(24rpx * var(--font-scale, 1));
  819. color: var(--text, $uni-text-color);
  820. }
  821. /* 消息 */
  822. .message {
  823. margin-bottom: 24rpx;
  824. }
  825. .message-user {
  826. display: flex;
  827. justify-content: flex-end;
  828. }
  829. .message-ai {
  830. display: flex;
  831. align-items: flex-start;
  832. }
  833. .message-avatar {
  834. width: 56rpx;
  835. height: 56rpx;
  836. font-size: calc(36rpx * var(--font-scale, 1));
  837. margin-right: 12rpx;
  838. flex-shrink: 0;
  839. display: flex;
  840. align-items: center;
  841. justify-content: center;
  842. border-radius: 50%;
  843. transition: transform 0.2s;
  844. }
  845. .mascot-xibao .message-avatar {
  846. background: linear-gradient(135deg, $uni-primary-pale 0%, $tint-warm-edge 100%);
  847. border: 2rpx solid $dim-body;
  848. }
  849. .mascot-fubao .message-avatar {
  850. background: linear-gradient(135deg, $dim-wealth-tint 0%, $status-warning-soft 100%);
  851. border: 2rpx solid $dim-wealth;
  852. }
  853. .message-bubble {
  854. max-width: 70%;
  855. padding: 16rpx 20rpx;
  856. font-size: calc(26rpx * var(--font-scale, 1));
  857. line-height: 1.6;
  858. border-radius: 16rpx;
  859. word-break: break-word;
  860. }
  861. .user-bubble {
  862. background: var(--color-primary, $brand-primary);
  863. color: $app-surface;
  864. border-bottom-right-radius: 8rpx;
  865. }
  866. .ai-bubble {
  867. background: $app-surface;
  868. color: var(--text, $uni-text-color);
  869. border-bottom-left-radius: 8rpx;
  870. box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
  871. }
  872. /* 输入区 */
  873. .chat-input-area {
  874. display: flex;
  875. align-items: center;
  876. padding: 16rpx 24rpx;
  877. padding-bottom: calc(16rpx + env(safe-area-inset-bottom));
  878. background: $app-surface;
  879. border-top: 1rpx solid var(--border-light, $uni-border-color-light);
  880. }
  881. .chat-input-wrap {
  882. flex: 1;
  883. background: var(--bg, $uni-primary-pale);
  884. border-radius: 24rpx;
  885. padding: 0 24rpx;
  886. margin-right: 12rpx;
  887. }
  888. .chat-voice-btn {
  889. width: 60rpx;
  890. height: 60rpx;
  891. border-radius: 50%;
  892. background: var(--border-light, $uni-border-color-light);
  893. display: flex;
  894. align-items: center;
  895. justify-content: center;
  896. flex-shrink: 0;
  897. margin-right: 12rpx;
  898. }
  899. .chat-voice-btn.voice-recording {
  900. background: $accent-coral;
  901. }
  902. .voice-icon {
  903. font-size: calc(28rpx * var(--font-scale, 1));
  904. }
  905. .chat-input {
  906. height: 72rpx;
  907. font-size: calc(26rpx * var(--font-scale, 1));
  908. color: var(--text, $uni-text-color);
  909. }
  910. .chat-send-btn {
  911. width: 72rpx;
  912. height: 72rpx;
  913. border-radius: 50%;
  914. background: var(--border-light, $uni-border-color-light);
  915. display: flex;
  916. align-items: center;
  917. justify-content: center;
  918. flex-shrink: 0;
  919. }
  920. .chat-send-active {
  921. background: var(--color-primary, $brand-primary);
  922. }
  923. .send-icon {
  924. font-size: calc(28rpx * var(--font-scale, 1));
  925. color: $app-surface;
  926. }
  927. /* 打字动画 */
  928. .typing {
  929. display: flex;
  930. align-items: center;
  931. gap: 4rpx;
  932. min-height: 40rpx;
  933. }
  934. .typing-dot {
  935. font-size: calc(40rpx * var(--font-scale, 1));
  936. line-height: 1;
  937. animation: typingBounce 1.4s infinite;
  938. }
  939. .typing-dot:nth-child(2) {
  940. animation-delay: 0.2s;
  941. }
  942. .typing-dot:nth-child(3) {
  943. animation-delay: 0.4s;
  944. }
  945. @keyframes typingBounce {
  946. 0%, 60%, 100% { opacity: 0.3; transform: translateY(0); }
  947. 30% { opacity: 1; transform: translateY(-8rpx); }
  948. }
  949. /* 推荐卡片 */
  950. .ai-answer-text {
  951. display: block;
  952. margin-bottom: 16rpx;
  953. line-height: 1.7;
  954. }
  955. .rec-list {
  956. border-top: 1rpx solid var(--border-light, $uni-border-color-light);
  957. padding-top: 16rpx;
  958. display: flex;
  959. flex-direction: column;
  960. gap: 12rpx;
  961. }
  962. /* 任务卡片列表 */
  963. .task-list {
  964. border-top: 1rpx solid var(--border-light, $uni-border-color-light);
  965. padding-top: 16rpx;
  966. display: flex;
  967. flex-direction: column;
  968. gap: 12rpx;
  969. }
  970. /* 报告来源标识 */
  971. .source-label {
  972. margin-top: 16rpx;
  973. font-size: calc(22rpx * var(--font-scale, 1));
  974. color: var(--muted, $app-text-subtle);
  975. text-align: right;
  976. }
  977. .rec-card {
  978. display: flex;
  979. flex-direction: row;
  980. background: var(--bg, $uni-primary-pale);
  981. border-radius: 16rpx;
  982. overflow: hidden;
  983. padding: 12rpx;
  984. }
  985. .rec-cover {
  986. width: 120rpx;
  987. height: 120rpx;
  988. border-radius: 8rpx;
  989. margin-right: 12rpx;
  990. flex-shrink: 0;
  991. background: $uni-border-color-light;
  992. }
  993. .rec-info {
  994. flex: 1;
  995. display: flex;
  996. flex-direction: column;
  997. gap: 4rpx;
  998. min-width: 0;
  999. }
  1000. .rec-type-tag {
  1001. display: inline-block;
  1002. font-size: calc(18rpx * var(--font-scale, 1));
  1003. color: var(--color-primary, $brand-primary);
  1004. background: rgba(249,115,22,0.1);
  1005. padding: 2rpx 12rpx;
  1006. border-radius: 8rpx;
  1007. align-self: flex-start;
  1008. }
  1009. .rec-name {
  1010. font-size: calc(26rpx * var(--font-scale, 1));
  1011. font-weight: 600;
  1012. color: var(--text, $uni-text-color);
  1013. overflow: hidden;
  1014. text-overflow: ellipsis;
  1015. white-space: nowrap;
  1016. }
  1017. .rec-desc {
  1018. font-size: calc(22rpx * var(--font-scale, 1));
  1019. color: var(--text-secondary, $uni-text-color-secondary);
  1020. overflow: hidden;
  1021. text-overflow: ellipsis;
  1022. white-space: nowrap;
  1023. }
  1024. .rec-price {
  1025. font-size: calc(26rpx * var(--font-scale, 1));
  1026. color: $brand-primary;
  1027. font-weight: 600;
  1028. }
  1029. /* Mascot badge in nav */
  1030. .mascot-badge {
  1031. display: flex;
  1032. align-items: center;
  1033. gap: 4rpx;
  1034. padding: 6rpx 16rpx;
  1035. background: $dim-wisdom-tint-2;
  1036. border-radius: 24rpx;
  1037. font-size: calc(22rpx * var(--font-scale, 1));
  1038. }
  1039. .mascot-badge-icon {
  1040. font-size: calc(24rpx * var(--font-scale, 1));
  1041. }
  1042. .mascot-badge-name {
  1043. color: $dim-wisdom;
  1044. font-weight: 500;
  1045. }
  1046. .chat-disclaimer {
  1047. text-align: center;
  1048. font-size: calc(22rpx * var(--font-scale, 1));
  1049. color: $facade-text-muted;
  1050. padding: 16rpx 0 20rpx;
  1051. background: $facade-fill-2;
  1052. }
  1053. .quota-bar-wrapper {
  1054. padding: 16rpx $uni-space-page;
  1055. background: $app-surface;
  1056. border-top: 1rpx solid $facade-fill-2;
  1057. }
  1058. </style>