<template>
	<view class="container">
		<!-- 聊天记录区域 -->
		<scroll-view class="chat-container" scroll-y :scroll-top="scrollTop" :scroll-with-animation="true"
			@scroll="onScroll" :style="{ 
        height: `calc(100vh - ${inputHeight}px)`,
        marginTop: '0'
      }">
			<view class="chat-list">
				<view v-for="(message, index) in chatMessages" :key="index" class="message-item"
					:class="{ 'message-ai': message.sender === 'ai', 'message-user': message.sender === 'user' }">
					<!-- AI消息 -->
					<template v-if="message.sender === 'ai'">
						<view class="avatar-container">
							<image class="avatar" src="/static/icons/ai.png" mode="aspectFill"></image>
						</view>
						<view class="message-content">
							<view class="message-bubble ai-bubble"
								:class="{'typing': message.isTyping, 'welcome': message.isWelcome || index === 0}">
								<!-- 正在输入指示器 -->
								<view v-if="message.isTyping" class="typing-indicator">
									<view class="typing-dot"></view>
									<view class="typing-dot"></view>
									<view class="typing-dot"></view>
								</view>
								
								<!-- 消息内容 -->
								<text v-else-if="message.content" class="message-text"
									:class="{'highlight': containsKeywords(message.content)}">
									{{ message.content }}
								</text>
							</view>
							
							<!-- 操作按钮区域（仅最后一条AI消息显示） -->
							<view v-if="index === chatMessages.length - 1 && message.sender === 'ai' && !message.isTyping" class="message-actions">
								<view class="action-button" @click="regenerateMessage" hover-class="action-button-hover">
									<text class="action-icon">🔄</text>
									<text class="action-text">重新生成</text>
								</view>
							</view>
							
							<text class="message-time">{{ message.time }}</text>
						</view>
					</template>

					<!-- 用户消息 -->
					<template v-else>
						<view class="message-content user-content">
							<text class="message-time">{{ message.time }}</text>
							<view class="message-bubble user-bubble">
								<text class="message-text">{{ message.content }}</text>
							</view>
						</view>
						<view class="avatar-container">
							<image class="avatar" src="/static/images/user-avatar.svg" mode="aspectFill"></image>
						</view>
					</template>
				</view>
			</view>
		</scroll-view>

		<!-- 底部输入区 -->
		<view class="input-container" :style="{ paddingBottom: `${isIOS ? safeAreaBottom : 20}rpx` }">
			<!-- 问题建议区 -->
			<scroll-view v-if="chatMessages.length <= 3 && !inputMessage && !isProcessing" class="suggested-questions" scroll-x>
				<view v-for="(question, index) in suggestedQuestions" :key="index" class="question-chip"
					@click="useQuestion(question)">
					<text>{{ question }}</text>
				</view>
			</scroll-view>

			<view class="input-wrapper">
				<textarea class="message-input" v-model="inputMessage" placeholder="请输入您的问题..." :disabled="isProcessing"
					auto-height :maxlength="300" :style="{ maxHeight: '120rpx' }" @focus="onInputFocus"
					@confirm="submitQuestion" />
				
				<!-- 中止按钮（流式输出时显示） -->
				<view v-if="isProcessing" class="stop-button" @click="stopStreaming" hover-class="button-hover">
					<text class="stop-icon">⏹</text>
				</view>
				
				<!-- 发送按钮 -->
				<view v-else class="send-button" :class="{ 'disabled': !inputMessage.trim() }"
					@click="submitQuestion" hover-class="button-hover">
					<image class="send-icon-image"
						:src="inputMessage.trim() ? '/static/icons/chat.png' : '/static/icons/chat_off.png'"
						mode="aspectFit"></image>
				</view>
			</view>
		</view>
		
		<!-- renderjs 模块容器（用于 H5/App 端 SSE 流式连接） -->
		<view 
			:change:prop="renderModule.onDataChange" 
			:prop="renderjsData"
			class="renderjs-container"
		></view>
	</view>
