<template>
	<view class="chat-container">
		<scroll-view class="messages" scroll-y :scroll-top="scrollTop" scroll-with-animation>
			<block v-for="message in messages" :key="message.id">
				<view :class="['message', message.user]">
					<view class="avatar-container">
						<image :src="message.user === 'user' ? userAvatar : '/static/机器人.png'" class="avatar"
							mode="aspectFill" />
						<text class="sender-name">{{ message.user === 'user' ? userInfo.nickName : 'AI助理' }}</text>
					</view>
					<view class="message-content"> <!-- 改为 message-content 类 -->
						<template v-if="message.message.includes('相关资料来源')">
							<view>{{ getMainContent(message.message) }}</view>
							<view class="source-section" v-if="minioUrls && minioUrls.length > 0">
								<view class="source-title">相关资料来源：</view>
								<view class="source-links">
									<view v-for="(item, index) in minioUrls" :key="index" class="source-link"
										@tap="copyLink(item.url)">
										{{ item.object_name }}
									</view>
								</view>
							</view>
							<!-- <view v-if="message.user === 'bot' && message.audioData && message.audioData.visible"
								class="audio-controls">
								<view class="audio-btn" @tap="playAudio(message.audioData.base64, message.id)">
									<image :src="message.audioData.isPlaying ? '/static/pause.svg' : '/static/play.svg'"
										class="audio-icon" mode="aspectFit" />
								</view>
								<view class="audio-progress" v-if="message.audioData.progress">
									{{ message.audioData.progress }}%
								</view>
							</view> -->
						</template>
						<template v-else>
							{{ message.message }}

						</template>
					</view>
				</view>
			</block>
		</scroll-view>
		<!-- 添加新建对话按钮 -->
		<!-- <view class="new-chat-btn">
			<button @tap="startNewChat" class="btn-new">新建对话</button>
		</view> -->
		<view class="input-container">
			<!-- 图片预览区域和上传按钮组合 -->
			<scroll-view class="image-upload-area" scroll-x :show-scrollbar="false"
				v-if="selectedImages.length > 0 || selectedVideos.length > 0 || selectedDocs.length > 0">
				<view class="image-list">
					<!-- 图片预览 -->
					<view class="image-preview" v-for="(image, index) in selectedImages" :key="'img-'+index">
						<image :src="image" mode="aspectFill" class="preview-img" />
						<view class="delete-btn" @tap="removeImage(index)">
							<text class="delete-icon">×</text>
						</view>
					</view>
					<!-- 视频预览 -->
					<view class="image-preview" v-for="(video, index) in selectedVideos" :key="'vid-'+index">
						<view class="video-preview-container">
							<image src="/static/video-placeholder.svg" mode="aspectFill" class="preview-img" />
							<!-- <image src="/static/play-icon.svg" class="play-icon" /> -->
						</view>
						<view class="delete-btn" @tap="removeVideo(index)">
							<text class="delete-icon">×</text>
						</view>
					</view>
					<!-- 文档预览 -->
					<view class="doc-preview" v-for="(doc, index) in selectedDocs" :key="'doc-'+index">
						<view class="doc-preview-container">
							<image src="/static/doc-icon.svg" mode="aspectFit" class="doc-icon" />
							<text class="doc-name">{{ doc.name }}</text>
						</view>
						<view class="delete-btn" @tap="removeDoc(index)">
							<text class="delete-icon">×</text>
						</view>
					</view>
					<!-- 继续上传按钮 -->
					<view class="upload-btn" @tap="chooseMedia"
						v-if="selectedImages.length < maxImages && selectedVideos.length < maxVideos && selectedDocs.length < maxDocs">
						<image src="/static/upload.svg" class="upload-icon" mode="aspectFit" />
					</view>
				</view>
			</scroll-view>

			<view class="input-wrapper">
				<textarea v-model="userInput" @keydown="handleKeydown" placeholder="有问题可以咨询我..." maxlength="100"
					class="input-textarea" />
				<!-- 添加设置按钮 -->
				<view class="set_btn">
					<image src="/static/images/setting.png" @tap="showVoiceSettings" class="settings-icon" />
					<view
						v-if="!userInput.trim() && !selectedImages.length && !selectedVideos.length && !selectedDocs.length"
						class="upload-options">
						<image src="/static/upload.svg" @tap="chooseMedia" class="upload-icon" />
					</view>
					<image v-else src="/static/sendm.svg" @tap="sendMessage" class="upload-img"></image>
				</view>
			</view>
		</view>
		<!-- 添加语音设置弹窗 -->
		<uni-popup ref="voiceSettingsPopup" type="center" :mask-click="false" mask-background-color="rgba(0, 0, 0, 0.6)"
			@change="handlePopupChange">
			<view class="settings-popup">
				<view class="settings-header">
					<text class="settings-title">语音设置</text>
					<text class="close-btn" @tap="closeVoiceSettings">×</text>
				</view>
				<view class="settings-content">
					<view class="settings-item">
						<text class="item-label">语言</text>
						<picker :value="languageOptions.indexOf(voiceSettings.language)" :range="languageOptions"
							@change="handleLanguageChange">
							<view class="picker-value">{{voiceSettings.language || '请选择'}}</view>
						</picker>
					</view>

					<view class="settings-item">
						<text class="item-label">声音名称</text>
						<picker :value="currentVoices.findIndex(v => v.name === voiceSettings.voice_name)"
							:range="currentVoices" range-key="name" @change="handleVoiceNameChange">
							<view class="picker-value">{{voiceSettings.voice_name || '请选择'}}</view>
						</picker>
					</view>

					<view class="settings-item">
						<text class="item-label">性别</text>
						<view class="picker-value">{{voiceSettings.gender}}</view>
					</view>

					<view class="settings-item">
						<text class="item-label">风格</text>
						<picker :value="styleOptions.indexOf(voiceSettings.style)" :range="styleOptions"
							@change="handleStyleChange">
							<view class="picker-value">{{voiceSettings.style || '请选择'}}</view>
						</picker>
					</view>

					<view class="settings-item">
						<text class="item-label">语速 ({{voiceSettings.rate}})</text>
						<slider :value="parseInt(voiceSettings.rate)" @change="handleRateChange" min="0" max="100"
							show-value />
					</view>

					<view class="settings-item">
						<text class="item-label">音量 ({{voiceSettings.volume}})</text>
						<slider :value="parseInt(voiceSettings.volume)" @change="handleVolumeChange" min="0" max="100"
							show-value />
					</view>
				</view>
				<button class="save-btn" @tap="saveVoiceSettings">保存设置</button>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import MarkdownIt from "markdown-it";
	const md = new MarkdownIt();
	export default {
		data() {
			return {
				messages: [{
					user: "bot",
					messageType: "TEXT",
					message: "欢迎使用智能AI助理",
					html: "",
					time: "",
					done: true,
				}, ],
				userInput: "",
				websocket: null,
				AiUrl: '',
				apiUrl: 'https://ylaiapi.raycos.com.cn', //https://ylaiapi.raycos.com.cn
				scrollTop: 0,
				tweaks: {},
				userAvatar: '/static/用户.png',
				userInfo: {},
				level: 1,
				idArray: [],
				minioUrls: [], // 新增：用于存储 Minio URL
				generating: false, // 是否正在生成回复
				typewriterTimer: null,
				currentIndex: 0,
				fullMessage: '',
				session_id: "",
				platform: {
					type: '', // 平台类型
					name: '', // 平台名称
					isWeixin: false
				},
				selectedImages: [], // 存储已上传图片的信息
				uploadedFiles: [], // 存储上传后的文件信息
				maxImages: 9,
				selectedVideos: [], // 存储已选择的视频
				uploadedVideos: [], // 存储已上传的视频信息
				maxVideos: 1, // 限制视频上传数量
				currentAudioContext: null,
				currentPlayingMessage: null,
				currentPlayingMessageId: null, // 添加：跟踪当前正在播放的消息ID
				selectedDocs: [], // 存储已选择的文档
				uploadedDocs: [], // 存储已上传的文档信息
				maxDocs: 3, // 限制文档上传数量
				voiceSettings: {
					language: 'zh-cn',
					voice_name: '',
					gender: '',
					style: '',
					rate: '+10%',
					volume: '+20%'
				},
				voicesData: {}, // 存储接口返回的语音数据
				languageOptions: [], // 可选择的语言
				currentVoices: [], // 当前语言下的声音选项
				styleOptions: [], // 当前选择的声音可用的风格
			};
		},
		created() {

		},
		onLoad() {
			// this.getKbmUrl()
			this.loadUserInfo()
			this.getPlatformInfo();
		},
		onShow() {
			this.getKbmUrl()
		},
		watch: {
			messages: {
				handler() {
					this.$nextTick(() => {
						this.scrollToBottom();
					});
				},
				deep: true
			}
		},
		methods: {
			/* 语速及音量 */
			handleRateChange(e) {
				const value = e.detail.value;
				// 将滑块值转换为百分比格式
				this.voiceSettings.rate = value > 0 ? `+${value}%` : `${value}%`;
			},

			handleVolumeChange(e) {
				const value = e.detail.value;
				// 将滑块值转换为百分比格式
				this.voiceSettings.volume = value > 0 ? `+${value}%` : `${value}%`;
			},
			// 添加新建对话方法
			startNewChat() {
				uni.showModal({
					title: '确认新建对话',
					content: '是否清空当前对话内容开始新的对话？',
					success: (res) => {
						if (res.confirm) {
							// 重置消息列表，只保留欢迎息
							this.messages = [{
								user: "bot",
								messageType: "TEXT",
								message: "欢迎使用智能AI助理",
								html: "",
								time: "",
								done: true,
							}];

							// 清空session_id
							this.session_id = "";

							// 清空MinioUrls
							this.minioUrls = [];

							// 重置其他相关状态
							this.generating = false;
							this.currentIndex = 0;
							this.fullMessage = '';

							// 显示提示
							uni.showToast({
								title: '已开始新对话',
								icon: 'success',
								duration: 1500
							});
						}
					}
				});
			},
			// 获取平台信息
			getPlatformInfo() {
				try {
					const systemInfo = uni.getSystemInfoSync();
					// console.log('系统信息：', systemInfo);

					// 判断平台类型
					// #ifdef MP-WEIXIN
					this.platform.type = 'mp-weixin';
					this.platform.name = '微信小程序';
					this.platform.isWeixin = true;
					// #endif

					// #ifdef MP-ALIPAY
					this.platform.type = 'mp-alipay';
					this.platform.name = '支付宝小程序';
					// #endif

					// #ifdef MP-BAIDU
					this.platform.type = 'mp-baidu';
					this.platform.name = '百度小程序';
					// #endif

					// #ifdef MP-TOUTIAO
					this.platform.type = 'mp-toutiao';
					this.platform.name = '头条小程序';
					// #endif

					// #ifdef H5
					this.platform.type = 'h5';
					this.platform.name = 'H5';
					// 在H5中判断是否在微信浏览器中
					if (navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1) {
						this.platform.isWeixin = true;
						this.platform.name = 'H5微信浏览器';
					}
					// #endif

					// #ifdef APP-PLUS
					this.platform.type = 'app';
					this.platform.name = 'App';
					// #endif

					// console.log('当前平台：', this.platform);

					// 获取更详细的平台信息
					const platformInfo = {
						brand: systemInfo.brand, // 手机品牌
						model: systemInfo.model, // 手机型号
						system: systemInfo.system, // 操作系统版本
						platform: systemInfo.platform, // 客户端平台
						SDKVersion: systemInfo.SDKVersion, // 小程序基库版本
						version: systemInfo.version, // 微信版本号
					};

					// console.log('平台详细信息：', platformInfo);

					return this.platform;

				} catch (error) {
					console.error('获取平台信息失败：', error);
					return {
						type: 'unknown',
						name: '未知平台',
						isWeixin: false
					};
				}
			},
			getMainContent(message) {
				const parts = message.split('相关资料来源');
				return parts[0].trim();
			},

			extractUrls(message) {
				const urlRegex = /href="([^"]+)"/g;
				const urls = [];
				let match;

				while ((match = urlRegex.exec(message)) !== null) {
					urls.push(match[1]);
				}
				return urls;
			},

			getFileName(url) {
				try {
					const decodedUrl = decodeURIComponent(url);
					const parts = decodedUrl.split('/');
					let fileName = parts[parts.length - 1];
					// 如果文件名过长，截断
					if (fileName.length > 30) {
						fileName = fileName.substring(0, 27) + '...';
					}
					return fileName;
				} catch (e) {
					return '文件';
				}
			},

			// 修改 copyLink 方法
			copyLink(url) {
				if (!url) return;

				uni.setClipboardData({
					data: url,
					success: () => {
						uni.showToast({
							title: '链接已复制',
							icon: 'none',
							duration: 1500
						});
					}
				});
			},

			loadUserInfo() {
				const userDataString = uni.getStorageSync('userInfo');
				if (userDataString) {
					this.userInfo = JSON.parse(userDataString);
					this.userAvatar = this.userInfo.avatarUrl || '/static/用户.png'; // Fallback to default if no avatar
				}
			},
			scrollToBottom() {
				// 使用一个很大的值来确保滚动到底部
				this.scrollTop += 9999;
				// 重置 scrollTop 以便下次动生效
				// this.$nextTick(() => {
				//   this.scrollTop = 0;
				// });
			},
			/* 请求链接 */
			getKbmUrl() {
				let userDataString;

				if (uni.getStorageSync('userData') == '') {
				
					// 跳转到个人页面
					uni.switchTab({
						url: '/pages/my/index',
						success: function() {
						},
						fail: function(err) {
							console.error('Failed to switch to personal page:', err);
						}
					});
					return;
				} else {
					userDataString = JSON.parse(uni.getStorageSync('userData'));
				}

				uni.request({
					url: this.apiUrl + '/wechat/getUserInfo',
					method: 'POST',
					data: {
						openid: userDataString.openid
					},
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						console.log('获取用户信息成功', res.data);
						this.AiUrl = this.apiUrl + '/chatbot/multimodal'
						this.level = res.data.data.level
					},
					fail: (err) => {
						console.error('获取用户信息失败', err);
						uni.showToast({
							title: '获取用户信息失败，请重试',
							icon: 'none'
						});
					}
				});

				/* uni.request({
					url: this.apiUrl + '/wechat/getKbmUrl', // 确保这是正确的URL
					method: 'POST',
					data: {
						openid: userDataString.openid
					}, //JSON.stringify()
					header: {
						'content-type': 'application/x-www-form-urlencoded' // 设置正确的内容类型
					},
					success: (res) => {
						console.log('Login response:', res.data);
						if (res.data && res.data.status == 200) {
							this.tweaks = res.data.data.tweaks
							this.connectWebSocket();
						}

					},
					fail: (err) => {
						console.error('请求失败', err);
						uni.showToast({
							title: '请求失败，请重试',
							icon: 'none'
						});
					}
				}) */


			},
			getUuid() {
				return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
					/[xy]/g,
					function(c) {
						var r = (Math.random() * 16) | 0,
							v = c == "x" ? r : (r & 0x3) | 0x8;
						return v.toString(16);
					}
				);
			},
			connectWebSocket() {
				const wsUrl = this.AiUrl
				//'http://ai.raycos.net/api/v1/run/c7ea3a2d-f50c-4936-b96c-3fe7c34fa062?stream=false';
				// 使用 XMLHttpRequest 替代 fetch
				uni.request({
					url: wsUrl,
					method: 'POST',
					data: JSON.stringify({}), // 如果需要发送数据，可以在这里加
					header: {
						'content-type': 'application/json'
					},
					success: (res) => {
						if (res.statusCode === 200) {
							const result = res.data;
							this.handleWebSocketMessage(result);
						} else {
							console.error("请求失败:", res.statusCode);
						}
					},
					fail: (err) => {
						console.error("网络连接错误:", err);
					}
				});
				// 如果需要发送数据，可以在这里添加
			},

			// 新增方法来处理消息
			handleWebSocketMessage(result) {
			

				// 检查消息是否完结
				if (result.done) {
					this.messages[this.messages.length - 1].done = true;
					return;
				}

				if (this.messages[this.messages.length - 1].done) {
					// 添加新的消息
					this.messages.push({
						time: Date.now(),
						message: result.content,
						messageType: "TEXT",
						user: "bot",
						done: false,
					});
				} else {
					// 更新最后一条消息
					let lastMessage = this.messages[this.messages.length - 1];
					lastMessage.message += result.content;
					this.messages[this.messages.length - 1] = lastMessage;
				}
			},
			// 修改发送消息方法
			async sendMessage() {
				/* // 确保在发送新消息前停止当前音频
				if (this.currentAudioContext) {
					this.stopCurrentAudio();
				} */

				const message = this.userInput.trim();
				if (!message && !this.selectedImages.length && !this.selectedVideos.length && !this.selectedDocs.length) {
					return;
				}

				// 构建用户消息对象
				const userMessage = {
					id: this.getUuid(),
					user: "user",
					messageType: "TEXT",
					message: message,
					time: Date.now(),
					done: true,
					images: this.uploadedFiles.map(file => file.url),
					videos: this.uploadedVideos.map(file => file.url),
					docs: this.uploadedDocs.map(file => file.url)
				};
				this.messages.push(userMessage);

				// 清空输入框和媒体文件
				this.userInput = "";
				this.selectedImages = [];
				this.uploadedFiles = [];
				this.selectedVideos = [];
				this.uploadedVideos = [];
				this.selectedDocs = [];
				this.uploadedDocs = [];
				this.scrollToBottom();

				// 添加AI助理的消息
				const botMessage = {
					id: this.getUuid(),
					user: "bot",
					messageType: "TEXT",
					message: "正在思考中...",
					time: Date.now(),
					done: false,
				};
				this.messages.push(botMessage);

				try {
					const response = await uni.request({
						url: this.AiUrl,
						method: 'POST',
						header: {
							'Content-Type': 'application/json'
						},
						data: {
							message: message,
							image_urls: userMessage.images,
							video_urls: userMessage.videos, // 添加视频URL到请求
							documents_file: userMessage.docs, // 添加文档URL到请求
							chat_config_id: '17',
							user_id: this.userInfo.phoneNumber,
							session_id: this.session_id || "",
						}
					});
					// 检查响应状态和数据
					if (response.statusCode !== 200 || !response.data || !response.data.data?.answer) {
						throw new Error('Invalid response from server');
					}

					if (this.level === '0' && response.data.data?.milvus_ids) {
						await this.getMinioUrls({
							ids: response.data.data.milvus_ids
						});
					}

					this.session_id = response.data.data.session_id;
					await this.handleResponse(response.data, botMessage);
					// 如果有音频，播放音频
					if (
						response.data.data.audio_info &&
						response.data.data.audio_info.audio
					) {
						this.playAudio(response.data.data.audio_info.audio);
					}

				} catch (error) {
					console.error("Error sending message:", error);
					// 找到最后一条消息（应该是机器人的消息）并更新它
					const lastMessage = this.messages[this.messages.length - 1];
					if (lastMessage && lastMessage.user === 'bot') {
						lastMessage.message = "抱歉，处理消息时出现错误，请重试。";
						lastMessage.done = true;
					}

					uni.showToast({
						title: '发送消息失败，请重试',
						icon: 'none'
					});
				}
			},
			// 修改停止当前音频的方法
			stopCurrentAudio() {
				try {
					if (this.currentAudioContext) {
						// 先停止播放
						this.currentAudioContext.stop();
						
						// 更新消息的播放状态
						if (this.currentPlayingMessageId) {
							const message = this.messages.find(m => m.id === this.currentPlayingMessageId);
							if (message && message.audioData) {
								message.audioData.isPlaying = false;
								message.audioData.progress = 0;
							}
						}

						// 销毁音频实例
						this.currentAudioContext.destroy();
						this.currentAudioContext = null;
						this.currentPlayingMessageId = null;
					}
				} catch (error) {
					console.error('停止音频时出错:', error);
					// 即使出错也要重置状态
					this.currentAudioContext = null;
					this.currentPlayingMessageId = null;
				}
			},

			// 修改播放音频方法
			playAudio(audioBase64, messageId) {
				try {
					// 如果有正在播放的音频，先停止它
					if (this.currentAudioContext) {
						this.stopCurrentAudio();
					}

					// 创建新的音频上下文
					const innerAudioContext = uni.createInnerAudioContext();
					
					// 设置音频源
					innerAudioContext.src = audioBase64;

					// 更新状态和引用
					this.currentAudioContext = innerAudioContext;
					this.currentPlayingMessageId = messageId;

					// 更新消息的播放状态
					const message = this.messages.find(m => m.id === messageId);
					if (message && message.audioData) {
						message.audioData.isPlaying = true;
						message.audioData.progress = 0;
					}

					// 监听播放错误
					innerAudioContext.onError((res) => {
						console.error('音频播放错误:', res.errMsg);
						uni.showToast({
							title: '音频播放失败',
							icon: 'none'
						});
						this.stopCurrentAudio();
					});

					// 播放结束后的处理
					innerAudioContext.onEnded(() => {
						this.stopCurrentAudio();
					});

					// 开始播放
					innerAudioContext.play();
				} catch (error) {
					console.error('播放音频失败:', error);
					this.stopCurrentAudio();
				}
			},

			// 修改组件销毁时的处理
			beforeDestroy() {
				// 确保在组件销毁前停止并清理音频
				if (this.currentAudioContext) {
					this.stopCurrentAudio();
				}
			},

			// 修改 getMinioUrls 方法
			async getMinioUrls(idObject) {
				this.minioUrls = []
				try {
					const response = await uni.request({
						url: `${this.apiUrl}/milvus/getMinioURl`,
						method: 'POST',
						data: idObject,
						header: {
							'Content-Type': 'application/json'
						}
					});

					if (response.statusCode === 200 && response.data?.data) {
						this.minioUrls = response.data.data;
						console.log("Received Minio URLs:", this.minioUrls);
					} else {
						this.minioUrls = [];
						console.error("Invalid response format:", response);
					}
				} catch (error) {
					console.error("Error fetching Minio URLs:", error);
					this.minioUrls = [];
					uni.showToast({
						title: '获取资源链接失败',
						icon: 'none'
					});
				}
			},

			// 修改 handleResponse 方法
			async handleResponse(value, existingMessage) {
				try {
					if (!value?.data?.answer) {
						throw new Error('Invalid response format');
					}

					const data = value.data.answer;
					this.fullMessage = data;
					this.currentIndex = 0;

					// 先设置基本消息结构
					existingMessage.message = '';
					existingMessage.done = false;

					// 如果有音频数据，创建完整的音频数据结构
					if (value.data.audio_info?.audio) {
						existingMessage.audioData = {
							base64: value.data.audio_info.audio,
							isPlaying: false,
							progress: 0,
							visible: true // 添加可见性标志
						};
					}

					// 开始打字效果
					this.startTypewriter(existingMessage);

				} catch (error) {
					console.error("Error handling response:", error);
					existingMessage.message = "抱歉，处理响应时出现错误。";
					existingMessage.done = true;
				}
			},

			// 新的打字效果实现
			startTypewriter(existingMessage) {
				// 清除可能存在的旧计时器
				if (this.typewriterTimer) {
					clearInterval(this.typewriterTimer);
					this.typewriterTimer = null;
				}

				const doTypewriter = () => {
					if (this.currentIndex < this.fullMessage.length) {
						// 保存有的音频数据
						const audioData = existingMessage.audioData;

						// 新消息内容
						existingMessage.message = this.fullMessage.slice(0, this.currentIndex + 1);

						// 恢复音频数据
						if (audioData) {
							existingMessage.audioData = audioData;
						}

						this.currentIndex++;

						// 使用 nextTick 确保视图更新
						this.$nextTick(() => {
							this.scrollToBottom();
						});

						// 使用 setTimeout 代替 setInterval
						this.typewriterTimer = setTimeout(() => {
							doTypewriter();
						}, 30);
					} else {
						// 打字效果完成
						// 保存原有的音频数据
						const audioData = existingMessage.audioData;

						if (this.minioUrls && this.minioUrls.length > 0) {
							existingMessage.message += '\n\n相关资料来源';
						}

						// 恢复音频数据
						if (audioData) {
							existingMessage.audioData = audioData;
						}

						existingMessage.done = true;
						this.typewriterTimer = null;
						this.scrollToBottom();
					}
				};

				// 立即开始打字效果
				doTypewriter();
			},
			// 修改 renderMarkdown 方法以保留 HTML 标签
			/* renderMarkdown(rawMarkdown) {
				if (typeof rawMarkdown !== 'string') {
					console.warn('Invalid input for renderMarkdown:', rawMarkdown);
					return '';
				}

				try {
					const md = new MarkdownIt({
						html: true, // 允许 HTML 标签
						breaks: true,
						linkify: true
					});

					// 自定义链接渲染
					md.renderer.rules.link_open = (tokens, idx) => {
						const token = tokens[idx];
						const hrefIndex = token.attrIndex('href');
						const href = token.attrs[hrefIndex][1];
						return `<text class="link" style="color: #1296db; text-decoration: underline;" data-href="${href}">`;
					};
					md.renderer.rules.link_close = () => '</text>';

					// 自定义段落染
					md.renderer.rules.paragraph_open = () =>
						'<p style="font-size: 12px; margin: 5px 0 10px; padding: 0; line-height: 22px;">';

					return md.render(rawMarkdown);
				} catch (error) {
					console.error('Markdown rendering error:', error);
					return rawMarkdown;
				}
			}, */

			// 修改 sendMessage 方法
			/* async sendMessage() {
				const wsUrl = this.AiUrl;
				let message = this.userInput.trim();
				if (message) {
					// 添加用户消息
					const userMessage = {
						id: this.getUuid(),
						user: "user",
						messageType: "TEXT",
						message: message,
						time: Date.now(),
						done: true,
					};
					this.messages.push(userMessage);

					// 清空输入框并滚动
					this.userInput = "";
					this.scrollToBottom();

					// 添加AI助理的消息
					const botMessage = {
						id: this.getUuid(),
						user: "bot",
						messageType: "TEXT",
						message: "正在思考中...", // 添加加载提示
						time: Date.now(),
						done: false,
					};
					this.messages.push(botMessage);

					try {
						const response = await uni.request({
							url: wsUrl,
							method: 'POST',
							header: {
								'Content-Type': 'application/json'
							},
							data: {
								message: message,
								chat_config_id: '17',
								user_id: this.userInfo.phoneNumber,
								session_id: this.session_id || "",
							}
						});

						if (response.statusCode === 200 && response.data) {
							// 如果需要获取 MinioUrls，先获取
							if (this.level === '0' && response.data.data?.milvus_ids) {
								await this.getMinioUrls({
									ids: response.data.data.milvus_ids
								});
							}
							// 然后处理完整响应
							await this.handleResponse(response.data, botMessage);
						}
					} catch (error) {
						console.error("Error sending message:", error);
						botMessage.message = "抱歉，发送消息失败，请重试。";
						botMessage.done = true;
						uni.showToast({
							title: '发送消息失败，请重试',
							icon: 'none'
						});
					}
				}
			}, */
			// 修改 renderMarkdown 方法
			/* renderMarkdown(rawMarkdown) {
			    if (typeof rawMarkdown !== 'string') {
			        console.warn('Invalid input for renderMarkdown:', rawMarkdown);
			        return '';
			    }
			    
			    try {
			        const md = new MarkdownIt({
			            html: true,
			            breaks: true,
			            linkify: true
			        });
			    
			        // 自定义链接渲染
			        md.renderer.rules.link_open = (tokens, idx) => {
			            const token = tokens[idx];
			            const hrefIndex = token.attrIndex('href');
			            const href = token.attrs[hrefIndex][1];
			            return `<text class="link" data-href="${href}">`;
			        };
			        md.renderer.rules.link_close = () => '</text>';
			    
			        return md.render(rawMarkdown);
			    } catch (error) {
			        console.error('Markdown rendering error:', error);
			        return rawMarkdown;
			    }
			}, */

			// 添加链接点击处理方法
			// 修改 handleLinkClick 方法
			// 修改 renderMarkdown 方法
			renderMarkdown(rawMarkdown) {
				if (typeof rawMarkdown !== 'string') {
					console.warn('Invalid input for renderMarkdown:', rawMarkdown);
					return '';
				}

				try {
					const md = new MarkdownIt({
						html: true,
						breaks: true,
						linkify: true
					});

					// 自定义链接渲染
					md.renderer.rules.link_open = (tokens, idx) => {
						const token = tokens[idx];
						const hrefIndex = token.attrIndex('href');
						const href = token.attrs[hrefIndex][1];
						// 使用自定义的类名和数据属性
						return `<view class="custom-link" data-url="${href}">`;
					};
					md.renderer.rules.link_close = () => '</view>';

					const html = md.render(rawMarkdown);
					return html;
				} catch (error) {
					console.error('Markdown rendering error:', error);
					return rawMarkdown;
				}
			},

			// 修改 handleLinkClick 方法
			handleLinkClick(e) {
				// 查找最近的带有 custom-link 类的父元素
				let target = e.target;
				while (target && !target.classList?.contains('custom-link')) {
					target = target.parentElement;
				}

				if (target && target.dataset.url) {
					const url = target.dataset.url;
					console.log('Clicked URL:', url);

					// 复制链接到剪贴板
					uni.setClipboardData({
						data: url,
						success: () => {
							uni.showToast({
								title: '链接已复制',
								icon: 'none'
							});
						}
					});
				}
			},
			/* renderMarkdown(rawMarkdown) {
				if (typeof rawMarkdown !== 'string') {
					console.warn('Invalid input for renderMarkdown:', rawMarkdown);
					return '';
				}
				return md.render(rawMarkdown);
			}, */
			handleKeydown(event) {
				// Check if 'Enter' is pressed without the 'Alt' key
				if (event.key === "Enter" && !(event.shiftKey || event.altKey)) {
					event.preventDefault(); // Prevent the default action to avoid line break in textarea
					this.sendMessage();
				} else if (event.key === "Enter" && event.altKey) {
					// Allow 'Alt + Enter' to insert a newline
					const cursorPosition = event.target.selectionStart;
					const textBeforeCursor = this.userInput.slice(0, cursorPosition);
					const textAfterCursor = this.userInput.slice(cursorPosition);

					// Insert the newline character at the cursor position
					this.userInput = textBeforeCursor + "\n" + textAfterCursor;

					// Move the cursor to the right after the inserted newline
					this.$nextTick(() => {
						event.target.selectionStart = cursorPosition + 1;
						event.target.selectionEnd = cursorPosition + 1;
					});
				}
			},
			beforeDestroy() {
				if (this.websocket) {
					this.websocket.close();
				}
			},
			// 选择图片
			chooseImage() {
				const remainingSlots = this.maxImages - this.selectedImages.length;
				if (remainingSlots <= 0) {
					uni.showToast({
						title: `最多只能上传${this.maxImages}张图片`,
						icon: 'none'
					});
					return;
				}

				uni.chooseImage({
					count: remainingSlots,
					success: async (res) => {
						// 即处理每个选择的图片
						for (const tempFilePath of res.tempFilePaths) {
							await this.uploadSingleImage(tempFilePath);
						}
					},
					fail: (err) => {
						console.error('选择图片失败:', err);
						uni.showToast({
							title: '选择图片失败',
							icon: 'none'
						});
					}
				});
			},

			// 新增单个图片上传方法
			async uploadSingleImage(tempFilePath) {
				try {
					// 显示上传进度提示
					uni.showLoading({
						title: '正在上传...',
						mask: true
					});

					const uploadResult = await uni.uploadFile({
						url: `${this.apiUrl}/upload/file`, // 修改为你的上传接口
						filePath: tempFilePath,
						name: 'file',
						header: {
							'Content-Type': 'multipart/form-data'
						}
					});

					if (uploadResult.statusCode === 200) {
						const response = JSON.parse(uploadResult.data);
						const fileUrl = response.data.fileUrl; // 根据实际返回结构调整

						// 添加已上传文件组
						this.uploadedFiles.push({
							url: fileUrl
						});

						// 更新预览图片数组
						this.selectedImages.push(tempFilePath);

						uni.hideLoading();
						uni.showToast({
							title: '上传成功',
							icon: 'success'
						});
					} else {
						throw new Error('Upload failed');
					}
				} catch (error) {
					console.error('图片上传失败:', error);
					uni.hideLoading();
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					});
				}
			},

			// 修改移除图片方法
			removeImage(index) {
				// 同时移除预览图和已上传的文件信息
				this.selectedImages.splice(index, 1);
				this.uploadedFiles.splice(index, 1);
			},

			// 添加选择视频方法
			chooseVideo() {
				if (this.selectedVideos.length >= this.maxVideos) {
					uni.showToast({
						title: `最多只能上传${this.maxVideos}个视频`,
						icon: 'none'
					});
					return;
				}

				uni.chooseVideo({
					count: 1,
					sourceType: ['album', 'camera'],
					success: async (res) => {
						await this.uploadSingleVideo(res.tempFilePath);
					},
					fail: (err) => {
						console.error('选择视频失败:', err);
						uni.showToast({
							title: '选择视频失败',
							icon: 'none'
						});
					}
				});
			},

			// 添加上传单个视频方法
			async uploadSingleVideo(tempFilePath) {
				try {
					uni.showLoading({
						title: '正在上传视频...',
						mask: true
					});

					const uploadResult = await uni.uploadFile({
						url: `${this.apiUrl}/upload/file`,
						filePath: tempFilePath,
						name: 'file',
						header: {
							'Content-Type': 'multipart/form-data'
						}
					});

					if (uploadResult.statusCode === 200) {
						const response = JSON.parse(uploadResult.data);
						const fileUrl = response.data.fileUrl;

						// 添加到已上传视频数组
						this.uploadedVideos.push({
							url: fileUrl
						});

						// 更新预览视频数组
						this.selectedVideos.push(tempFilePath);

						uni.hideLoading();
						uni.showToast({
							title: '上传成功',
							icon: 'success'
						});
					} else {
						throw new Error('Upload failed');
					}
				} catch (error) {
					console.error('视频上传失败:', error);
					uni.hideLoading();
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					});
				}
			},

			// 修改移除视频方法
			removeVideo(index) {
				this.selectedVideos.splice(index, 1);
				this.uploadedVideos.splice(index, 1);
			},

			// 新增统一的媒体选择方法
			chooseMedia() {
				const options = [];
				if (this.selectedImages.length < this.maxImages) {
					options.push('选择图片');
				}
				if (this.selectedVideos.length < this.maxVideos) {
					options.push('选择视频');
				}
				if (this.selectedDocs.length < this.maxDocs) {
					options.push('选择文档');
				}

				if (options.length === 0) {
					uni.showToast({
						title: '已达上传上限',
						icon: 'none'
					});
					return;
				}

				uni.showActionSheet({
					itemList: options,
					success: (res) => {
						const selected = options[res.tapIndex];
						if (selected === '选择图片') {
							this.chooseImage();
						} else if (selected === '选择视频') {
							this.chooseVideo();
						} else if (selected === '选择文档') {
							this.chooseDoc();
						}
					}
				});
			},

			// 切换音频播放状态
			toggleAudio(message) {
				if (!message.audioData) {
					uni.showToast({
						title: '没有可用的音频',
						icon: 'none'
					});
					return;
				}

				if (message.audioData.isPlaying) {
					this.stopAudio(message);
				} else {
					this.playAudio(message.audioData.base64);
				}
			},

			// 播放音频
			playAudio(audioBase64) {
				try {
					// 先停止当前正在播放的音频
					this.stopCurrentAudio();

					// 创建新的音频上下文
					const innerAudioContext = uni.createInnerAudioContext();
					this.currentAudioContext = innerAudioContext;

					// 设置音频源
					innerAudioContext.src = audioBase64;

					// 监听播放错误
					innerAudioContext.onError((res) => {
						console.error('音频播放错误:', res.errMsg);
						uni.showToast({
							title: '音频播放失败',
							icon: 'none'
						});
						this.stopCurrentAudio();
					});

					// 播放结束后的处理
					innerAudioContext.onEnded(() => {
						// 只调用 stop，不销毁实例
						if (this.currentAudioContext) {
							this.currentAudioContext.stop();
						}
					});

					// 开始播放
					innerAudioContext.play();
				} catch (error) {
					console.error('播放音频失败:', error);
					this.stopCurrentAudio();
				}
			},

			// 停止音频
			stopAudio(message) {
				if (this.currentAudioContext) {
					this.currentAudioContext.stop();
					this.currentAudioContext.destroy();
					this.currentAudioContext = null;
				}
				message.audioData.isPlaying = false;
				message.audioData.progress = 0;
			},

			// 组件销毁时清理音频
			beforeDestroy() {
				this.stopCurrentAudio();
			},

			// 添加选择文档方法
			chooseDoc() {
				if (this.selectedDocs.length >= this.maxDocs) {
					uni.showToast({
						title: `最多只能上传${this.max +'Docs'}个文档`,
						icon: 'none'
					});
					return;
				}

				// #ifdef H5
				// H5环境下使用input标签选择文件
				const input = document.createElement('input');
				input.type = 'file';
				input.accept = '.doc,.docx,.pdf,.txt';
				input.onchange = (event) => {
					const file = event.target.files[0];
					if (file) {
						this.uploadSingleDoc(file);
					}
				};
				input.click();
				// #endif

				// #ifdef APP-PLUS || MP-WEIXIN
				// 小程序和APP环境下使用选择文件API
				uni.chooseMessageFile({
					count: 1,
					type: 'file',
					extension: ['doc', 'docx', 'pdf', 'txt'],
					success: (res) => {
						const tempFile = res.tempFiles[0];
						this.uploadSingleDoc(tempFile);
					}
				});
				// #endif
			},

			// 添加上传单个文档方法
			async uploadSingleDoc(file) {
				try {
					uni.showLoading({
						title: '正在上传文档...',
						mask: true
					});

					const uploadResult = await uni.uploadFile({
						url: `${this.apiUrl}/upload/file`,
						filePath: file.path || file,
						name: 'file',
						header: {
							'Content-Type': 'multipart/form-data'
						}
					});

					if (uploadResult.statusCode === 200) {
						const response = JSON.parse(uploadResult.data);
						const fileUrl = response.data.fileUrl;
						// 添加到已上传文档数组
						this.uploadedDocs.push({
							url: fileUrl,
							name: file.name || '文档'
						});

						// 更新预览文档数组
						this.selectedDocs.push({
							name: file.name || '文档',
							path: file.path || file
						});

						uni.hideLoading();
						uni.showToast({
							title: '上传成功',
							icon: 'success'
						});
					} else {
						throw new Error('Upload failed');
					}
				} catch (error) {
					console.error('文档上传失败:', error);
					uni.hideLoading();
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					});
				}
			},

			// 添加移除文档方法
			removeDoc(index) {
				this.selectedDocs.splice(index, 1);
				this.uploadedDocs.splice(index, 1);
			},
			/* 打开弹窗 */
			async showVoiceSettings() {
				try {
					const response = await uni.request({
						url: `${this.apiUrl}/chatbot/list_voices`,
						method: 'GET'
					});

					if (response.statusCode === 200 && response.data.code === 200) {
						this.voicesData = response.data.data.voices;
						this.languageOptions = Object.keys(this.voicesData);

						// 设置默认值
						if (!this.voiceSettings.language || !this.voicesData[this.voiceSettings.language]) {
							this.voiceSettings.language = this.languageOptions[0];
						}

						// 初始化 rate 和 volume 的值
						if (!this.voiceSettings.rate) {
							this.voiceSettings.rate = '+10%';
						}
						if (!this.voiceSettings.volume) {
							this.voiceSettings.volume = '+20%';
						}

						this.updateVoiceOptions();

						// 打开弹窗
						this.$refs.voiceSettingsPopup.open();
					}
				} catch (error) {
					uni.showToast({
						title: '获取语音配置失败',
						icon: 'none'
					});
				}
			},

			// 更新声音选项
			updateVoiceOptions() {
				this.currentVoices = this.voicesData[this.voiceSettings.language] || [];

				// 如果当前选择的声音不在新的选项中，重置选择
				if (!this.currentVoices.find(v => v.name === this.voiceSettings.voice_name)) {
					if (this.currentVoices.length > 0) {
						this.voiceSettings.voice_name = this.currentVoices[0].name;
						this.voiceSettings.gender = this.currentVoices[0].gender;
						this.updateStyleOptions(this.currentVoices[0]);
					}
				}
			},

			// 更新风格选项
			updateStyleOptions(voice) {
				this.styleOptions = voice.style || [];
				if (!this.styleOptions.includes(this.voiceSettings.style)) {
					this.voiceSettings.style = this.styleOptions[0] || '';
				}
			},

			// 处理语言变化
			handleLanguageChange(e) {
				const newLanguage = this.languageOptions[e.detail.value];
				this.voiceSettings.language = newLanguage;
				this.updateVoiceOptions();
			},

			// 处理声音名称变化
			handleVoiceNameChange(e) {
				const selectedVoice = this.currentVoices[e.detail.value];
				this.voiceSettings.voice_name = selectedVoice.name;
				this.voiceSettings.gender = selectedVoice.gender;
				this.updateStyleOptions(selectedVoice);
			},

			// 处理风格变化
			handleStyleChange(e) {
				this.voiceSettings.style = this.styleOptions[e.detail.value];
			},

			// 保存配置
			async saveVoiceSettings() {
				try {
					const response = await uni.request({
						url: this.apiUrl + '/switch_voice_config', // 确保使用正确的接口地址
						method: 'POST',
						data: {
							language: this.voiceSettings.language,
							voice_name: this.voiceSettings.voice_name,
							gender: this.voiceSettings.gender,
							style: this.voiceSettings.style,
							rate: this.voiceSettings.rate,
							volume: this.voiceSettings.volume
						},
						header: {
							'content-type': 'application/x-www-form-urlencoded'
						}
					});

					if (response.statusCode === 200 && response.data.code === 200) {
						uni.showToast({
							title: '设置保存成功',
							icon: 'success'
						});
						this.closeVoiceSettings();
					} else {
						throw new Error(response.data.msg || '保存失败');
					}
				} catch (error) {
					console.error('保存设置失败:', error); // 添加错误日志
					uni.showToast({
						title: error.message || '保存失败，请重试',
						icon: 'none'
					});
				}
			},
			// 添加关闭弹窗方法
			closeVoiceSettings() {
				this.$refs.voiceSettingsPopup.close();
			},

			// 添加弹窗状态改变处理方法
			handlePopupChange(e) {
				if (e.show) {
					// 弹窗打开时
					uni.hideTabBar(); // 隐藏底部导航栏
					// #ifdef H5
					// 禁止页面滚动
					document.body.style.overflow = 'hidden';
					// #endif
				} else {
					// 弹窗关闭时
					uni.showTabBar(); // 显示底部导航栏
					// #ifdef H5
					// 恢复页面滚动
					document.body.style.overflow = 'auto';
					// #endif
				}
			}
		},
		// updated() {
		//   const messagesContainer = this.$el.querySelector(".messages");
		//   messagesContainer.scrollTop = messagesContainer.scrollHeight;
		// },
	};
