<template>
	<div class="wrapper">
		<div class="main">
			<div class="left">
				<div class="left-header">
					<div class="icon">
						<img src="./assets/images/ai.png" alt="" />
					</div>
					<el-input placeholder="新对话" v-model="newChatTitle" style="width: 220px" />
				</div>
				<!-- <div class="left-main">
					<div class="left-main-title">{{ "历史对话" }}</div>
					<div class="left-list">
						<div class="left-list-item" :class="{ itemActive: currentChatId === item.id }"
							v-for="(item, index) in chatList" :key="index">
							{{ item.title }}
						</div>
					</div>
				</div> -->
			</div>
			<div class="right">
				<div class="right-header">{{ curChatTitle }}</div>
				<div class="right-main">
					<div class="right-main-content">
						<div class="chat-content" ref="contentContainer">
							<!-- 消息列表 -->
							<div class="message-list">
								<div v-for="(message, index) in messages" :key="index">
									<!-- AI 消息 -->
									<div v-if="message.type === 'ai'" class="ai-item">
										<div class="ai-header" v-if="!isLoading">
											<div class="icon">
												<img src="./assets/images/ai-avator.png" alt="" />
											</div>
											<div class="text">{{ `已深度思考` }}</div>
										</div>
										<!-- <div v-if="message.think" class="think-title">思考内容</div>
										<div
											v-if="message.think"
											class="content think-content"
											v-html="renderMarkdown(message.think)"
										></div> -->
										<div v-if="message.source" class="source-title">
											<div class="text">知识库检索结果:</div>
											<div class="tool" @click="handleShowThinking">
												<div class="tool-item" v-if="!isShowThinking">
													<div class="text">展开</div>
													<div class="img">
														<img src="@/assets/icons/chat/down.png" alt="">
													</div>
												</div>
												<div class="tool-item" v-else>
													<div class="text">折叠</div>
													<div class="img">
														<img src="@/assets/icons/chat/up.png" alt="">
													</div>
												</div>
											</div>
										</div>
										<div v-if="message.source" class="content source-content" :class="{hiddenThinkContent: !isShowThinking}">
											<div class="source-item" v-for="(item, index) in message.source" :key="index"
												v-html="renderMarkdown(item)"></div>
										</div>
										<div v-if="message.content" class="answer-title">正文内容</div>
										<div v-if="message.content" class="content ai-content" v-html="renderMarkdown(message.content)">
										</div>
										<div v-if="message.raw_data?.length || message.raw_data?.rows?.length" class="answer-title">
											完整实体列表
										</div>
										<div v-if="message.raw_data?.length || message.raw_data?.rows?.length" class="content row-content">
											<div class="row-header">
												<div class="row-header-item1">{{ message.raw_data.columns?.name_zhs }}</div>
												<div class="row-header-item">{{ message.raw_data.columns?.date }}</div>
												<div class="row-header-item">{{ message.raw_data.columns?.industry }}</div>
												<div class="row-header-item">{{ message.raw_data.columns?.category }}</div>
												<div class="row-header-item2">
													{{ message.raw_data.columns?.sanction_reason }}
												</div>
											</div>
											<div class="row-main">
												<div class="row-main-item" v-for="(item, index) in message.raw_data.rows" :key="index">
													<el-popover effect="dark" :width="500" :content="item.name_zhs" placement="top-start">
														<template #reference>
															<div class="item-item1">{{ item.name_zhs }}</div>
														</template>
													</el-popover>

													<div class="item-item">{{ item.date }}</div>
													<div class="item-item">{{ item.industry }}</div>
													<div class="item-item">{{ item.category }}</div>
													<el-popover effect="dark" :width="400" :content="item.sanction_reason" placement="top-start">
														<template #reference>
															<div class="item-item2">{{ item.sanction_reason }}</div>
														</template>
													</el-popover>
												</div>
											</div>
										</div>
									</div>
									<!-- 用户消息 -->
									<div v-else class="user-item">
										<div class="user-bubble">
											<!-- <div class="user-content">{{ message.content }}</div> -->
											<div class="user-content">{{ message.content }}</div>
										</div>
									</div>
								</div>

								<!-- 加载状态 -->
								<div v-if="isLoading" class="ai-item">
									<div class="ai-header">
										<div class="icon">
											<img src="./assets/images/ai-avator.png" alt="" />
										</div>
										<div class="text">{{ `正在思考中，请稍候` }}</div>
									</div>
									<div class="loading-indicator">
										<span v-show="loadingDotIndex < 3" class="dot"></span>
										<span v-show="loadingDotIndex > 0" class="dot"></span>
										<span v-show="loadingDotIndex === 2" class="dot"></span>
									</div>
								</div>
							</div>
						</div>
					</div>
					<div class="right-main-footer">
						<el-input @keyup.enter="sendMessage" type="textarea" placeholder="发送消息" :rows="4" v-model="userInput" />
						<div class="input-footer">
							<div class="icon1">
								<el-tooltip effect="dark" content="录音" placement="top">
									<img src="./assets/images/microphone.png" alt="" />
								</el-tooltip>
							</div>
							<div class="icon2">
								<el-tooltip effect="dark" content="收藏" placement="top">
									<img src="./assets/images/attach.png" alt="" />
								</el-tooltip>
							</div>
							<!-- <div class="select-box">
								<el-select v-model="curArea" placeholder="选择领域方向" style="width: 160px">
									<el-option
										v-for="item in areaList"
										:key="item.value"
										:label="item.label"
										:value="item.value"
									/>
								</el-select>
							</div> -->
							<div class="submit" @click="sendMessage">
								<el-tooltip effect="dark" content="发送" placement="top">
									<img src="./assets/images/submit.png" alt="" />
								</el-tooltip>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from "vue";