</template>

<script>
	import api from "@/config/api.js";
	import storage from "@/utils/storage.js";
	import { chatStreamSuggested } from "@/api/services/chart.js";
	export default {
		data() {
			return {
				inputMessage: '', // 输入框消息
				chatMessages: [{
					sender: 'ai',
					content: '您好！我是农小禹，您的智能农业助手🌱 我可以帮您解答农业种植、病虫害防治、农产品管理等方面的问题。有什么可以帮助您的吗？',
					time: this.getFormattedTime(new Date()),
					timestamp: Date.now(),
					isWelcome: true
				}],
				scrollTop: 0,
				inputHeight: 110,
				isProcessing: false,
				currentTypingMessage: null, // 当前正在输入的消息索引
				lastUserQuestion: '', // 保存最后一个用户问题，用于重新生成
				suggestedQuestions: [
					'水稻插秧后如何管理？',
					'果树夏季修剪技巧？',
					'如何防治蔬菜常见病虫害？',
					'农药使用注意事项？',
					'有机肥和化肥怎么搭配使用？'
				],
				statusBarHeight: 20,
				safeAreaBottom: 34,
				isIOS: false,
				// renderjs 通信数据
				renderjsData: {
					action: '', // start, stop
					url: '',
					data: {},
					timestamp: 0
				},
				// 消息队列和打字机效果
				messageQueue: [],
				isTypingEffect: false,
				typingTimer: null,
				// Thinking 模式追踪
				isInThinkingMode: false,
				sessionId: null,
				messageId: null,// 消息ID，用于标识当前消息
				thinkingBuffer: '' // 临时存储 Thinking 内容
			}
		},
		// 设置页面标题
		onNavigationBarButtonTap(e) {
			console.log("导航栏按钮点击：", e);
		},
		created() {
			this.debouncedSubmitQuestion = this.debounce(this.submitQuestion, 300)
		},
		mounted() {
			// 获取系统信息
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight || 20;
			this.isIOS = systemInfo.platform === 'ios';
			this.safeAreaBottom = systemInfo.safeAreaInsets ? (systemInfo.safeAreaInsets.bottom || 0) : 0;

			// 初始化消息
			this.initMessages();

			// 滚动到底部
			this.$nextTick(() => {
				this.scrollToBottom();
			});
		},
		methods: {
			// ========== renderjs 通信方法 ==========
			
			// renderjs 回调：接收流式数据
			onStreamData(data) {
				console.log('收到流式数据:', data);
				
				if (data.type === 'thinking') {
					// 第一个 thinking 类型，开启 Thinking 模式
					this.isInThinkingMode = true;
					this.thinkingBuffer = data.content;
					this.processThinkingContent();
				} else if (data.type === 'message') {
					// 判断是否在 Thinking 模式中
					if (this.isInThinkingMode) {
						// 仍在 Thinking 区域内，累积内容
						this.thinkingBuffer += data.content;
						this.processThinkingContent();
					} else {
						// 普通消息内容
						this.handleMessageData(data.content);
					}
				} else if (data.type === 'end') {
					// 流式结束
					console.log("消息id：",data.id);
					
					this.finishStreaming(data.id);
				} else if (data.type === 'error') {
					// 错误处理
					this.handleStreamError(data.error);
				}
			},
			
			// 处理 Thinking 内容（跳过 Thinking，只处理后续内容）
			processThinkingContent() {
				if (this.currentTypingMessage === null) return;
				
				// 检查是否包含 </details> 结束标签
				if (this.thinkingBuffer.includes('</details>')) {
					// Thinking 区域结束，提取 </details> 之后的内容
					this.isInThinkingMode = false;
					
					// 提取 </details> 后面的内容
					const detailsEndIndex = this.thinkingBuffer.indexOf('</details>');
					const contentAfterThinking = this.thinkingBuffer.substring(detailsEndIndex + '</details>'.length);
					
					// 如果有内容，添加到消息队列
					if (contentAfterThinking) {
						this.handleMessageData(contentAfterThinking);
					}
					
					// 清空缓冲区
					this.thinkingBuffer = '';
				}
				// 如果还在 Thinking 区域内，不做任何显示，继续累积
			},
			
			// 处理消息数据（添加到队列）
			handleMessageData(text) {
				if (!text) return;
				
				// 将文本按字符添加到队列
				for (let char of text) {
					this.messageQueue.push(char);
				}
				
				// 如果打字机效果未启动，则启动
				if (!this.isTypingEffect) {
					this.startTypingEffect();
				}
			},
			
			// 启动打字机效果
			startTypingEffect() {
				if (this.isTypingEffect || this.currentTypingMessage === null) return;
				
				this.isTypingEffect = true;
				this.$set(this.chatMessages[this.currentTypingMessage], 'isTyping', false);
				
				const processQueue = () => {
					if (this.messageQueue.length > 0 && this.currentTypingMessage !== null) {
						// 每次取出一个字符
						const char = this.messageQueue.shift();
						const currentContent = this.chatMessages[this.currentTypingMessage].content || '';
						this.$set(this.chatMessages[this.currentTypingMessage], 'content', currentContent + char);
						
						// 每20个字符滚动一次，优化性能
						if (currentContent.length % 20 === 0) {
							this.scrollToBottom();
						}
						
						// 继续处理队列
						this.typingTimer = setTimeout(processQueue, 10);
					} else if (this.messageQueue.length === 0) {
						// 队列为空，等待新数据
						this.typingTimer = setTimeout(processQueue, 50);
					}
				};
				
				processQueue();
			},
			
			// 停止打字机效果
			stopTypingEffect() {
				this.isTypingEffect = false;
				if (this.typingTimer) {
					clearTimeout(this.typingTimer);
					this.typingTimer = null;
				}
				
				// 清空队列，将剩余内容一次性显示
				if (this.messageQueue.length > 0 && this.currentTypingMessage !== null) {
					const remainingText = this.messageQueue.join('');
					const currentContent = this.chatMessages[this.currentTypingMessage].content || '';
					this.$set(this.chatMessages[this.currentTypingMessage], 'content', currentContent + remainingText);
					this.messageQueue = [];
				}
			},
			
			// 完成流式输出
			finishStreaming(id) {
				console.log("消息id2:",id);
				this.stopTypingEffect();
				
				if (this.currentTypingMessage !== null) {
					this.$set(this.chatMessages[this.currentTypingMessage], 'isTyping', false);
					this.currentTypingMessage = null;
				}
				
				// 重置 Thinking 模式状态
				this.isInThinkingMode = false;
				this.thinkingBuffer = '';
				
				this.isProcessing = false;
				this.scrollToBottom();
				
				// 获取下一轮建议问题
				// this.fetchSuggestedQuestions({user: this.sessionId,messageId:id});
			},
			
			// 处理流式错误
			handleStreamError(error) {
				console.error('流式错误:', error);
				this.stopTypingEffect();
				
				// 移除正在输入的消息
				if (this.currentTypingMessage !== null) {
					this.chatMessages.splice(this.currentTypingMessage, 1);
					this.currentTypingMessage = null;
				}
				
				// 重置 Thinking 模式状态
				this.isInThinkingMode = false;
				this.thinkingBuffer = '';
				
				this.isProcessing = false;
				this.handleError({ message: error || '网络异常，请稍后重试' });
			},

			// ========== 用户交互方法 ==========
			
			// 发送消息
			submitQuestion() {
				if (!storage.getHasLogin()) {
					uni.showModal({
						title: '提示',
						content: '您还未登录，请先登录',
						confirmText: '去登录',
						cancelText: '取消',
						success: function(res) {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/login/index'
								});
							}
						},
					});
					return;
				}
				
				if (!this.inputMessage.trim() || this.isProcessing) return;

				const question = this.inputMessage.trim();
				this.lastUserQuestion = question; // 保存问题用于重新生成
				this.inputMessage = '';
				
				// 添加用户消息
				this.chatMessages.push({
					sender: 'user',
					content: question,
					time: this.getCurrentTime(),
					timestamp: Date.now()
				});

				// 添加 AI 正在输入的消息
				const typingMessageIndex = this.chatMessages.push({
					sender: 'ai',
					content: '',
					time: this.getCurrentTime(),
					timestamp: Date.now(),
					isTyping: true
				}) - 1;

				this.currentTypingMessage = typingMessageIndex;
				this.isProcessing = true;
				this.scrollToBottom();
				
				// 通过 renderjs 发起 SSE 请求
				this.startSSERequest(question);
			},
			
			// 启动 SSE 请求（通过 renderjs）
			startSSERequest(question) {
				const url = api.serve + '/uniapp/dify/chat/stream';
				this.sessionId = Date.now().toString()
				const requestData = {
					query: question,
					user: 'user_' + this.sessionId
				};
				
				// 更新 renderjs 数据，触发 SSE 连接
				this.renderjsData = {
					action: 'start',
					url: url,
					data: requestData,
					token: storage.getAccessToken(),
					timestamp: Date.now()
				};
			},
			
			// 停止流式输出
			stopStreaming() {
				console.log('用户中止流式输出');
				
				// 通知 renderjs 停止
				this.renderjsData = {
					action: 'stop',
					timestamp: Date.now()
				};
				
				// 立即停止打字机效果并完成
				this.finishStreaming();
				
				uni.showToast({
					title: '已中止',
					icon: 'none',
					duration: 1500
				});
			},
			
			// 重新生成回复
			regenerateMessage() {
				if (!this.lastUserQuestion || this.isProcessing) return;
				
				// 删除最后一条 AI 消息
				if (this.chatMessages.length > 0 && this.chatMessages[this.chatMessages.length - 1].sender === 'ai') {
					this.chatMessages.pop();
				}
				
				// 添加新的正在输入消息
				const typingMessageIndex = this.chatMessages.push({
					sender: 'ai',
					content: '',
					time: this.getCurrentTime(),
					timestamp: Date.now(),
					isTyping: true
				}) - 1;

				this.currentTypingMessage = typingMessageIndex;
				this.isProcessing = true;
				this.messageQueue = [];
				
				// 重置 Thinking 模式状态
				this.isInThinkingMode = false;
				this.thinkingBuffer = '';
				
				this.scrollToBottom();
				
				// 重新发起请求
				this.startSSERequest(this.lastUserQuestion);
			},

			// ========== 工具方法 ==========
			
			// 错误处理
			handleError(error) {
				let errorMessage = '发生错误';
				if (error.errMsg) {
					errorMessage = error.errMsg;
				} else if (error.message) {
					errorMessage = error.message;
				}

				uni.showToast({
					title: errorMessage,
					icon: 'none',
					duration: 2000
				});
			},

			// 防抖函数
			debounce(func, wait) {
				let timeout;
				return (...args) => {
					clearTimeout(timeout);
					timeout = setTimeout(() => {
						func.apply(this, args);
					}, wait);
				};
			},
			
			// 输入框获取焦点
			onInputFocus() {
				this.$nextTick(() => {
					this.scrollToBottom();
				});
			},
			
			// 滚动到底部
			scrollToBottom() {
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.chat-list').boundingClientRect(data => {
						if (data) {
							this.scrollTop = data.height + 1000;
						}
					}).exec();
				});
			},
			onScroll(e) {
				// 可以添加滚动事件处理
			},
			getCurrentTime() {
				return this.getFormattedTime(new Date());
			},
			getFormattedTime(date) {
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				return `${hours}:${minutes}`;
			},
			
			useQuestion(question) {
				this.inputMessage = question;
			},
			containsKeywords(text) {
				const keywords = ['水稻', '小麦', '玉米', '病虫害', '农药', '化肥', '有机肥', '种植技术'];
				return keywords.some(keyword => text.includes(keyword));
			},
			formatMessage(text) {
				// 将文本中的换行符转换为<br>标签
				return text.replace(/\n/g, '<br>');
			},
			initMessages() {
				// 确保消息有时间戳
				this.chatMessages.forEach(msg => {
					if (!msg.timestamp) {
						msg.timestamp = new Date().getTime();
					}
				});

				// 按时间排序
				this.chatMessages.sort((a, b) => a.timestamp - b.timestamp);
			},
			showDateSeparator(index) {
				// 判断是否需要显示日期分割线
				if (index === 0) return true;

				const currentMsg = this.chatMessages[index];
				const prevMsg = this.chatMessages[index - 1];

				// 如果两条消息相隔超过30分钟，或者是不同日期，显示日期分割线
				return this.isDifferentDay(currentMsg.timestamp, prevMsg.timestamp) ||
					(currentMsg.timestamp - prevMsg.timestamp > 30 * 60 * 1000);
			},
			isDifferentDay(timestamp1, timestamp2) {
				const date1 = new Date(timestamp1);
				const date2 = new Date(timestamp2);

				return date1.getDate() !== date2.getDate() ||
					date1.getMonth() !== date2.getMonth() ||
					date1.getFullYear() !== date2.getFullYear();
			},
			formatDateSeparator(timestamp) {
				const now = new Date();
				const msgDate = new Date(timestamp);

				// 今天
				if (this.isSameDay(msgDate, now)) {
					return '今天 ' + this.getFormattedTime(msgDate);
				}

				// 昨天
				const yesterday = new Date(now);
				yesterday.setDate(now.getDate() - 1);
				if (this.isSameDay(msgDate, yesterday)) {
					return '昨天 ' + this.getFormattedTime(msgDate);
				}

				// 一周内
				const oneWeekAgo = new Date(now);
				oneWeekAgo.setDate(now.getDate() - 7);
				if (msgDate >= oneWeekAgo) {
					const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
					return weekdays[msgDate.getDay()] + ' ' + this.getFormattedTime(msgDate);
				}

				// 其他日期
				return msgDate.getFullYear() + '年' + (msgDate.getMonth() + 1) + '月' + msgDate.getDate() + '日 ' +
					this
					.getFormattedTime(msgDate);
			},
			isSameDay(date1, date2) {
				return date1.getDate() === date2.getDate() &&
					date1.getMonth() === date2.getMonth() &&
					date1.getFullYear() === date2.getFullYear();
			},
			
			// 获取下一轮建议问题列表
			async fetchSuggestedQuestions(data) {
				console.log("获取下一轮建议问题参数",data);
				try {
					const response = await chatStreamSuggested(data);
					
					if (response && response.data) {
						// 假设接口返回的数据格式为 { data: ["问题1", "问题2", ...] }
						if (Array.isArray(response.data) && response.data.length > 0) {
							this.suggestedQuestions = response.data;
						} else if (response.data.questions && Array.isArray(response.data.questions)) {
							// 或者接口返回 { data: { questions: [...] } }
							this.suggestedQuestions = response.data.questions;
						}
					}
				} catch (error) {
					console.error('获取建议问题失败:', error);
					// 失败时保持默认建议问题，不影响用户体验
				}
			}
		},
		// 组件销毁时清理资源
		beforeDestroy() {
			// 停止打字机效果
			this.stopTypingEffect();
			
			// 通知 renderjs 停止连接
			if (this.isProcessing) {
				this.renderjsData = {
					action: 'stop',
					timestamp: Date.now()
				};
			}
			
			// 清理消息队列
			this.messageQueue = [];
		}
	}