</script>

<style scoped>
	/* 这里引入 ChatBox.css 的内容 */
	/* @import '/static/css/ChatBox.css'; */

	.chat-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		/* 或者按照实际需要调整高度 */
	}

	.messages {
		width: 90%;
		/* 设置消息列表宽度为屏幕宽度的 80% */
		max-width: 90%;
		/* 限制最大宽度，避免超出视口 */
		margin: 0 auto;
		/* 上下保持原有的 margin，左右自动调整以居中 */
		overflow-y: auto;
		/* 如果消息太多，允许滚动 */
		height: calc(100vh - 120px);
		/* 高度需要根据输入框和其元素的高度调整 */
		padding: 10px 10px 0;
		/* 或你希望的内边距大小 */
	}

	.message {
		display: flex;
		padding: 10px;
		align-items: flex-start;
	}

	.avatar-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		min-width: 50px;
		/* 确保头像容器有固定宽度 */
	}

	.messages li {
		display: flex;
		align-items: flex-start;
		/* 这将确保所有子素对到容器的顶部 */
		margin-bottom: 10px;
	}

	.avatar-container {
		display: flex;
		/* flex-direction: column; */
		flex-direction: row;
		margin-right: 10px;
	}

	.avatar {
		width: 30px;
		height: 30px;
		border-radius: 50%;
		margin-bottom: 5px;
	}

	.sender-name {
		margin-left: 15px;
		font-size: 12px;
		color: #666;
		margin-top: 2px;
	}

	.message {
		display: flex;
		align-items: flex-start;
		flex-direction: column;
		/* 增加消息间距 */
	}


	.user-avatar {
		/* background-image: url('/static/用户.png'); */
		/* 替换为您的 GIF 文件路径 */
		background-size: cover;
		/* 确保 GIF 覆盖整个头像区域 */
		background-repeat: no-repeat;
		/* 防止 GIF 重复 */
		background-position: center;
		/* 将 GIF 居中 */
		border-radius: 50%;
	}

	.bot-avatar {
		background-image: url('/static/机器人.png');
		/* 替换为您的 GIF 文件路径 */
		background-size: cover;
		/* 确保 GIF 覆盖整个头像区域 */
		background-repeat: no-repeat;
		/* 防止 GIF 重复 */
		background-position: center;
		/* 将 GIF 居中 */

	}

	.message-content {
		background-color: #f0f0f0;
		/* 消息背景 */
		padding-left: 20px;
		/* 上下右内边距 */
		padding-right: 10px;
		/* 上下左右的内边距 */
		padding-top: 10px;
		/* 上下左右的内边距 */
		padding-bottom: 10px;
		/* 上下左右的内边距 */
		max-width: calc(90% - 15px);
		/* 计算头像和间距 */
		border-radius: 10px 10px 10px 10px;
		/* 边框圆角 */
		margin-bottom: 10px;
		/* 和下一条消息之���的间距 */
		/* 消息内容样式 */
		display: flex;
		flex-direction: column;
		/* 排列文本 */
		margin-left: 30px;
		margin-top: 0;
		font-size: 12px;
	}


	.message-text {
		margin: 0;
		white-space: normal;
		/* 确保文本会换行 */
		word-wrap: break-word;
		/* 长单词或 URL 会被断开以适应容器宽度 */
	}

	.input-container {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 96%;
		background: white;
		padding: 5px 10px;
		box-shadow: 0px -2px 5px rgba(0, 0, 0, 0.1);
	}

	.input-wrapper {
		display: flex;
		align-items: center;
		gap: 10px;
	}

	.input-textarea {
		flex: 1;
		background: #f5f5f5;
		border-radius: 20px;
		padding: 8px 15px;
		min-height: 20px;
		max-height: 80px;
		font-size: 14px;
	}

	.send-btn {
		min-width: 60px;
		height: 36px;
		line-height: 36px;
		font-size: 14px;
		background: #1296db;
		color: white;
		border-radius: 18px;
		padding: 0 15px;
		margin: 0;
	}

	.sender-name {
		font-weight: bold;
		color: #333;
		font-size: 12px;
		margin-bottom: 5px;
	}

	.btn {
		border: none;
		background-color: #1296db;
		color: #fff;
	}

	.message-content :deep(p) {
		font-size: 12px !important;
		margin: 5px 0 10px;
		padding: 0;
		line-height: 22px;
		font-weight: inherit;
	}

	.message-content :deep(ol) {
		padding-bottom: 10px;
	}

	.message-content :deep(.source-section) {
		margin: 20px 0 3px;
		color: #333;
		font-size: 16px;
	}

	.message-content :deep(ol li) {
		padding-top: 3px;
	}

	.message-content :deep(ol li a) {
		font-size: 14px;
		color: #1296db;
	}

	/* 添加资料来源相关的新样式 */
	.source-section {
		border-top: 1px solid #e5e5e5;
		padding-top: 10px;
		margin-top: 10px;
	}

	.source-title {
		font-size: 14px;
		color: #666;
		margin-bottom: 8px;
	}

	.source-links {
		display: flex;
		flex-direction: column;
		gap: 5px;
	}

	.source-link {
		color: #1296db;
		font-size: 12px;
		cursor: pointer;
		/* text-decoration: underline; */
	}

	.source-link:hover {
		opacity: 0.8;
	}

	/* 添加新建对话按钮样式 */
	.new-chat-btn {
		padding: 0px 20px;
		display: flex;
		justify-content: flex-start;
		background-color: #fff;
	}

	.btn-new {
		background-color: #1296db;
		color: #fff;
		font-size: 14px;
		border-radius: 5px;
		border: none;
		height: 35px;
		margin: 0;
	}

	/* 上传图标 */
	.upload-img {
		width: 30px;
		height: 30px;
	}

	.image-upload-area {
		width: 100%;
		white-space: nowrap;
		margin-bottom: 10px;
		padding: 5px;
	}

	.image-list {
		display: inline-flex;
		gap: 10px;
	}

	.image-preview {
		width: 75px;
		height: 75px;
		position: relative;
		flex-shrink: 0;
		border-radius: 8px;
		/* overflow: hidden; */
	}

	.preview-img {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.delete-btn {
		position: absolute;
		top: 0px;
		right: 0px;
		width: 20px;
		height: 20px;
		background: rgba(0, 0, 0, 0.5);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 5;
	}

	.delete-icon {
		color: white;
		font-size: 18px;
	}

	.upload-btn {
		width: 75px;
		height: 75px;
		border: 2px dashed #ddd;
		border-radius: 8px;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
	}

	.upload-icon {
		width: 30px;
		height: 30px;
		opacity: 0.5;
	}

	/* 添加消息中图片的样式 */
	.message-images {
		display: flex;
		flex-wrap: wrap;
		gap: 5px;
		margin-top: 5px;
	}

	.message-image {
		width: 120px;
		height: 120px;
		border-radius: 8px;
		object-fit: cover;
	}

	/* 添加视频相关样式 */
	.upload-options {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.upload-icon {
		width: 24px;
		height: 24px;
		opacity: 0.7;
	}

	.video-preview {
		width: 120px;
		height: 120px;
		position: relative;
		flex-shrink: 0;
	}

	.video-thumbnail {
		width: 100%;
		height: 100%;
		border-radius: 8px;
		object-fit: cover;
	}

	.play-icon {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 30px;
		height: 30px;
		opacity: 0.8;
	}

	/* 添加视频预览相关样式 */
	.video-preview-container {
		width: 100%;
		height: 100%;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f5f5f5;
		border-radius: 8px;
	}

	.play-icon {
		position: absolute;
		width: 24px;
		height: 24px;
		opacity: 0.8;
	}

	/* 添加音频控件样式 */
	.audio-controls {
		display: flex;
		align-items: center;
		margin-top: 8px;
		gap: 10px;
	}

	.audio-btn {
		width: 30px;
		height: 30px;
		border-radius: 50%;
		/* background: #1296db; */
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
	}

	.audio-icon {
		width: 16px;
		height: 16px;
	}

	.audio-progress {
		font-size: 12px;
		color: #666;
	}

	/* 更新消息内容样式 */
	.message-content {
		display: flex;
		flex-direction: column;
		background-color: #f0f0f0;
		padding: 10px 15px;
		border-radius: 10px;
		margin-left: 30px;
		max-width: calc(90% - 15px);
		font-size: 12px;
	}

	/* 添加文档预览相关样式 */
	.doc-preview {
		width: 75px;
		height: 75px;
		position: relative;
		flex-shrink: 0;
		border-radius: 8px;
		overflow: hidden;
		background-color: #f5f5f5;
	}

	.doc-preview-container {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 5px;
	}

	.doc-icon {
		width: 30px;
		height: 30px;
		margin-bottom: 5px;
	}

	.doc-name {
		font-size: 10px;
		color: #666;
		text-align: center;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		width: 100%;
		padding: 0 5px;
	}

	/* 设置图标样式 */
	.settings-icon {
		width: 24px;
		height: 24px;
		margin-bottom: 10px;
		opacity: 0.7;
	}

	/* 设置弹窗样式 */
	.settings-popup {
		background: #fff;
		border-radius: 12px;
		width: 80vw;
		padding: 20px;
		position: relative;
		z-index: 999;
		/* 确保弹窗在最上层 */
	}

	.settings-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
	}

	.settings-title {
		font-size: 18px;
		font-weight: bold;
	}

	.close-btn {
		font-size: 24px;
		color: #999;
	}

	.settings-content {
		max-height: 60vh;
		overflow-y: auto;
	}

	.settings-item {
		margin-bottom: 15px;
	}

	.item-label {
		display: block;
		margin-bottom: 5px;
		color: #666;
		font-size: 14px;
	}

	.picker-value {
		height: 35px;
		line-height: 35px;
		padding: 0 10px;
		background: #f5f5f5;
		border-radius: 5px;
	}

	input {
		height: 35px;
		padding: 0 10px;
		background: #f5f5f5;
		border-radius: 5px;
	}

	.save-btn {
		margin-top: 20px;
		background: #1296db;
		color: #fff;
		border: none;
		border-radius: 5px;
		height: 40px;
		line-height: 40px;
	}

	/* 添加遮罩层样式 */
	:deep(.uni-popup__mask) {
		z-index: 998;
	}

	/* 更新弹窗样式以适应不同设备 */
	.settings-popup {
		background: #fff;
		border-radius: 12px;
		width: 80vw;
		padding: 20px;
		position: relative;
		z-index: 999;
		/* 确保弹窗在最上层 */
	}

	.settings-content {
		max-height: 60vh;
		/* 限制内容最大高度 */
		overflow-y: auto;
	}

	/* 确保遮罩层在正确的层级 */
	:deep(.uni-popup__mask) {
		z-index: 998;
	}

	/* 适配小屏幕设备 */
	@media screen and (max-width: 375px) {
		.settings-popup {
			width: 90vw;
			padding: 15px;
		}

		.settings-title {
			font-size: 16px;
		}

		.item-label {
			font-size: 13px;
		}
	}

	/* 适配大屏幕设备 */
	@media screen and (min-width: 768px) {
		.settings-popup {
			width: 60vw;
			max-width: 500px;
		}
	}

	.set_btn {
		display: flex;
		flex-direction: column;
		/* 设置为竖向排列 */
		gap: 10px;
		/* 按钮之间的间距 */
		justify-content: center;
		align-items: center;
	}
</style>