import { fetchEventSource } from "@microsoft/fetch-event-source";
import MarkdownIt from "markdown-it";
import { ElMessage } from "element-plus";
import { getChat, getChecklistChat } from "@/api/chat";
import router from "@/router/index";
import json5 from "json5";

const isShowThinking = ref(false)

const handleShowThinking = () => {
	isShowThinking.value = !isShowThinking.value
}
const curArea = ref("法案");

const areaList = ref([
	{
		label: "法案",
		value: "法案"
	},
	{
		label: "法案RAG",
		value: "法案RAG"
	},
	{
		label: "清单",
		value: "清单"
	}
]);


const contentContainer = ref(null);

const userInput = ref("");
const isLoading = ref(false);
const abortController = ref(null);

const loadingDotIndex = ref(0);

// 消息数据
const messages = ref([
	// {
	// 	type: "user",
	// 	content: "你好"
	// },
	// {
	// 	type: "ai",
	// 	source: [
	// 		`完整检索实体名单: \n\n 中国科学院空天信息创新研究院\n\n北京复旦微电子技术有限公司\n\n北京天宜源生物科技有限公司\n\n北京擎科生物科技有限公司\n长沙南飞电子技术有限公司\n常州南飞微电子有限公司\n成都南飞微电子有限公司\n中国科学院国家授时中心\n吉姆西半导体科技（无锡）有限公司\n香港德铭电子有限公司\n华科物流（香港）有限公司\n华科供应链（香港）有限公司\n积村半导体科技（上海）有限公司\n生工生物工程（上海）股份有限公司\n上海复旦微电子集团股份有限公司\n上海复旦微电子（香港）有限公司\n上海富控华龙微电子系统技术有限公司\n上海富维迅捷数字科技有限公司\n上海索辰信息科技有限公司\n深圳复旦微电子有限公司\n深圳南飞微电子有限公司\n深圳新力康供应链管理有限公司\n盛美半导体设备（上海）股份有限公司\n总数量：23`
	// 	],
	// 	content: `2025年9月实体清单的主要制裁实体、制裁原因\n\n 时间范围\n-当前查询的时间范围为：2025年9月16日。`,
	// 	raw_data: {
	// 		columns: {
	// 			category: "实体类别",
	// 			date: "制裁日期",
	// 			industry: "所属行业",
	// 			name_zhs: "实体名称",
	// 			sanction_reason: "制裁理由"
	// 		},
	// 		rows: [
	// 			{
	// 				category: "科研机构",
	// 				date: "2025-09-16",
	// 				industry: "航空航天",
	// 				name_zhs: "中国科学院空天信息创新研究院",
	// 				sanction_reason: "与中国高空气球计划有关联"
	// 			},
	// 			{
	// 				category: "科研机构",
	// 				date: "2025-09-16",
	// 				industry: "航空航天",
	// 				name_zhs: "中国科学院空天信息创新研究院",
	// 				sanction_reason: "与中国高空气球计划有关联"
	// 			},
	// 			{
	// 				category: "科研机构",
	// 				date: "2025-09-16",
	// 				industry: "航空航天",
	// 				name_zhs: "中国科学院空天信息创新研究院",
	// 				sanction_reason: "与中国高空气球计划有关联"
	// 			}
	// 		]
	// 	}
	// }
]);

// Markdown 渲染器
const md = new MarkdownIt();

// 渲染 markdown
const renderMarkdown = content => {
	return md.render(content);
};

// 自动滚动到底部
const scrollToBottom = async () => {
	await nextTick();
	if (contentContainer.value) {
		const container = contentContainer.value;
		container.scrollTop = container.scrollHeight;
	}
};

// 添加消息
const addMessage = (type, content) => {
	messages.value.push({
		type,
		content,
		timestamp: new Date().getTime()
	});
	scrollToBottom();
};

// 更新最后一条 AI 消息（用于流式输出）
const updateLastAIMessage = content => {
	const lastMessage = messages.value[messages.value.length - 1];
	if (lastMessage && lastMessage.type === "ai") {
		if (isCurAnswerMessage.value) {
			lastMessage.content = content;
		} else {
			lastMessage.think = content;
		}

		scrollToBottom();
	}
};

let aiMessage = ref("");

const isCurAnswerMessage = ref(false);

function parseOuterOnly(json5String, maxDepth = 1) {
	let currentDepth = 0;

	return json5.parse(json5String, (key, value) => {
		// 检查当前深度
		if (currentDepth > maxDepth) {
			return value; // 超过最大深度，直接返回值
		}

		// 如果是对象或数组，增加深度计数
		if (typeof value === "object" && value !== null) {
			currentDepth++;
		}

		return value;
	});
}