</script>

<!-- renderjs 模块：处理 H5/App 端的 SSE 流式连接 -->
<script module="renderModule" lang="renderjs">
	export default {
		data() {
			return {
				eventSource: null,
				reader: null,
				isReading: false
			};
		},
		methods: {
			// 监听 prop 变化
			onDataChange(newValue, oldValue, ownerInstance, instance) {
				if (!newValue || !newValue.action) return;
				
				if (newValue.action === 'start') {
					this.startSSE(newValue, ownerInstance);
				} else if (newValue.action === 'stop') {
					this.stopSSE();
				}
			},
			
			// 启动 SSE 连接
			async startSSE(config, ownerInstance) {
				// 先停止之前的连接
				this.stopSSE();
				
				const { url, data, token } = config;
				
				try {
					// 使用 fetch API 建立 SSE 连接
					const response = await fetch(url, {
						method: 'POST',
						headers: {
							'Content-Type': 'application/json',
							'Accept': 'text/event-stream',
							'Authorization': `Bearer ${token}`
						},
						body: JSON.stringify(data)
					});
					
					if (!response.ok) {
						throw new Error(`HTTP error! status: ${response.status}`);
					}
					
					// 获取 reader
					this.reader = response.body.getReader();
					const decoder = new TextDecoder('utf-8');
					this.isReading = true;
					
					let buffer = '';
					this.eventType    = '';          // 当前事件名
					this.dataBuffer   = [];          // 当前事件的所有 data 行
					
					// 读取流式数据
					while (this.isReading) {
						const { done, value } = await this.reader.read();
						
						if (done) {
							console.log('SSE 流结束');
							ownerInstance.callMethod('onStreamData', { type: 'end' , id: this.messageId});
							break;
						}
						
						// 解码数据
						buffer += decoder.decode(value, { stream: true });
						
						// 按行处理
						const lines = buffer.split('\n');
						buffer = lines.pop() || ''; // 保留最后不完整的行						
						// buffer = lines.pop(); // 保留最后不完整的行
						
						for (const line of lines) {
							this.processLine(line, ownerInstance);
						}
					}
					
				} catch (error) {
					console.error('SSE 连接错误:', error);
					ownerInstance.callMethod('onStreamData', { 
						type: 'error', 
						error: error.message || '连接失败' 
					});
				} finally {
					this.stopSSE();
				}	
			},
			// 处理单行数据
			processLine(line, ownerInstance) {
				// console.log("处理单行数据:",line);
				if (!line.trim()) return;
				
				// 解析 SSE 格式
				if (line.startsWith('event:')) {
					// event: message
					return;
				}
				
				if (line.startsWith('data:') || line != '') {
					let data = line;
					if (line.startsWith('data:') ){
						data = data.substring(5).trim();
					}
					 			
					if (!data || data.includes("ping") ) return;
					
					// 过滤掉 MESSAGE_END 等元数据事件（JSON 格式）
					if (data.startsWith('{') && data.includes('"eventType"')) {
						try {
							const jsonData = JSON.parse(data);
							// 如果是 MESSAGE_END 事件，通知结束
							if (jsonData.eventType === 'MESSAGE_END' || jsonData.event === 'message_end') {
								console.log('收到 MESSAGE_END 事件，流式结束');
								this.messageId = jsonData.id
								ownerInstance.callMethod('onStreamData', { type: 'end' , id: this.messageId });
								return;
							}
							// 其他元数据事件也忽略
							return;
						} catch (e) {
							// 不是 JSON，继续处理
						}
					}
					
					// 检查是否是 Thinking 内容
					if (data.includes('<details') && data.includes('<summary>')) {
						ownerInstance.callMethod('onStreamData', {
							type: 'thinking',
							content: data
						});
					} else {
						// 普通消息内容
						ownerInstance.callMethod('onStreamData', {
							type: 'message',
							content: data
						});
					}
				}
			},
			
			// 停止 SSE 连接
			stopSSE() {
				this.isReading = false;
				
				if (this.reader) {
					try {
						this.reader.cancel();
					} catch (e) {
						console.error('关闭 reader 失败:', e);
					}
					this.reader = null;
				}
				
				if (this.eventSource) {
					this.eventSource.close();
					this.eventSource = null;
				}
			}
		}
	};
