| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160 |
- <template>
- <view class="chat-container" :style="{ '--font-scale': fontScale }">
- <!-- 导航栏 -->
- <view class="chat-nav" :class="'mascot-' + mascotCode">
- <view class="nav-back" @click="goBack">
- <text class="nav-back-icon">‹</text>
- </view>
- <view class="nav-actions">
- <view class="mascot-badge" v-if="mascotCode && !isNutrition" @click="showConversations = !showConversations">
- <text class="mascot-badge-icon">{{ mascotIcon }}</text>
- <text class="mascot-badge-name">{{ mascotName }}</text>
- </view>
- <text class="nav-action" @click="showConversations = !showConversations" v-else>☰</text>
- </view>
- </view>
- <!-- 会员状态条:过期 / 临期时给出续费入口(T-F2) -->
- <view class="member-status-bar" v-if="memberStatusText" @click="goRenew">
- <text class="member-status-text">{{ memberStatusText }}</text>
- <text class="member-status-action">去续费 ›</text>
- </view>
- <!-- 会话列表(侧拉) -->
- <view class="conv-overlay" v-if="showConversations" @click="showConversations = false"></view>
- <view class="conv-sidebar" :class="{ 'conv-sidebar-open': showConversations }">
- <view class="conv-header">
- <text class="conv-header-title">会话列表</text>
- <text class="conv-header-new" @click="newConversation">+ 新会话</text>
- </view>
- <scroll-view class="conv-list" scroll-y>
- <view class="conv-item" v-for="conv in conversations" :key="conv.id"
- :class="{ 'conv-item-active': conv.id === currentConversationId }"
- @click="switchConversation(conv.id)">
- <text class="conv-item-name">{{ conv.name || '新会话' }}</text>
- <text class="conv-item-time">{{ formatTime(conv.updated_at) }}</text>
- </view>
- <BaseEmpty v-if="conversations.length === 0" text="暂无会话" icon="💬" />
- </scroll-view>
- </view>
- <!-- 消息列表 -->
- <scroll-view class="message-list" scroll-y :scroll-into-view="scrollToId" scroll-with-animation
- @scrolltoupper="loadMoreMessages" id="messageList">
- <view class="message-list-inner">
- <view class="welcome-card" v-if="messages.length === 0 && !sending">
- <view class="welcome-icon">{{ mascotIcon || (isNutrition ? '🥗' : (isHealthCoach ? '💡' : '🤖')) }}</view>
- <text class="welcome-title">{{ isNutrition ? '你好!我是营养助手' : (isHealthCoach ? ('你好!我是' + (mascotName || '健康教练')) : (isButler ? '你好!我是健康管家' : ('你好!我是' + (mascotName || '家庭助手')))) }}</text>
- <text class="welcome-desc">{{ welcomeSubtitle }}</text>
- <view class="welcome-suggestions">
- <view class="welcome-suggestion" v-if="!isNutrition && !isHealthCoach" @click="quickQuestion('小明最近任务完成怎么样?')">
- <text class="suggestion-icon">📋</text>
- <text class="suggestion-text">小明最近任务完成怎么样?</text>
- </view>
- <view class="welcome-suggestion" v-if="!isNutrition && !isHealthCoach" @click="quickQuestion('我家家庭成员的能量评分怎么样?')">
- <text class="suggestion-icon">⚡</text>
- <text class="suggestion-text">家庭成员的能量评分怎么样?</text>
- </view>
- <view class="welcome-suggestion" v-if="!isNutrition && !isHealthCoach" @click="quickQuestion('今天有什么需要我做的事情?')">
- <text class="suggestion-icon">✅</text>
- <text class="suggestion-text">今天有什么需要我做的事情?</text>
- </view>
- <view class="welcome-suggestion" v-if="isNutrition" @click="quickQuestion('根据报告,家庭成员需要补充哪些营养?')">
- <text class="suggestion-icon">🥦</text>
- <text class="suggestion-text">根据报告,家庭成员需要补充哪些营养?</text>
- </view>
- <view class="welcome-suggestion" v-if="isNutrition" @click="quickQuestion('有哪些食物或产品推荐?')">
- <text class="suggestion-icon">🛒</text>
- <text class="suggestion-text">有哪些食物或产品推荐?</text>
- </view>
- <view class="welcome-suggestion" v-if="isHealthCoach" @click="quickQuestion('家人挑食怎么办?')">
- <text class="suggestion-icon">🍽️</text>
- <text class="suggestion-text">家人挑食怎么办?</text>
- </view>
- <view class="welcome-suggestion" v-if="isHealthCoach" @click="quickQuestion('家人总生病,是不是抵抗力差?')">
- <text class="suggestion-icon">🤧</text>
- <text class="suggestion-text">家人总生病,是不是抵抗力差?</text>
- </view>
- <view class="welcome-suggestion" v-if="isHealthCoach" @click="quickQuestion('怎么知道家人是什么体质?')">
- <text class="suggestion-icon">🔍</text>
- <text class="suggestion-text">怎么知道家人是什么体质?</text>
- </view>
- <view class="welcome-suggestion" v-if="isButler" @click="quickQuestion('我家成员肠道菌群怎么样?')">
- <text class="suggestion-icon">🦠</text>
- <text class="suggestion-text">我家成员肠道菌群怎么样?</text>
- </view>
- <view class="welcome-suggestion" v-if="isButler" @click="quickQuestion('怎么改善家人挑食问题?')">
- <text class="suggestion-icon">🥗</text>
- <text class="suggestion-text">怎么改善家人挑食问题?</text>
- </view>
- <view class="welcome-suggestion" v-if="isButler" @click="quickQuestion('需要补充什么营养素?')">
- <text class="suggestion-icon">💊</text>
- <text class="suggestion-text">需要补充什么营养素?</text>
- </view>
- </view>
- </view>
- <view class="message-group" v-for="(msg, idx) in messages" :key="msg.id">
- <!-- 用户消息 -->
- <view class="message message-user" v-if="msg.query">
- <view class="message-bubble user-bubble">{{ msg.query }}</view>
- </view>
- <!-- 回复 -->
- <view class="message message-ai" v-if="msg.answer">
- <view class="message-avatar">{{ isHealthCoach ? '🎯' : (isButler ? '🏥' : (mascotIcon || '🤖')) }}</view>
- <view class="message-bubble ai-bubble">
- <text class="ai-answer-text">{{ msg.answer }}</text>
- <!-- 推荐卡片 -->
- <view class="rec-list" v-if="msg.recommendations && msg.recommendations.length > 0">
- <view class="rec-card" v-for="(rec, ri) in msg.recommendations" :key="ri" @click="gotoRec(rec)">
- <image class="rec-cover" v-if="rec.coverImage" :src="getImageUrl(rec.coverImage)" mode="aspectFill" />
- <view class="rec-info">
- <text class="rec-type-tag">{{ rec.type === 'product' ? '商品' : rec.type === 'activity' ? '活动' : '文章' }}</text>
- <text class="rec-name">{{ rec.name }}</text>
- <text class="rec-desc">{{ rec.description }}</text>
- <text class="rec-price" v-if="rec.price">¥{{ rec.price }}</text>
- </view>
- </view>
- </view>
- <!-- 任务卡片 -->
- <view class="task-list" v-if="msg.tasks && msg.tasks.length > 0">
- <TaskCard v-for="(task, ti) in msg.tasks" :key="ti" :task="task" :conversationId="currentConversationId" @accepted="onTaskAccepted" />
- </view>
- <!-- 报告来源标识 -->
- <view class="source-label" v-if="msg.sourceReport">
- 来源:{{ msg.sourceReport.type === 'nutrition' ? '营养报告' : '测评报告' }} #{{ msg.sourceReport.id }}
- </view>
- </view>
- </view>
- </view>
- <!-- 加载中 -->
- <view class="message message-ai" v-if="sending">
- <view class="message-avatar">{{ mascotIcon || '🤖' }}</view>
- <view class="message-bubble ai-bubble typing">
- <text class="typing-dot">.</text>
- <text class="typing-dot">.</text>
- <text class="typing-dot">.</text>
- </view>
- </view>
- <view id="scrollBottom"></view>
- </view>
- </scroll-view>
- <!-- 输入区 -->
- <view class="chat-input-area">
- <view class="chat-input-wrap">
- <input class="chat-input" v-model="inputText" :placeholder="inputPlaceholder"
- :disabled="sending || gateBlocked" @confirm="sendMessage" confirm-type="send" />
- </view>
- <view class="chat-voice-btn" :class="{ 'voice-recording': isRecording }" @touchstart="startVoiceRecord" @touchend="stopVoiceRecord">
- <text class="voice-icon">{{ isRecording ? '🔴' : '🎤' }}</text>
- </view>
- <view class="chat-send-btn" :class="{ 'chat-send-active': inputText.trim() }"
- @click="sendMessage">
- <text class="send-icon">➤</text>
- </view>
- </view>
- <view class="chat-disclaimer">本服务为生成内容,结果仅供参考</view>
- <!-- 配额进度条 -->
- <view class="quota-bar-wrapper" v-if="aiChatQuota && !aiChatQuota.unlimited">
- <quota-progress-bar :remaining="aiChatQuota.remaining || 0" :total="aiChatQuota.total || 3" name="今日AI对话剩余"></quota-progress-bar>
- </view>
- <!-- 升级引导弹窗 -->
- <upgrade-guide-modal ref="upgradeGuideModal"></upgrade-guide-modal>
- </view>
- </template>
- <script>
- import { aiSendMessage, aiGetConversations, aiGetMessages, aiDeleteConversation, aiSendNutritionMessage, aiSendHealthCoachMessage, aiSendHealthButlerMessage, aiGateStatus, getMyMembership, getAllQuotaStatus, reportAppEnter
- } from '../../utils/api.js'
- import { sttTranscribe } from '../../utils/api.js'
- import BaseEmpty from '../../components/BaseEmpty.vue'
- import TaskCard from '@/pages/ai/components/AITaskCard.vue'
- import QuotaProgressBar from '@/pages/ai/components/QuotaProgressBar.vue'
- import UpgradeGuideModal from '@/pages/ai/components/UpgradeGuideModal.vue'
- import config from '@/config.js'
- import { parseDate } from '../../utils/format.js'
- import fontScaleMixin from '@/mixins/font-scale.js'
- export default {
- mixins: [fontScaleMixin],
- components: { BaseEmpty, TaskCard, QuotaProgressBar, UpgradeGuideModal },
- data() {
- return {
- inputText: '',
- messages: [],
- conversations: [],
- currentConversationId: '',
- sending: false,
- showConversations: false,
- scrollToId: '',
- pageLoaded: false,
- pendingFirstMessage: '',
- fromPage: '',
- mode: '',
- reportId: '',
- recommendations: [],
- mascotCode: '',
- mascotName: '',
- mascotIcon: '',
- isRecording: false,
- recorderManager: null,
- aiChatQuota: null,
- // 会员门禁(/api/ai/gate 返回的 AiGateResult)
- memberGate: null,
- gateStatus: '',
- gateBlocked: false,
- // 临期提醒阈值(天),T-F2 状态条使用
- nearExpiryDays: 7
- }
- },
- computed: {
- isNutrition: function() {
- return this.mode === 'nutrition'
- },
- isHealthCoach: function() {
- return this.mode === 'health'
- },
- isButler: function() {
- return this.mode === 'butler'
- },
- welcomeSubtitle: function() {
- if (this.isNutrition) {
- return '我可以基于菌群检测报告,为你提供个性化的营养建议和推荐'
- }
- if (this.isHealthCoach) {
- return '陪伴家庭成员健康成长,用提问帮你找到答案'
- }
- if (this.isButler) {
- return '专属健康管家,基于知识库提供个性化健康建议'
- }
- if (this.fromPage) {
- var pageNames = {
- 'pages/body/index': '身',
- 'pages/wisdom/index': '智',
- 'pages/mind/index': '心',
- 'pages/index/index': '首页',
- 'pages/index/parent-index': '首页',
- 'pages/index/child-index': '首页',
- 'pages/profile/profile': '我的',
- 'pages/profile/children': '我的',
- 'pages/shop/index': '商城',
- 'pages/discover/index': '发现'
- }
- var pageName = pageNames[this.fromPage] || this.fromPage
- return '从 ' + pageName + ' 发起,我可以帮你了解:'
- }
- return '我可以帮你了解家庭成员的成长情况,比如:'
- },
- inputPlaceholder: function() {
- if (this.gateStatus === 'MEMBER_EXPIRED') return '会员已到期,续费后可继续对话'
- if (this.gateStatus === 'UPGRADE_REQUIRED') return '开通会员后即可对话'
- return '问我关于家庭和成员的问题...'
- },
- // T-F2 会员状态条:过期 / 临期才有文案
- memberStatusText: function() {
- if (!this.memberGate) return ''
- if (this.gateStatus === 'MEMBER_EXPIRED') {
- var end = this.memberGate.memberExpireTime || this.memberGate.endDate
- var day = this.formatGateDate(end)
- return day ? ('会员已于 ' + day + ' 到期') : '会员已到期'
- }
- if (this.gateStatus === 'ALLOW' && this.memberGate.isActive) {
- var remain = this.memberGate.daysRemaining
- if (typeof remain === 'number' && remain >= 0 && remain <= this.nearExpiryDays) {
- // 后端可能返回小数(按毫秒折算),展示向上取整,避免「剩余 0 天」却仍可用
- return '会员即将到期(剩余 ' + Math.ceil(remain) + ' 天)'
- }
- }
- return ''
- }
- },
- onLoad: function(options) {
- reportAppEnter('ai');
-
- this.mode = options.mode || ''
- this.fromPage = options.fromPage ? decodeURIComponent(options.fromPage) : ''
- this.reportId = options.reportId || ''
- if (options.firstMessage) {
- this.pendingFirstMessage = decodeURIComponent(options.firstMessage)
- }
- // 会员门禁:统一走 /api/ai/gate
- // ALLOW → 正常加载;UPGRADE_REQUIRED → 引导升级且不加载会话;MEMBER_EXPIRED → 可看历史但不可新建/发送
- this.checkMemberGate(true)
- // 加载 AI 配额(BASIC用户可见)
- var selfQuota = this
- getAllQuotaStatus().then(function(res) {
- if (res.data && res.data.AI_CHAT) {
- selfQuota.aiChatQuota = res.data.AI_CHAT
- }
- }).catch(function() {})
- },
- onShow() {
- if (this.pageLoaded) {
- // 从升级/续费页返回等场景:重新查门禁,按最新状态决定能否加载/继续对话
- this.checkMemberGate(false)
- }
- this.pageLoaded = true
- },
- methods: {
- goBack() {
- uni.navigateBack()
- },
- // 查询会员门禁;autoPrompt=true 时按 status 主动弹引导弹窗(首次进入)
- checkMemberGate(autoPrompt) {
- var self = this
- aiGateStatus().then(function(res) {
- self.applyMemberGate((res && res.data) || {}, autoPrompt)
- }).catch(function(e) {
- // 门禁接口不可用(后端未发布 / 网络异常)时回退旧口径,避免误伤有效会员。
- // 真实权限仍由后端 AI 端点兜底,这里只是展示层降级。
- console.warn('[AI] aiGateStatus 失败,回退 getMyMembership', e && e.code)
- getMyMembership().then(function(res) {
- self.applyMemberGate(self.buildLegacyGate((res && res.data) || {}), autoPrompt)
- }).catch(function() {
- self.applyMemberGate({ status: 'UPGRADE_REQUIRED', canUse: false }, autoPrompt)
- })
- })
- },
- // /api/ai/gate 不可用时的旧会员接口降级映射
- // 注意:旧接口不区分「从未付费 / 曾付费已过期」,也不能给出剩余天数,
- // 因此 daysRemaining / isActive 置空(状态条据此跳过临期提醒),避免展示假数据。
- buildLegacyGate(membership) {
- var level = membership.memberLevel || 'FREE'
- var allowed = level !== 'FREE'
- return {
- enabled: true,
- status: allowed ? 'ALLOW' : 'UPGRADE_REQUIRED',
- canUse: allowed,
- canViewHistory: false,
- memberLevel: level,
- isActive: null,
- memberExpireTime: membership.memberExpireTime || null,
- endDate: membership.endDate || membership.memberExpireTime || null,
- daysRemaining: null
- }
- },
- applyMemberGate(gate, autoPrompt) {
- // status 缺失(gate 接口返回空 data / 5001 无家庭兜底)时 fail-closed:
- // 不默认放行,沿用上一次已知状态;首次遇到则按未开通处理(不主动弹窗,避免误伤)。
- var status = gate.status
- if (!status) {
- if (gate.canUse === true) status = 'ALLOW'
- else if (gate.canUse === false) status = 'UPGRADE_REQUIRED'
- else status = this.gateStatus || 'UPGRADE_REQUIRED'
- }
- this.memberGate = gate
- this.gateStatus = status
- this.gateBlocked = status !== 'ALLOW'
- if (status === 'UPGRADE_REQUIRED') {
- // 从未付费:不加载会话,直接引导升级
- if (autoPrompt) this.showGateModal('hard')
- return
- }
- // ALLOW 与 MEMBER_EXPIRED 都可查看历史会话
- this.loadMascot()
- this.loadConversations()
- if (status === 'MEMBER_EXPIRED') {
- if (autoPrompt) this.showGateModal('expired')
- return
- }
- if (this.pendingFirstMessage) {
- var self = this
- this.$nextTick(function() {
- self.inputText = self.pendingFirstMessage
- self.pendingFirstMessage = ''
- self.sendMessage()
- })
- }
- },
- // 加载用户 mascot 设置(福宝/浠宝)
- loadMascot() {
- var userInfo = uni.getStorageSync('userInfo')
- if (!userInfo) return
- if (userInfo.mascot === 'xibao') {
- this.mascotCode = 'xibao'
- this.mascotName = '浠宝'
- this.mascotIcon = '🌟'
- } else if (userInfo.mascot === 'fubao') {
- this.mascotCode = 'fubao'
- this.mascotName = '福宝'
- this.mascotIcon = '💪'
- }
- },
- // type: soft | hard | expired
- showGateModal(type) {
- var self = this
- this.$nextTick(function() {
- var modal = self.$refs.upgradeGuideModal
- if (!modal) return
- modal.type = type
- modal.quotaType = ''
- modal.show()
- })
- },
- goRenew() {
- uni.navigateTo({ url: '/pages/membership/upgrade' })
- },
- // 门禁日期展示:yyyy-MM-dd(iOS 安全解析走 parseDate,兼容时间戳/ISO/Java 格式)
- formatGateDate(value) {
- var d = parseDate(value)
- if (!d) return ''
- var m = d.getMonth() + 1
- var day = d.getDate()
- return d.getFullYear() + '-' + (m < 10 ? '0' + m : m) + '-' + (day < 10 ? '0' + day : day)
- },
- startVoiceRecord() {
- if (this.isRecording) return
- if (this.gateBlocked) {
- this.showGateModal(this.gateStatus === 'MEMBER_EXPIRED' ? 'expired' : 'hard')
- return
- }
- this.recorderManager = uni.getRecorderManager()
- var self = this
- this.recorderManager.onStop(function(res) {
- self.isRecording = false
- uni.showLoading({ title: '语音识别中...', mask: true })
- sttTranscribe(res.tempFilePath).then(function(text) {
- uni.hideLoading()
- self.inputText = text
- }).catch(function(err) {
- uni.hideLoading()
- uni.showToast({ title: '语音识别失败', icon: 'none' })
- })
- })
- this.recorderManager.onError(function() {
- self.isRecording = false
- uni.showToast({ title: '录音失败', icon: 'none' })
- })
- this.recorderManager.start({ duration: 60000, format: 'mp3' })
- this.isRecording = true
- },
- stopVoiceRecord() {
- if (this.recorderManager) {
- this.recorderManager.stop()
- }
- },
- onTaskAccepted() {
- this.loadConversations()
- },
- async loadConversations() {
- try {
- const res = await aiGetConversations()
- this.conversations = res.data || []
- } catch (e) {
- console.log('加载会话列表失败', e)
- }
- },
- async switchConversation(convId) {
- this.currentConversationId = convId
- this.showConversations = false
- this.messages = []
- this.$nextTick(() => {
- this.scrollToBottom()
- })
- try {
- const res = await aiGetMessages({ conversationId: convId })
- this.messages = res.data || []
- this.$nextTick(() => {
- this.scrollToBottom()
- })
- } catch (e) {
- console.log('加载消息失败', e)
- }
- },
- newConversation() {
- // 过期 / 未开通:不可新建会话(历史仍可查看与删除)
- if (this.gateStatus === 'MEMBER_EXPIRED' || this.gateStatus === 'UPGRADE_REQUIRED') {
- this.showGateModal(this.gateStatus === 'MEMBER_EXPIRED' ? 'expired' : 'hard')
- return
- }
- this.currentConversationId = ''
- this.showConversations = false
- this.messages = []
- this.inputText = ''
- this.$nextTick(() => {
- this.scrollToBottom()
- })
- },
- async sendMessage() {
- const text = this.inputText.trim()
- if (!text || this.sending) return
- // 会员门禁拦截:ALLOW 以外不发请求,直接弹对应引导弹窗
- if (this.gateBlocked) {
- this.showGateModal(this.gateStatus === 'MEMBER_EXPIRED' ? 'expired' : 'hard')
- return
- }
- // BASIC 配额检查(unlimited=true 不拦截)
- if (this.aiChatQuota && !this.aiChatQuota.unlimited && this.aiChatQuota.remaining <= 0) {
- this.$refs.upgradeGuideModal.type = 'soft'
- this.$refs.upgradeGuideModal.quotaType = 'AI_CHAT'
- this.$refs.upgradeGuideModal.total = this.aiChatQuota.total
- this.$refs.upgradeGuideModal.show()
- return
- }
- // 立即显示用户消息
- const tempMsg = { id: 'temp_' + Date.now(), query: text, answer: '' }
- this.messages.push(tempMsg)
- this.inputText = ''
- this.sending = true
- this.$nextTick(() => {
- this.scrollToBottom()
- })
- try {
- var params = {
- query: text,
- conversationId: this.currentConversationId
- }
- if (this.reportId) {
- params.reportId = this.reportId
- }
- var res, data
- if (this.mode === 'nutrition') {
- res = await aiSendNutritionMessage(params)
- data = res.data || {}
- const lastMsg = this.messages[this.messages.length - 1]
- if (lastMsg) {
- lastMsg.answer = data.answer || ''
- lastMsg.recommendations = data.recommendations || []
- lastMsg.tasks = data.tasks || []
- if (this.reportId) {
- lastMsg.sourceReport = { id: this.reportId, type: 'nutrition' }
- }
- }
- } else if (this.mode === 'health') {
- res = await aiSendHealthCoachMessage(params)
- data = res.data || {}
- const lastMsg = this.messages[this.messages.length - 1]
- if (lastMsg) {
- lastMsg.answer = data.answer || ''
- lastMsg.recommendations = data.recommendations || []
- lastMsg.tasks = data.tasks || []
- }
- } else if (this.mode === 'butler') {
- // 传递 memberId 让健康管家能加载家庭上下文
- var butlerParams = Object.assign({}, params)
- butlerParams.memberId = uni.getStorageSync('currentChildId') || null
- res = await aiSendHealthButlerMessage(butlerParams)
- data = res.data || {}
- const butlerLastMsg = this.messages[this.messages.length - 1]
- if (butlerLastMsg) {
- butlerLastMsg.answer = data.answer || ''
- butlerLastMsg.recommendations = data.recommendations || []
- butlerLastMsg.tasks = data.tasks || []
- }
- } else {
- res = await aiSendMessage(params)
- data = res.data || {}
- const lastMsg = this.messages[this.messages.length - 1]
- if (lastMsg) {
- lastMsg.answer = data.answer || ''
- lastMsg.recommendations = data.recommendations || []
- lastMsg.tasks = data.tasks || []
- if (this.reportId) {
- lastMsg.sourceReport = { id: this.reportId, type: 'assessment' }
- }
- }
- }
- // 更新 conversationId(新建会话时 Dify 返回)
- if (data.conversationId && !this.currentConversationId) {
- this.currentConversationId = data.conversationId
- // 刷新会话列表
- this.loadConversations()
- }
- } catch (e) {
- var errCode = e && e.code
- if (errCode === 46003 || errCode === 46004) {
- // 会员门禁:撤掉未落库的乐观消息,把输入还给用户,改为弹专用引导弹窗
- const lastMsg = this.messages[this.messages.length - 1]
- if (lastMsg && String(lastMsg.id).indexOf('temp_') === 0) {
- this.messages.pop()
- }
- if (!this.inputText) this.inputText = text
- if (errCode === 46004) {
- this.gateStatus = 'MEMBER_EXPIRED'
- } else {
- this.gateStatus = 'UPGRADE_REQUIRED'
- }
- this.gateBlocked = true
- // 保证状态条依赖的 memberGate 不为空(会话中途降级时也能显示续费入口)
- // 用新对象覆盖,避免直接改写接口返回体(可能被 3 秒去重缓存共享)
- this.memberGate = Object.assign({}, this.memberGate || {}, {
- status: this.gateStatus,
- canUse: false
- })
- this.showGateModal(errCode === 46004 ? 'expired' : 'hard')
- return
- }
- // 显示错误(发送类走 _noToast,这里补回后端原话,避免只剩通用兜底)
- const lastMsg = this.messages[this.messages.length - 1]
- if (lastMsg) {
- lastMsg.answer = '抱歉,我暂时无法回答,请稍后再试。'
- }
- uni.showToast({ title: (e && e.message) || '发送失败,请稍后再试', icon: 'none' })
- } finally {
- this.sending = false
- this.$nextTick(() => {
- this.scrollToBottom()
- })
- }
- },
- quickQuestion(text) {
- this.inputText = text
- this.sendMessage()
- },
- gotoRec(rec) {
- if (rec.url) {
- uni.navigateTo({ url: rec.url })
- }
- },
- loadMoreMessages() {
- // 分页加载历史(当前简化)
- },
- scrollToBottom() {
- this.scrollToId = 'scrollBottom'
- },
- formatTime(timestamp) {
- if (!timestamp) return ''
- const d = new Date(timestamp * 1000)
- const now = new Date()
- const diff = now - d
- if (diff < 86400000) {
- return d.getHours().toString().padStart(2, '0') + ':' + d.getMinutes().toString().padStart(2, '0')
- }
- return (d.getMonth() + 1) + '/' + d.getDate()
- },
- getImageUrl: function(path) {
- if (!path || path === 'null' || path === 'undefined' || path === '/null') return ''
- var s = String(path).trim()
- if (!s || s === 'null' || s === '/null') return ''
- if (s.indexOf('http://') === 0 || s.indexOf('https://') === 0) return s
- return config.API_BASE_URL + (s.charAt(0) === '/' ? s : '/' + s)
- }
- }
- }
- </script>
- <style scoped lang="scss">
- .chat-container {
- display: flex;
- flex-direction: column;
- height: 100vh;
- background: var(--bg, $uni-primary-pale);
- position: relative;
- }
- /* 导航栏 */
- .chat-nav {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 88rpx 24rpx 16rpx;
- background: $app-surface;
- border-bottom: 1rpx solid var(--border-light, $uni-border-color-light);
- position: relative;
- z-index: 100;
- }
- .chat-nav.mascot-xibao {
- background: linear-gradient(135deg, $uni-primary-pale 0%, $tint-warm-edge 100%);
- border-bottom-color: $dim-body;
- }
- .chat-nav.mascot-xibao .chat-nav.mascot-fubao {
- background: linear-gradient(135deg, $dim-wealth-tint 0%, $status-warning-soft 100%);
- border-bottom-color: $dim-wealth;
- }
- .chat-nav.mascot-fubao .nav-back-icon {
- font-size: calc(40rpx * var(--font-scale, 1));
- color: var(--text, $uni-text-color);
- font-weight: 600;
- }
- .nav-actions {
- width: 60rpx;
- height: 60rpx;
- display: flex;
- align-items: center;
- justify-content: center;
- }
- .nav-action {
- font-size: calc(36rpx * var(--font-scale, 1));
- color: var(--text-secondary, $uni-text-color-secondary);
- }
- /* 会员状态条(过期 / 临期续费入口) */
- .member-status-bar {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 12rpx 24rpx;
- background: $status-warning-soft;
- border-bottom: 1rpx solid var(--border-light, $uni-border-color-light);
- }
- .member-status-text {
- font-size: calc(24rpx * var(--font-scale, 1));
- color: $facade-text-body;
- }
- .member-status-action {
- font-size: calc(24rpx * var(--font-scale, 1));
- color: $brand-primary;
- font-weight: 500;
- flex-shrink: 0;
- margin-left: 16rpx;
- }
- /* 会话列表侧拉 */
- .conv-overlay {
- position: fixed;
- top: 0;
- left: 0;
- right: 0;
- bottom: 0;
- background: rgba(0,0,0,0.3);
- z-index: 200;
- }
- .conv-sidebar {
- position: fixed;
- top: 0;
- right: -500rpx;
- width: 460rpx;
- height: 100vh;
- background: $app-surface;
- z-index: 210;
- transition: right 0.3s ease;
- display: flex;
- flex-direction: column;
- }
- .conv-sidebar-open {
- right: 0;
- }
- .conv-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: 100rpx 24rpx 16rpx;
- border-bottom: 1rpx solid var(--border-light, $uni-border-color-light);
- }
- .conv-header-title {
- font-size: calc(28rpx * var(--font-scale, 1));
- font-weight: 600;
- color: var(--text, $uni-text-color);
- }
- .conv-header-new {
- font-size: calc(24rpx * var(--font-scale, 1));
- color: var(--color-primary, $brand-primary);
- font-weight: 500;
- }
- .conv-list {
- flex: 1;
- overflow-y: auto;
- }
- .conv-item {
- padding: 20rpx 24rpx;
- border-bottom: 1rpx solid var(--border-light, $uni-border-color-light);
- }
- .conv-item-active {
- background: rgba(249,115,22,0.06);
- }
- .conv-item-name {
- font-size: calc(26rpx * var(--font-scale, 1));
- color: var(--text, $uni-text-color);
- display: block;
- margin-bottom: 6rpx;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- .conv-item-time {
- font-size: calc(20rpx * var(--font-scale, 1));
- color: var(--muted, $app-text-subtle);
- }
- /* 消息列表 */
- .message-list {
- flex: 1;
- overflow-y: auto;
- padding: 20rpx 24rpx;
- }
- .message-list-inner {
- min-height: 100%;
- }
- /* 欢迎卡片 */
- .welcome-card {
- text-align: center;
- padding: 60rpx 20rpx 40rpx;
- }
- .welcome-icon {
- font-size: calc($uni-font-size-5xl * var(--font-scale, 1));
- margin-bottom: 20rpx;
- transition: transform 0.3s;
- }
- .mascot-xibao .welcome-icon {
- animation: welcomeFloat 3s ease-in-out infinite;
- }
- .mascot-fubao .welcome-icon {
- animation: welcomeFloat 3s ease-in-out infinite 0.5s;
- }
- @keyframes welcomeFloat {
- 0%, 100% { transform: translateY(0); }
- 50% { transform: translateY(-10rpx); }
- }
- .welcome-title {
- font-size: calc(32rpx * var(--font-scale, 1));
- font-weight: 600;
- color: var(--text, $uni-text-color);
- display: block;
- margin-bottom: 12rpx;
- }
- .welcome-desc {
- font-size: calc(24rpx * var(--font-scale, 1));
- color: var(--text-secondary, $uni-text-color-secondary);
- display: block;
- margin-bottom: 32rpx;
- }
- .welcome-suggestions {
- display: flex;
- flex-direction: column;
- gap: 16rpx;
- padding: 0 20rpx;
- }
- .welcome-suggestion {
- display: flex;
- align-items: center;
- background: $app-surface;
- padding: 20rpx 24rpx;
- border-radius: 16rpx;
- box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
- }
- .suggestion-icon {
- font-size: calc(28rpx * var(--font-scale, 1));
- margin-right: 12rpx;
- }
- .suggestion-text {
- font-size: calc(24rpx * var(--font-scale, 1));
- color: var(--text, $uni-text-color);
- }
- /* 消息 */
- .message {
- margin-bottom: 24rpx;
- }
- .message-user {
- display: flex;
- justify-content: flex-end;
- }
- .message-ai {
- display: flex;
- align-items: flex-start;
- }
- .message-avatar {
- width: 56rpx;
- height: 56rpx;
- font-size: calc(36rpx * var(--font-scale, 1));
- margin-right: 12rpx;
- flex-shrink: 0;
- display: flex;
- align-items: center;
- justify-content: center;
- border-radius: 50%;
- transition: transform 0.2s;
- }
- .mascot-xibao .message-avatar {
- background: linear-gradient(135deg, $uni-primary-pale 0%, $tint-warm-edge 100%);
- border: 2rpx solid $dim-body;
- }
- .mascot-fubao .message-avatar {
- background: linear-gradient(135deg, $dim-wealth-tint 0%, $status-warning-soft 100%);
- border: 2rpx solid $dim-wealth;
- }
- .message-bubble {
- max-width: 70%;
- padding: 16rpx 20rpx;
- font-size: calc(26rpx * var(--font-scale, 1));
- line-height: 1.6;
- border-radius: 16rpx;
- word-break: break-word;
- }
- .user-bubble {
- background: var(--color-primary, $brand-primary);
- color: $app-surface;
- border-bottom-right-radius: 8rpx;
- }
- .ai-bubble {
- background: $app-surface;
- color: var(--text, $uni-text-color);
- border-bottom-left-radius: 8rpx;
- box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
- }
- /* 输入区 */
- .chat-input-area {
- display: flex;
- align-items: center;
- padding: 16rpx 24rpx;
- padding-bottom: calc(16rpx + env(safe-area-inset-bottom));
- background: $app-surface;
- border-top: 1rpx solid var(--border-light, $uni-border-color-light);
- }
- .chat-input-wrap {
- flex: 1;
- background: var(--bg, $uni-primary-pale);
- border-radius: 24rpx;
- padding: 0 24rpx;
- margin-right: 12rpx;
- }
- .chat-voice-btn {
- width: 60rpx;
- height: 60rpx;
- border-radius: 50%;
- background: var(--border-light, $uni-border-color-light);
- display: flex;
- align-items: center;
- justify-content: center;
- flex-shrink: 0;
- margin-right: 12rpx;
- }
- .chat-voice-btn.voice-recording {
- background: $accent-coral;
- }
- .voice-icon {
- font-size: calc(28rpx * var(--font-scale, 1));
- }
- .chat-input {
- height: 72rpx;
- font-size: calc(26rpx * var(--font-scale, 1));
- color: var(--text, $uni-text-color);
- }
- .chat-send-btn {
- width: 72rpx;
- height: 72rpx;
- border-radius: 50%;
- background: var(--border-light, $uni-border-color-light);
- display: flex;
- align-items: center;
- justify-content: center;
- flex-shrink: 0;
- }
- .chat-send-active {
- background: var(--color-primary, $brand-primary);
- }
- .send-icon {
- font-size: calc(28rpx * var(--font-scale, 1));
- color: $app-surface;
- }
- /* 打字动画 */
- .typing {
- display: flex;
- align-items: center;
- gap: 4rpx;
- min-height: 40rpx;
- }
- .typing-dot {
- font-size: calc(40rpx * var(--font-scale, 1));
- line-height: 1;
- animation: typingBounce 1.4s infinite;
- }
- .typing-dot:nth-child(2) {
- animation-delay: 0.2s;
- }
- .typing-dot:nth-child(3) {
- animation-delay: 0.4s;
- }
- @keyframes typingBounce {
- 0%, 60%, 100% { opacity: 0.3; transform: translateY(0); }
- 30% { opacity: 1; transform: translateY(-8rpx); }
- }
- /* 推荐卡片 */
- .ai-answer-text {
- display: block;
- margin-bottom: 16rpx;
- line-height: 1.7;
- }
- .rec-list {
- border-top: 1rpx solid var(--border-light, $uni-border-color-light);
- padding-top: 16rpx;
- display: flex;
- flex-direction: column;
- gap: 12rpx;
- }
- /* 任务卡片列表 */
- .task-list {
- border-top: 1rpx solid var(--border-light, $uni-border-color-light);
- padding-top: 16rpx;
- display: flex;
- flex-direction: column;
- gap: 12rpx;
- }
- /* 报告来源标识 */
- .source-label {
- margin-top: 16rpx;
- font-size: calc(22rpx * var(--font-scale, 1));
- color: var(--muted, $app-text-subtle);
- text-align: right;
- }
- .rec-card {
- display: flex;
- flex-direction: row;
- background: var(--bg, $uni-primary-pale);
- border-radius: 16rpx;
- overflow: hidden;
- padding: 12rpx;
- }
- .rec-cover {
- width: 120rpx;
- height: 120rpx;
- border-radius: 8rpx;
- margin-right: 12rpx;
- flex-shrink: 0;
- background: $uni-border-color-light;
- }
- .rec-info {
- flex: 1;
- display: flex;
- flex-direction: column;
- gap: 4rpx;
- min-width: 0;
- }
- .rec-type-tag {
- display: inline-block;
- font-size: calc(18rpx * var(--font-scale, 1));
- color: var(--color-primary, $brand-primary);
- background: rgba(249,115,22,0.1);
- padding: 2rpx 12rpx;
- border-radius: 8rpx;
- align-self: flex-start;
- }
- .rec-name {
- font-size: calc(26rpx * var(--font-scale, 1));
- font-weight: 600;
- color: var(--text, $uni-text-color);
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- .rec-desc {
- font-size: calc(22rpx * var(--font-scale, 1));
- color: var(--text-secondary, $uni-text-color-secondary);
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- .rec-price {
- font-size: calc(26rpx * var(--font-scale, 1));
- color: $brand-primary;
- font-weight: 600;
- }
- /* Mascot badge in nav */
- .mascot-badge {
- display: flex;
- align-items: center;
- gap: 4rpx;
- padding: 6rpx 16rpx;
- background: $dim-wisdom-tint-2;
- border-radius: 24rpx;
- font-size: calc(22rpx * var(--font-scale, 1));
- }
- .mascot-badge-icon {
- font-size: calc(24rpx * var(--font-scale, 1));
- }
- .mascot-badge-name {
- color: $dim-wisdom;
- font-weight: 500;
- }
- .chat-disclaimer {
- text-align: center;
- font-size: calc(22rpx * var(--font-scale, 1));
- color: $facade-text-muted;
- padding: 16rpx 0 20rpx;
- background: $facade-fill-2;
- }
- .quota-bar-wrapper {
- padding: 16rpx $uni-space-page;
- background: $app-surface;
- border-top: 1rpx solid $facade-fill-2;
- }
- </style>
|