// 使用 fetchEventSource 连接
// const connectSSE = async question => {
// 	// 添加用户消息
// 	addMessage("user", question);

// 	// 添加空的 AI 消息用于流式更新
// 	addMessage("ai", "");

// 	isLoading.value = true;

// 	// 创建 AbortController 用于取消请求
// 	abortController.value = new AbortController();

// 	const params = {
// 		// question: "川普1期对华制裁领域分布情况"
// 		question: question
// 		// knowledge_base_name: "kb_test251112",
// 		// top_k: 6,
// 		// score_threshold: 0.5,
// 		// metadata: { year: 2024 }
// 	};

// 	fetchEventSource("/sseChat/rag/chat/stream", {
// 		method: "POST",
// 		headers: {
// 			"Content-Type": "application/json"
// 		},
// 		body: JSON.stringify(params),
// 		signal: abortController.value.signal,
// 		openWhenHidden: true,
// 		async onopen(res) {
// 			isLoading.value = false;
// 			console.log("流式回答开始", res);
// 		},
// 		async onmessage(res) {
// 			console.log("res", res);
// 			let msgData = parseOuterOnly(res.data);
// 			if (res.event === "end_of_workflow") {
// 				ElMessage.success("问答完成！");
// 				abortController.value.abort();
// 				abortController.value = new AbortController();
// 				return;
// 			}
// 			if (res.event === "start_of_agent" && msgData.agent_name === "answer") {
// 				isCurAnswerMessage.value = true;
// 				aiMessage.value = "";
// 			}
// 			if (res.event === "message") {
// 				let content = msgData.delta.content;
// 				console.log("msgData", msgData);
// 				console.log("content", content);
// 				if (content !== "[DONE]") {
// 					aiMessage.value += content;
// 					updateLastAIMessage(aiMessage.value);
// 				} else {
// 					aiMessage.value = "";
// 					abortController.value.abort();
// 					abortController.value = new AbortController();
// 				}
// 			}
// 		},
// 		onerror(error) {
// 			ElMessage({
// 				message: "问答报错!",
// 				type: "warning"
// 			});
// 			abortController.value.abort();
// 			abortController.value = new AbortController();
// 			throw new Error(error);
// 		}
// 	}).catch(error => {
// 		ElMessage({
// 			message: "问答报错!",
// 			type: "warning"
// 		});
// 		abortController.value.abort();
// 		abortController.value = new AbortController();
// 		throw new Error(error);
// 	});
// };

// 定义正则替换
function removeHttpParentheses(str) {
	// 匹配 (http://... 开头，以 ) 结尾的内容
	return str.replace(/\(http:\/\/[^)]*\)/g, "");
}

// 将字符串中符合以'['开头以'.txt]'结尾的字符串中的'.txt'替换为空
function removeTxtInBrackets(str) {
	// 匹配 [开头，.txt]结尾的内容，并替换其中的.txt为空
	return str.replace(/\[([^[\]]*)\.txt\]/g, "[$1]");
}

const connectSSE = async question => {
	// 添加用户消息
	addMessage("user", question);

	let mesParam = messages.value.map(item => {
		return {
			role: item.type,
			content: item.content
		};
	});

	// 添加空的 AI 消息用于流式更新
	addMessage("ai", "");

	isLoading.value = true;
	const loadingInterval = setInterval(() => {
		if (loadingDotIndex.value < 2) {
			loadingDotIndex.value++;
		} else {
			loadingDotIndex.value = 0;
		}
	}, 500);

	// 创建 AbortController 用于取消请求
	abortController.value = new AbortController();

	const params = {
		model: "qwen-plus",
		messages: mesParam,
		stream: true,
		temperature: 0.3,
		top_k: 9,
		score_threshold: 0.1,
		prompt_name: "default",
		return_direct: false
	};

	fetchEventSource("/sseChat/knowledge_base/local_kb/bills-500/chat/completions", {
		method: "POST",
		headers: {
			"Content-Type": "application/json"
		},
		body: JSON.stringify(params),
		signal: abortController.value.signal,
		openWhenHidden: true,
		async onopen(res) {
			isLoading.value = false;
			clearInterval(loadingInterval);
			console.log("流式回答开始", res);
		},
		async onmessage(res) {
			console.log("res", res);
			let msgData = JSON.parse(res.data);
			if (msgData.docs) {
				console.log("docs", msgData.docs);
				const lastMessage = messages.value[messages.value.length - 1];
				if (lastMessage && lastMessage.type === "ai") {
					let newDocs = msgData.docs
						.map(item => {
							return removeHttpParentheses(item);
						})
						.map(val => {
							return removeTxtInBrackets(val);
						});
					lastMessage.source = newDocs;

					scrollToBottom();
				}
			}
			if (msgData.choices) {
				isCurAnswerMessage.value = true;
				let content = msgData.choices[0].delta.content;
				aiMessage.value += content;
				updateLastAIMessage(aiMessage.value);
			}
			if (msgData.raw_data) {
				const lastMessage = messages.value[messages.value.length - 1];
				if (lastMessage && lastMessage.type === "ai") {
					lastMessage.raw_data = msgData.raw_data;
					scrollToBottom();
				}
			}
			// if (res.event === "end_of_workflow") {
			// 	ElMessage.success("问答完成！");
			// 	abortController.value.abort();
			// 	abortController.value = new AbortController();
			// 	return;
			// }
			// if (res.event === "start_of_agent" && msgData.agent_name === "answer") {
			// 	isCurAnswerMessage.value = true;
			// 	aiMessage.value = "";
			// }
			// if (res.event === "message") {
			// 	let content = msgData.delta.content;
			// 	console.log("msgData", msgData);
			// 	console.log("content", content);
			// 	if (content !== "[DONE]") {
			// 		aiMessage.value += content;
			// 		updateLastAIMessage(aiMessage.value);
			// 	} else {
			// 		aiMessage.value = "";
			// 		abortController.value.abort();
			// 		abortController.value = new AbortController();
			// 	}
			// }
		},
		onerror(error) {
			ElMessage({
				message: "问答报错!",
				type: "warning"
			});
			abortController.value.abort();
			abortController.value = new AbortController();
			throw new Error(error);
		}
	}).catch(error => {
		ElMessage({
			message: "问答报错!",
			type: "warning"
		});
		abortController.value.abort();
		abortController.value = new AbortController();
		throw new Error(error);
	});
};