</script>

<style>
	/* 容器样式 */
	.container {
		position: relative;
		min-height: 100vh;
		background-color: #f5f5f5;
		overflow: hidden;
		/* 防止内容溢出 */
	}

	/* 聊天容器 */
	.chat-container {
		padding: 20rpx 30rpx;
		box-sizing: border-box;
		background-color: #f8f8f8;
		background-image: url('/static/images/chat-bg-pattern.png');
		background-size: 300rpx;
		background-blend-mode: overlay;
		background-opacity: 0.05;
		-webkit-overflow-scrolling: touch;
		/* 增强iOS滚动体验 */
	}

	.chat-list {
		padding-bottom: 30rpx;
	}

	/* 消息项 */
	.message-item {
		display: flex;
		margin-bottom: 30rpx;
		position: relative;
	}

	.message-ai {
		justify-content: flex-start;
	}

	.message-user {
		justify-content: flex-end;
	}

	/* 头像 */
	.avatar-container {
		width: 90rpx;
		height: 90rpx;
		flex-shrink: 0;
	}

	.avatar {
		width: 90rpx;
		height: 90rpx;
		border-radius: 50%;
		background-color: #e0e0e0;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
		object-fit: cover;
	}

	/* 消息内容 */
	.message-content {
		max-width: 70%;
		margin: 0 20rpx;
		display: flex;
		flex-direction: column;
	}

	.user-content {
		align-items: flex-end;
	}

	.message-bubble {
		padding: 24rpx;
		border-radius: 24rpx;
		position: relative;
		margin-bottom: 10rpx;
		word-wrap: break-word;
		min-width: 80rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
		transition: all 0.3s ease;
		max-width: 100%;
	}

	.ai-bubble {
		background-color: #e8f5e9;
		border-top-left-radius: 4rpx;
	}

	.user-bubble {
		background-color: #e3f2fd;
		border-top-right-radius: 4rpx;
	}

	.message-text {
		font-size: 28rpx;
		color: #333;
		line-height: 1.5;
		word-break: break-all;
	}

	.message-time {
		font-size: 22rpx;
		color: #999;
	}
	
	/* 消息操作按钮 */
	.message-actions {
		display: flex;
		gap: 16rpx;
		margin-top: 12rpx;
	}
	
	.action-button {
		display: flex;
		align-items: center;
		padding: 8rpx 16rpx;
		background-color: #f5f5f5;
		border-radius: 20rpx;
		border: 1rpx solid #e0e0e0;
		transition: all 0.2s;
	}
	
	.action-button-hover {
		background-color: #e8f5e9;
		border-color: #a5d6a7;
	}
	
	.action-icon {
		font-size: 24rpx;
		margin-right: 6rpx;
	}
	
	.action-text {
		font-size: 24rpx;
		color: #666;
	}

	/* 输入区域 */
	.input-container {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		padding: 20rpx 30rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
		display: flex;
		flex-direction: column;
		z-index: 10;
	}

	.input-wrapper {
		display: flex;
		align-items: flex-end;
	}

	.message-input {
		flex: 1;
		min-height: 70rpx;
		max-height: 120rpx;
		border-radius: 35rpx;
		background-color: #f5f5f5;
		padding: 15rpx 30rpx;
		font-size: 28rpx;
		color: #333;
		border: 1rpx solid #e0e0e0;
		line-height: 1.4;
	}

	.send-button {
		margin-left: 16rpx;
		width: 76rpx;
		height: 76rpx;
		border-radius: 50%;
		background-color: transparent;
		background-image: none;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.2s ease;
		position: relative;
		align-self: center;
	}

	.send-button.disabled {
		background-color: transparent;
		background-image: none;
		opacity: 1;
	}
	
	/* 中止按钮 */
	.stop-button {
		margin-left: 16rpx;
		width: 76rpx;
		height: 76rpx;
		border-radius: 50%;
		background-color: #ff5252;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.2s ease;
		align-self: center;
	}
	
	.stop-icon {
		font-size: 36rpx;
		color: white;
	}

	.button-hover {
		transform: scale(0.95);
	}

	@keyframes pulse {
		0% {
			transform: scale(1);
		}

		50% {
			transform: scale(0.95);
		}

		100% {
			transform: scale(1);
		}
	}

	.send-button:active:not(.disabled) {
		animation: pulse 0.3s ease-in-out;
	}

	/* 删除或注释掉之前的样式 */
	.send-icon {
		display: none;
	}

	.send-icon:before {
		display: none;
	}

	.send-icon-text {
		display: none;
	}

	/* 推荐问题区域 */
	.suggested-questions {
		display: flex;
		white-space: nowrap;
		margin-bottom: 15rpx;
		padding: 5rpx 0;
	}

	.question-chip {
		display: inline-block;
		padding: 12rpx 20rpx;
		margin-right: 15rpx;
		background-color: #e8f5e9;
		color: #4CAF50;
		font-size: 24rpx;
		border-radius: 30rpx;
		border: 1rpx solid #a5d6a7;
	}

	/* AI正在输入的样式 */
	.message-bubble.ai-bubble.typing {
		background-color: #f0f0f0;
	}

	.typing-indicator {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 40rpx;
		padding: 0 20rpx;
	}

	.typing-dot {
		width: 10rpx;
		height: 10rpx;
		margin: 0 5rpx;
		background-color: #4CAF50;
		border-radius: 50%;
		opacity: 0.5;
		animation: typingAnimation 1.4s infinite both;
	}

	.typing-dot:nth-child(2) {
		animation-delay: 0.2s;
	}

	.typing-dot:nth-child(3) {
		animation-delay: 0.4s;
	}

	@keyframes typingAnimation {
		0% {
			opacity: 0.3;
			transform: translateY(0);
		}

		50% {
			opacity: 1;
			transform: translateY(-5rpx);
		}

		100% {
			opacity: 0.3;
			transform: translateY(0);
		}
	}

	/* 关键词高亮 */
	.message-text.highlight {
		color: #2E7D32;
		font-weight: 500;
	}

	/* 欢迎消息特殊样式 */
	.welcome {
		background-color: #e3f2fd !important;
		border-left: none !important;
		border-radius: 24rpx !important;
	}

	/* 日期分割线样式 */
	.date-separator {
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 20rpx 0;
	}

	.date-separator text {
		background-color: rgba(0, 0, 0, 0.1);
		color: #666;
		font-size: 24rpx;
		padding: 4rpx 20rpx;
		border-radius: 20rpx;
	}

	/* 纸飞机图标 */
	.plane-svg {
		display: none;
	}

	.send-icon-image {
		width: 76rpx;
		height: 76rpx;
	}

	.material-icon {
		font-family: 'Material Icons';
		font-weight: normal;
		font-style: normal;
		font-size: 48rpx;
		line-height: 1;
		letter-spacing: normal;
		text-transform: none;
		display: inline-block;
		white-space: nowrap;
		word-wrap: normal;
		direction: ltr;
		-webkit-font-smoothing: antialiased;
		color: white;
	}

	/* 删除不需要的导航栏样式 */
	.custom-navbar {
		display: none;
	}

	.navbar-bg,
	.navbar-content,
	.navbar-left,
	.navbar-title,
	.navbar-right,
	.back-icon,
	.arrow-left {
		display: none;
	}
	
	/* renderjs 容器（隐藏） */
	.renderjs-container {
		display: none;
		width: 0;
		height: 0;
		opacity: 0;
		position: absolute;
		pointer-events: none;
	}
</style>