function formatDateTime(isoString) {
	const date = new Date(isoString);

	// 获取各个时间部分
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始
	const day = String(date.getDate()).padStart(2, "0");
	const hours = String(date.getHours()).padStart(2, "0");
	const minutes = String(date.getMinutes()).padStart(2, "0");
	const seconds = String(date.getSeconds()).padStart(2, "0");

	return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const handleBillChat = async question => {
	// 添加用户消息
	addMessage("user", question);

	const params = {
		model: "neko-checklist-agent",
		// messages: [
		// 	{
		// 		role: "user",
		// 		content: "2024年12月5日当期实体清单的主要制裁对象、制裁原因是？"
		// 	}
		// ]
		messages: messages.value.map(item => {
			return {
				role: item.type === "ai" ? "assistant" : "user",
				content: item.content
			};
		})
	};

	// 添加空的 AI 消息用于流式更新
	addMessage("ai", "");

	isLoading.value = true;

	const loadingInterval = setInterval(() => {
		if (loadingDotIndex.value < 2) {
			loadingDotIndex.value++;
		} else {
			loadingDotIndex.value = 0;
		}
	}, 500);

	try {
		const response = await fetch("/checklistChat/langgraph/union/chat", {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify(params)
		});

		// console.log("状态码:", response.status); // 200
		// console.log("ok:", response.ok); // true
		// console.log("headers:", [...response.headers.entries()]);

		// 先以文本形式读取，看看实际内容
		const rawText = await response.text();
		// console.log("原始响应文本:", rawText);

		// 尝试解析 JSON
		const data = JSON.parse(rawText); // 可能在这里抛出错误
		console.log("解析后的数据:", data);
		clearInterval(loadingInterval);
		isLoading.value = false;
		console.log("data.logs:", data.logs);
		console.log("data.choices:", data.choices);

		if (data.logs) {
			const lastMessage = messages.value[messages.value.length - 1];
			if (lastMessage && lastMessage.type === "ai") {
				let newDocs = data.logs.map(item => {
					return item.detail + " " + formatDateTime(item.ts);
				});
				lastMessage.source = newDocs;
				scrollToBottom();
			}
		}

		if (data.choices && data.choices[0].message.content) {
			isCurAnswerMessage.value = true;
			let content = data.choices[0].message.content;
			if (content === "[DONE]") {
				ElMessage.success("生成完成！");
			} else {
				aiMessage.value += content;
				updateLastAIMessage(aiMessage.value);
			}
		}

		if (data.raw_data) {
			const lastMessage = messages.value[messages.value.length - 1];
			if (lastMessage && lastMessage.type === "ai") {
				lastMessage.raw_data = data.raw_data;
				scrollToBottom();
			}
		}

		if (data.detail && data.detail.error) {
			console.log(data.detail.error.message);
			// ElMessage.error(data.detail.error.message);
			isCurAnswerMessage.value = true;
			let content = "我们换个新话题吧！";
			aiMessage.value += content;
			updateLastAIMessage(aiMessage.value);
		}
	} catch (error) {
		console.error("catch 中的错误:", error);
	}
};

const handleListChat = async question => {
	// 添加用户消息
	addMessage("user", question);

	const params = {
		model: "neko-checklist-agent",
		// messages: [
		// 	{
		// 		role: "user",
		// 		content: "2024年12月5日当期实体清单的主要制裁对象、制裁原因是？"
		// 	}
		// ]
		messages: messages.value.map(item => {
			return {
				role: item.type === "ai" ? "assistant" : "user",
				content: item.content
			};
		})
	};

	// 添加空的 AI 消息用于流式更新
	addMessage("ai", "");

	isLoading.value = true;

	const loadingInterval = setInterval(() => {
		if (loadingDotIndex.value < 2) {
			loadingDotIndex.value++;
		} else {
			loadingDotIndex.value = 0;
		}
	}, 500);

	// // 创建 AbortController 用于取消请求
	// abortController.value = new AbortController();

	// const TIMEOUT_MS = 180 * 1000;

	// fetchEventSource("/checklistChat/langgraph/checklist/chat-stream", {
	// 	method: "POST",
	// 	headers: {
	// 		"Content-Type": "application/json"
	// 	},
	// 	body: JSON.stringify(params),
	// 	signal: abortController.value.signal,
	// 	// 设置 3 分钟超时
	//   // fetch: async (input, init) => {
	//   //   const abortController = new AbortController();
	//   //   const timeoutId = setTimeout(() => {
	//   //     console.log('请求超时（3分钟）');
	//   //     abortController.value.abort();
	//   //   }, TIMEOUT_MS);

	//   //   try {
	//   //     const response = await fetch(input, {
	//   //       ...init,
	//   //       signal: abortController.value.signal,
	//   //     });
	//   //     return response;
	//   //   } finally {
	//   //     clearTimeout(timeoutId);
	//   //   }
	//   // },
	// 	openWhenHidden: true,
	// 	async onopen(res) {
	// 		isLoading.value = false;
	// 		clearInterval(loadingInterval);
	// 		if(res.detail.error) {
	// 			ElMessage.error(res.detail.error.message)
	// 		}
	// 		console.log("流式回答开始", res);
	// 	},
	// 	async onmessage(res) {
	// 		console.log("res", res);
	// 		if (res.data === "[DONE]") {
	// 			ElMessage.success("生成完成！");
	// 		}
	// 		let msgData = JSON.parse(res.data);
	// 		if (msgData.logs) {
	// 			console.log("docs", msgData.logs);
	// 			const lastMessage = messages.value[messages.value.length - 1];
	// 			if (lastMessage && lastMessage.type === "ai") {
	// 				let newDocs = msgData.logs.map(item => {
	// 					return item.detail + " " + formatDateTime(item.ts);
	// 				});
	// 				lastMessage.source = newDocs;
	// 				scrollToBottom();
	// 			}
	// 		}
	// 		if (msgData.choices && msgData.choices[0].delta.content) {
	// 			isCurAnswerMessage.value = true;
	// 			let content = msgData.choices[0].delta.content;
	// 			if (content === "[DONE]") {
	// 				ElMessage.success("生成完成！");
	// 			} else {
	// 				aiMessage.value += content;
	// 				updateLastAIMessage(aiMessage.value);
	// 			}
	// 		}
	// 		// if (res.event === "end_of_workflow") {
	// 		// 	ElMessage.success("问答完成！");
	// 		// 	abortController.value.abort();
	// 		// 	abortController.value = new AbortController();
	// 		// 	return;
	// 		// }
	// 		// if (res.event === "start_of_agent" && msgData.agent_name === "answer") {
	// 		// 	isCurAnswerMessage.value = true;
	// 		// 	aiMessage.value = "";
	// 		// }
	// 		// if (res.event === "message") {
	// 		// 	let content = msgData.delta.content;
	// 		// 	console.log("msgData", msgData);
	// 		// 	console.log("content", content);
	// 		// 	if (content !== "[DONE]") {
	// 		// 		aiMessage.value += content;
	// 		// 		updateLastAIMessage(aiMessage.value);
	// 		// 	} else {
	// 		// 		aiMessage.value = "";
	// 		// 		abortController.value.abort();
	// 		// 		abortController.value = new AbortController();
	// 		// 	}
	// 		// }
	// 	},
	// 	onerror(error) {
	// 		ElMessage({
	// 			message: "问答报错!",
	// 			type: "warning"
	// 		});
	// 		abortController.value.abort();
	// 		abortController.value = new AbortController();
	// 		throw new Error(error);
	// 	}
	// }).catch(error => {
	// 	ElMessage({
	// 		message: "问答报错!",
	// 		type: "warning"
	// 	});
	// 	abortController.value.abort();
	// 	abortController.value = new AbortController();
	// 	throw new Error(error);
	// });

	// try {
	// 	const res = await getChecklistChat(params);

	// 	if (res.detail.error) {
	// 		console.log(res.detail.error.message);
	// 		ElMessage.error(res.detail.error.message);
	// 	}

	// 	if (res.logs) {
	// 		isLoading.value = false;
	// 		const lastMessage = messages.value[messages.value.length - 1];
	// 		if (lastMessage && lastMessage.type === "ai") {
	// 			let newDocs = res.logs.map(item => {
	// 				return item.detail + " " + formatDateTime(item.ts);
	// 			});
	// 			lastMessage.source = newDocs;
	// 			scrollToBottom();
	// 		}
	// 	}

	// 	if (res.choices && res.choices[0].delta.content) {
	// 		isLoading.value = false;
	// 		isCurAnswerMessage.value = true;
	// 		let content = res.choices[0].delta.content;
	// 		if (content === "[DONE]") {
	// 			ElMessage.success("生成完成！");
	// 		} else {
	// 			aiMessage.value += content;
	// 			updateLastAIMessage(aiMessage.value);
	// 		}
	// 	}
	// } catch (error) {
	// 	console.log("error", error);
	// 	if (error.detail && error.detail.error) {
	// 		console.log(res.detail.error.message);
	// 		ElMessage.error(res.detail.error.message);
	// 	}
	// }

	try {
		const response = await fetch("/checklistChat/langgraph/checklist/chat", {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify(params)
		});

		// console.log("状态码:", response.status); // 200
		// console.log("ok:", response.ok); // true
		// console.log("headers:", [...response.headers.entries()]);

		// 先以文本形式读取，看看实际内容
		const rawText = await response.text();
		// console.log("原始响应文本:", rawText);

		// 尝试解析 JSON
		const data = JSON.parse(rawText); // 可能在这里抛出错误
		console.log("解析后的数据:", data);
		clearInterval(loadingInterval);
		isLoading.value = false;
		console.log("data.logs:", data.logs);
		console.log("data.choices:", data.choices);

		if (data.logs) {
			const lastMessage = messages.value[messages.value.length - 1];
			if (lastMessage && lastMessage.type === "ai") {
				let newDocs = data.logs.map(item => {
					return item.detail + " " + formatDateTime(item.ts);
				});
				lastMessage.source = newDocs;
				scrollToBottom();
			}
		}

		if (data.choices && data.choices[0].message.content) {
			isCurAnswerMessage.value = true;
			let content = data.choices[0].message.content;
			if (content === "[DONE]") {
				ElMessage.success("生成完成！");
			} else {
				aiMessage.value += content;
				updateLastAIMessage(aiMessage.value);
			}
		}

		if (data.raw_data) {
			const lastMessage = messages.value[messages.value.length - 1];
			if (lastMessage && lastMessage.type === "ai") {
				lastMessage.raw_data = data.raw_data;
				scrollToBottom();
			}
		}

		if (data.detail.error) {
			console.log(data.detail.error.message);
			// ElMessage.error(data.detail.error.message);
			isCurAnswerMessage.value = true;
			let content = "我们换个新话题吧！";
			aiMessage.value += content;
			updateLastAIMessage(aiMessage.value);
		}
	} catch (error) {
		console.error("catch 中的错误:", error);
	}
};

// 发送消息
const sendMessage = async () => {
	const question = userInput.value.trim();
	if (!question) {
		ElMessage.warning("请输入问题");
		return;
	}

	if (isLoading.value) {
		ElMessage.warning("请等待上一条消息回复完成");
		return;
	}

	userInput.value = "";
	aiMessage.value = "";
	// if (curArea.value === "法案") {
	// 	handleBillChat(question);
	// } else if (curArea.value === "法案RAG") {
	// 	await connectSSE(question);
	// } else {
	// 	handleListChat(question);
	// }
	handleBillChat(question);
};

const newChatTitle = ref(""); // 新对话
const curChatTitle = ref("新对话");
const currentChatId = ref(1);
const chatList = ref([
	{
		id: 1,
		title: "美国对中国制裁实体清单"
	},
	{
		id: 2,
		title: "制作中国进口依赖度柱状图"
	},
	{
		id: 3,
		title: "列举2025年科技产品"
	},
	{
		id: 4,
		title: "获取美国国会议员名单"
	},
	{
		id: 5,
		title: "2000年以后美国金融法案列举"
	},
	{
		id: 6,
		title: "科研机构及高校仪器进口排名"
	}
]);

onMounted(() => {
	scrollToBottom();
});

onUnmounted(() => {
	if (abortController.value) {
		abortController.value.abort();
	}
});
</script>

<style lang="scss" scoped>
:deep(.el-input__wrapper) {
	box-shadow: none;
	height: 44px;
}

:deep(.el-input__wrapper:hover) {
	box-shadow: none !important;
}

:deep(.el-input__wrapper.is-focus) {
	box-shadow: none !important;
}

:deep(.el-input ::placeholder) {
	color: var(--color-main-active);
	font-family: Microsoft YaHei;
	font-size: 16px;
	font-weight: 400;
}

:deep(.el-input__inner) {
	color: #333;
	font-family: Microsoft YaHei;
	font-size: 16px;
	font-weight: 400;
}

:deep(.el-textarea__inner) {
	box-shadow: none;
	border-radius: 20px;
	resize: none;
}

:deep(.el-textarea__inner:hover) {
	box-shadow: none !important;
}

:deep(.el-textarea__inner.is-focus) {
	box-shadow: none !important;
}

:deep(.el-textarea ::placeholder) {
	color: rgba(132, 136, 142, 1);
	font-family: Microsoft YaHei;
	font-size: 16px;
	font-weight: 400;
}

:deep(.el-textarea__inner) {
	color: #333;
	font-family: Microsoft YaHei;
	font-size: 16px;
	font-weight: 400;
}

.wrapper {
	width: 100%;
	height: 100%;
	overflow-y: auto;

	.header {
		position: sticky;
		top: 0;
		z-index: 9999;
		height: 64px;
		color: #fff;
		font-family: Microsoft YaHei;
		font-size: 20px;
		font-weight: 700;
		line-height: 26px;
		line-height: 64px;
		background: url("../assets/images/header-bg.png");
		box-sizing: border-box;

		.header-content {
			width: 1600px;
			margin: 0 auto;
			display: flex;

			.header-item {
				margin: 0 3px;
			}

			.back-item {
				cursor: pointer;

				&:hover {
					color: #ccc;
				}
			}
		}
	}

	.main {
		margin-top: 16px;
		display: flex;
		justify-content: center;
		gap: 16px;
		margin-bottom: 10px;

		.left {
			width: 300px;
			height: 880px;
			border-radius: 4px;
			box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
			background: rgba(255, 255, 255, 1);

			.left-header {
				width: 268px;
				height: 48px;
				margin: 16px auto;
				box-sizing: border-box;
				border: 1px solid rgba(5, 95, 194, 1);
				border-radius: 8px;
				box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
				background: rgba(255, 255, 255, 1);
				display: flex;

				.icon {
					width: 20px;
					height: 13px;
					margin-top: 13px;
					margin-left: 16px;

					img {
						width: 100%;
						height: 100%;
					}
				}
			}

			.left-main {
				margin-top: 24px;

				.left-main-title {
					margin-left: 29px;
					width: 64px;
					height: 24px;
					color: rgba(132, 136, 142, 1);
					font-family: Microsoft YaHei;
					font-size: 16px;
					font-weight: 400;
					line-height: 24px;
					letter-spacing: 0px;
					text-align: left;
				}

				.left-list {
					margin-top: 12px;
					margin-left: 16px;
					width: 268px;
					height: 720px;

					.left-list-item {
						width: 268px;
						height: 48px;
						border-radius: 8px;
						color: rgba(59, 65, 75, 1);
						font-family: Microsoft YaHei;
						font-size: 16px;
						font-weight: 400;
						line-height: 48px;
						box-sizing: border-box;
						padding: 0 12px;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
						cursor: pointer;

						&:hover {
							background: rgba(246, 250, 255, 1);
						}
					}

					.itemActive {
						background: rgba(246, 250, 255, 1);
						color: var(--color-main-active);
						font-weight: 700;
					}
				}
			}
		}

		.right {
			width: 1284px;
			height: 880px;
			border-radius: 4px;
			box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
			background: rgba(255, 255, 255, 1);

			.right-header {
				height: 64px;
				border-bottom: 1px solid rgba(234, 236, 238, 1);
				line-height: 64px;
				box-sizing: border-box;
				padding-left: 24px;
				color: rgba(59, 65, 75, 1);
				font-family: Microsoft YaHei;
				font-size: 18px;
				font-weight: 700;
			}

			.right-main {
				.right-main-content {
					width: 926px;
					margin-left: 166px;
					height: 630px;
				}

				.right-main-footer {
					margin: 10px auto;
					width: 900px;
					height: 160px;
					box-sizing: border-box;
					border: 1px solid rgba(230, 231, 232, 1);
					border-radius: 20px;
					background: rgba(255, 255, 255, 1);

					.input-footer {
						display: flex;
						justify-content: flex-end;

						.icon1 {
							margin-top: 15px;
							width: 24px;
							height: 24px;
							margin-right: 20px;
							cursor: pointer;

							img {
								width: 100%;
								height: 100%;
							}
						}

						.icon2 {
							margin-top: 15px;
							width: 24px;
							height: 24px;
							margin-right: 20px;
							cursor: pointer;

							img {
								width: 100%;
								height: 100%;
							}
						}

						.select-box {
							margin-top: 10px;
							margin-right: 14px;

							:deep(.el-select__wrapper) {
								height: 36px;
								border-radius: 18px;
								border: 1px solid var(--color-main-active);
								box-shadow: none;
							}

							:deep(.el-select__selected-item) {
								color: var(--color-main-active);
								font-family: Microsoft YaHei;
								font-size: 16px;
								text-align: center;
							}

							:deep(.el-select__caret) {
								color: var(--color-main-active);
							}
						}

						.submit {
							margin-top: 7px;
							margin-right: 12px;
							width: 40px;
							height: 40px;
							border-radius: 20px;
							background: #b4cfed;
							cursor: pointer;

							&:hover {
								background: rgba(5, 95, 194, 1);
							}

							img {
								width: 24px;
								height: 24px;
								margin: 8px;
							}
						}
					}
				}
			}
		}
	}
}

/* 对话内容区域 */
.chat-content {
	overflow-x: hidden;
	overflow-y: auto;
	// padding: 20px;
	background: #fff;
	width: 1118px;
	padding-right: 192px;
	box-sizing: border-box;
	height: 620px;

	.chat-content::-webkit-scrollbar {
		width: 30px;
	}

	.chat-content::-webkit-scrollbar-thumb {
		background: #000;
		border-radius: 3px;
	}

	.chat-content::-webkit-scrollbar-thumb:hover {
		background: #555;
	}

	.message-list {
		padding-bottom: 20px;
	}

	.ai-item {
		width: 926px;
		overflow: hidden;

		.ai-header {
			height: 22px;
			display: flex;

			.icon {
				width: 10px;
				height: 10px;

				img {
					width: 100%;
					height: 100%;
				}
			}

			.text {
				margin-left: 16px;
				height: 22px;
				color: rgba(132, 136, 142, 1);
				font-family: Microsoft YaHei;
				font-size: 14px;
				font-weight: 400;
				line-height: 22px;
				letter-spacing: 0px;
				text-align: left;
			}
		}

		.think-title {
			margin-left: 26px;
			height: 22px;
			color: rgba(132, 136, 142, 1);
			font-family: Microsoft YaHei;
			font-size: 14px;
			font-weight: 400;
			line-height: 22px;
			letter-spacing: 0px;
			text-align: left;
		}

		.answer-title {
			margin-top: 10px;
			margin-left: 26px;
			height: 22px;
			color: var(--color-main-active);
			font-family: Microsoft YaHei;
			font-size: 18px;
			font-weight: 700;
			line-height: 24px;
			letter-spacing: 0px;
			text-align: left;
		}

		.think-content {
			background: rgba(245, 245, 245, 0.5);
			width: 900px;
			margin-left: 26px;
			padding: 1px 10px;
			border-radius: 5px;
		}

		.source-title {
			margin-left: 26px;
			height: 30px;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.text {
				color: var(--color-main-active);
				font-family: Microsoft YaHei;
				font-size: 14px;
				font-weight: 400;
				line-height: 22px;
				letter-spacing: 0px;
				text-align: left;
			}


			.tool-item {
				display: flex;
				gap: 10px;
				cursor: pointer;

				.text {
					color: var(--color-main-active);
					font-family: Microsoft YaHei;
					font-size: 14px;
					font-weight: 400;
					line-height: 22px;
					letter-spacing: 0px;
					text-align: left;
				}

				.img {
					width: 17px;
					height: 10px;

					img {
						width: 100%;
						height: 100%;
					}
				}
			}

		}

		.hiddenThinkContent {
			height: 0px;
			overflow: hidden;
		}

		.source-content {
			background: rgba(245, 245, 245, 0.5);
			width: 900px;
			margin-left: 26px;
			padding: 1px 10px;
			border-radius: 5px;

			// max-height: 300px;
			// overflow-y: auto;
			.source-item {
				text-indent: 30px;
				// line-height: 30px;
				color: #333;
			}
		}

		.ai-content {
			margin-top: 10px;
			width: 900px;
			margin-left: 26px;
			background: rgba(246, 250, 255, 1);
			padding: 1px 10px;
			border-radius: 5px;
		}

		.row-content {
			margin-top: 10px;
			width: 900px;
			margin-left: 26px;
			background: rgba(246, 250, 255, 1);
			padding: 1px 10px;
			border-radius: 5px;

			.row-header {
				height: 40px;
				line-height: 40px;
				font-family: Microsoft-YaHei;
				font-size: 20px;
				color: #555;
				font-weight: bold;
				display: flex;
				border-bottom: 1px solid #999;

				.row-header-item {
					text-align: center;
					width: 150px;
					border-right: 1px solid #999;
				}

				.row-header-item1 {
					text-align: center;
					width: 250px;
					border-right: 1px solid #999;
				}

				.row-header-item2 {
					text-align: center;
					width: 200px;
				}
			}

			.row-main {
				padding-bottom: 10px;

				.row-main-item {
					height: 35px;
					line-height: 35px;
					font-family: Microsoft-YaHei;
					font-size: 14px;
					color: #555;
					display: flex;
					border-bottom: 1px solid #ccc;

					.item-item {
						width: 150px;
						text-align: center;
						border-right: 1px solid #ccc;
					}

					.item-item1 {
						width: 250px;
						text-align: center;
						border-right: 1px solid #ccc;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
						cursor: pointer;

						&:hover {
							background: var(--color-bg-hover);
						}
					}

					.item-item2 {
						width: 200px;
						text-align: center;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
						cursor: pointer;

						&:hover {
							background: var(--color-bg-hover);
						}
					}
				}
			}
		}
	}

	.user-item {
		margin-top: 32px;
		height: 42px;
		display: flex;
		justify-content: flex-end;

		.user-bubble {
			line-height: 42px;
			border-radius: 21px 0px 21px 21px;
			background: rgba(234, 236, 238, 1);
			box-sizing: border-box;
			padding: 0 20px;
			text-align: right;
			word-wrap: break-word;

			.user-content {
				color: rgba(59, 65, 75, 1);
				font-family: Microsoft YaHei;
				font-size: 16px;
				font-weight: 400;
				line-height: 42px;
				letter-spacing: 0px;
				text-align: left;
			}
		}
	}
}

/* 加载指示器 */
.loading-indicator {
	margin-left: 26px;
	height: 30px;
	display: flex;
	gap: 4px;
	padding: 11px 0;
}

.dot {
	width: 8px;
	height: 8px;
	border-radius: 50%;
	background: #999;
	animation: bounce 1.4s infinite ease-in-out;
}

.dot:nth-child(1) {
	animation-delay: -0.32s;
}

.dot:nth-child(2) {
	animation-delay: -0.16s;
}
</style>