<template>
	<div class="writting-wrapper">
		<div class="writting-header">
			<div class="tab-box">
				<div class="tab" :class="{ tabActive: item.active }" v-for="(item, index) in tabList" :key="index">
					{{ item.name }}
				</div>
			</div>
			<div class="edit-box"></div>
			<div class="btn-box">
				<div class="btn" @click="exportContent">
					<div class="icon">
						<img src="./assets/images/export-icon.png" alt="" />
					</div>
					<div class="text">{{ "导出" }}</div>
				</div>
				<div class="btn" @click="handleSwitchMode">
					<div class="icon">
						<img v-if="isEditMode" src="./assets/images/preview-icon.png" alt="" />
						<img v-else src="./assets/images/edit.png" alt="" />
					</div>
					<div class="text">{{ isEditMode ? "预览" : "编辑" }}</div>
				</div>
				<div class="btn btn1">
					<div class="icon">
						<img src="./assets/images/save-icon.png" alt="" />
					</div>
					<div class="text text1">{{ "保存" }}</div>
				</div>
			</div>
		</div>
		<div class="writting-main">
			<div class="sider">
				<div class="sider-box1">
					<div class="header">报文主题</div>
					<div class="title-box">
						<div class="title">主题名称</div>
						<el-input
							style="width: 476px; height: 32px"
							class="title-input"
							placeholder="输入主题名称，如：大而美法案"
							v-model="writtingTitle"
						/>
					</div>
					<div class="description-box">
						<div class="title">主题描述</div>
						<el-input
							class="description-input"
							type="textarea"
							style="width: 476px"
							:rows="8"
							placeholder="输入报文主题描述，如：从科技领域方面分析大而美法案通过后对中国可能产生的影响"
							v-model="descText"
						/>
					</div>
				</div>
				<div class="sider-box2">
					<div class="header">报文模板</div>
					<div class="template-box">
						<div
							class="template"
							:class="{ tempActive: tempActiveIndex === index }"
							v-for="(temp, index) in tempList"
							:key="index"
							@click="handleClickTemp(item, index)"
						>
							<div class="header">
								<div class="title">{{ temp.title }}</div>
								<div class="icon">
									<img src="./assets/images/template-icon.png" alt="" />
								</div>
							</div>
							<div class="content">{{ temp.desc }}</div>
							<div class="active-icon" v-if="tempActiveIndex === index">
								<img src="./assets/images/active-icon.png" alt="" />
							</div>
							<div class="selected-icon" v-if="tempActiveIndex === index">
								<img src="./assets/images/selected-icon.png" alt="" />
							</div>
						</div>
					</div>
					<div class="tips">
						<div class="tips-icon">
							<img src="./assets/images/tips-icon.png" alt="" />
						</div>
						<div class="tips-text">内容由AI生成，无法确保真实准确，仅供参考</div>
					</div>
				</div>
				<div class="submit-btn" @click="getStreamChat">
					<div class="submit-icon">
						<img src="./assets/images/ai.png" alt="" />
					</div>
					<div class="submit-text">生成报文</div>
				</div>
			</div>
			<!-- <div class="process-box">
				<div class="back">
					{{ "< 返回" }}
				</div>
				<div class="process-main-box">
					<div class="analysis-box">
						<div class="analysis-header">
							<div class="icon">
								<img src="./assets/images/right-arrow.png" alt="" />
							</div>
							<div class="text">{{ "任务分析：" }}</div>
						</div>
						<div class="analysis-content">
							{{
								"用户需求属于态势要图制图任务，需要围绕“伊以冲突”主题生成关键词、搜索相关新闻、抽取并聚类事件、获取地理位置信息，最终完成事件和地点的可视化标绘"
							}}
						</div>
					</div>
					<div class="steps-box">
						<div class="steps-header">
							<div class="icon">
								<img src="./assets/images/right-arrow.png" alt="" />
							</div>
							<div class="text">{{ "执行步骤：" }}</div>
						</div>
						<div class="steps-content">
							<div class="steps" v-for="(step, index) in steps" :key="index">
								<div class="steps-id">{{ step.id }}</div>
								<div class="steps-content">{{ step.content }}</div>
							</div>
						</div>
					</div>
					<div class="doing-box">
						{{ "正在执行步骤1/7:根据制图主题生成关键词" }}
					</div>
					<div class="tool-box">
						<div class="tool-header">{{ '工具调用' }}</div>
						<div class="tool-main"></div>
					</div>
				</div>
				<div class="process-tips-box">
					<div class="tips-icon">
						<img src="./assets/images/tips-icon.png" alt="" />
					</div>
					<div class="tips-text">内容由AI生成，无法确保真实准确，仅供参考</div>
				</div>
				<div class="process-footer-box">
					<div class="footer-left">
						{{ "报文生成中..." }}
					</div>
					<div class="footer-right">
						<div class="icon"></div>
						<div class="text">{{ "停止" }}</div>
					</div>
				</div>
			</div> -->
			<div class="main-box">
				<div v-if="isEditMode" class="edit-panel">
					<v-md-editor
						v-model="reportContent"
						height="calc(100% - 40px)"
						:disabled-menus="[]"
						@upload-image="handleUploadImage"
						@save="handleSave"
						left-toolbar="undo redo clear | h bold italic strikethrough quote | ul ol table hr | link image code | save"
						right-toolbar="preview toc sync-scroll fullscreen"
					/>
				</div>
				<div v-else class="content-box" ref="scrollContainer" v-html="renderedContent"></div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { useMarkdownStream } from "@/hooks/useMarkdownStream";
import { fetchEventSource } from "@microsoft/fetch-event-source";

import VMdEditor from "@kangc/v-md-editor";
import "@kangc/v-md-editor/lib/style/base-editor.css";
import vuepressTheme from "@kangc/v-md-editor/lib/theme/vuepress.js";
import "@kangc/v-md-editor/lib/theme/style/vuepress.css";

// 引入 Prism 相关依赖
import Prism from "prismjs";

VMdEditor.use(vuepressTheme, {
	Prism
});

const steps = [
	{
		id: 1,
		content: "111111111111111111111111111"
	},
	{
		id: 2,
		content: "111111111111111111111111111"
	},
	{
		id: 3,
		content: "111111111111111111111111111222222222222222222222222222222222233333333333333333333333333"
	},
	{
		id: 4,
		content: "111111111111111111111111111"
	},
	{
		id: 5,
		content: "111111111111111111111111111"
	},
	{
		id: 6,
		content: "111111111111111111111111111"
	},
	{
		id: 7,
		content: "111111111111111111111111111"
	}
];

const isEditMode = ref(false);

const handleSwitchMode = () => {
	isEditMode.value = !isEditMode.value;
	if (!isEditMode.value) {
		console.log(reportContent.value);
		updateContent(reportContent.value, scrollContainer.value);
	}
};

// 保存处理函数
const handleSave = (text, html) => {
	console.log("保存内容:", {
		markdown: text,
		html: html
	});

	reportContent.value = text;
	// 实际保存逻辑
	// saveToLocalStorage(text);
	ElMessage.success("保存成功！");
};

// 保存到本地存储
const saveToLocalStorage = text => {
	localStorage.setItem("markdown-content", text);
};

const abortController = ref(null);

const scrollContainer = ref(null);
const { renderedContent, updateContent } = useMarkdownStream();

const reportContent = ref("");

const curTempTitle = ref("法案");

const getStreamChat = async (search, inputValue) => {
	const params = {
		query: writtingTitle.value, // "输出一篇报文"
		desc: descText.value,
		topic: curTempTitle.value // 政令、智库、法案、清单
	};

	abortController.value = new AbortController();

	fetchEventSource("/sse/api/v1/chat/stream", {
		method: "POST",
		headers: {
			"Content-Type": "application/json"
		},
		body: JSON.stringify(params),
		signal: abortController.value.signal,
		openWhenHidden: true,
		async onopen(res) {
			console.log("流式回答开始", res);
		},
		async onmessage(res) {
			let msgData = JSON.parse(res.data);
			console.log("resss", msgData.content);
			let str = msgData.content;
			if (str !== "[DONE]") {
			reportContent.value += str;
			if (reportContent.value.includes("./out/img")) {
				reportContent.value = reportContent.value.replaceAll("./out/img", "http://192.168.26.70:8000/out/img");
				console.log(111, reportContent.value);
			}
			updateContent(reportContent.value, scrollContainer.value);
			} else {
				ElMessage.success("报文生成结束");
				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);
	});
};

const writtingTitle = ref("");
const descText = ref("");
const tabList = ref([
	{
		name: "写报",
		active: true
	},
	{
		name: "收藏",
		active: false
	},
	{
		name: "问答",
		active: false
	}
]);
const tempList = ref([
	{
		title: "法案",
		desc: "基于法案内容生成各维度的综合分析报告"
	},
	{
		title: "智库",
		desc: "基于智库内容生成各维度的综合分析报告"
	},
	{
		title: "政令",
		desc: "基于政令内容生成各维度的综合分析报告"
	},
	{
		title: "清单",
		desc: "基于清单内容生成各维度的综合分析报告"
	}
]);

const tempActiveIndex = ref(0);

const handleClickTemp = (item, index) => {
	tempActiveIndex.value = index;
	curTempTitle.value = item.title;
};

// 导出
const exportContent = () => {
	const blob = new Blob([reportContent.value], { type: "text/markdown" });
	const url = URL.createObjectURL(blob);
	const a = document.createElement("a");
	a.href = url;
	a.download = `markdown-${new Date().getTime()}.md`;
	a.click();
	URL.revokeObjectURL(url);
};

onMounted(() => {
	// const str = '# 欢迎使用 Markdown 编辑器\n\n这是一个功能丰富的 Markdown 编辑器示例。\n\n## 功能特性\n\n- ✨ **实时预览**\n- 🎨 **代码高亮**\n- 📁 **图片上传**\n- 📊 **表格支持**\n- 🔗 **链接管理**\n\n```javascript\n// 示例代码\nconst message = "Hello Markdown!";\nconsole.log(message);\n```'
	// updateContent(str, scrollContainer.value);
});

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

<style lang="scss" scoped>
.writting-wrapper {
	width: 100%;
	height: 100%;
	.writting-header {
		height: 60px;
		box-sizing: border-box;
		border-bottom: 1px solid rgba(234, 236, 238, 1);
		border-top: 1px solid rgba(234, 236, 238, 1);
		box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
		background: rgba(255, 255, 255, 1);
		display: flex;
		position: relative;
		.tab-box {
			display: flex;
			margin-left: 130px;
			margin-top: 13px;
			width: 260px;
			height: 46px;
			justify-content: space-between;
			.tab {
				color: rgba(95, 101, 108, 1);
				font-family: Microsoft YaHei;
				font-size: 20px;
				font-weight: 400;
				line-height: 30px;
			}
			.tabActive {
				color: rgba(5, 95, 194, 1);
				font-family: Microsoft YaHei;
				font-size: 20px;
				font-weight: 700;
				line-height: 30px;
				border-bottom: 4px solid rgba(5, 95, 194, 1);
			}
		}
		.btn-box {
			position: absolute;
			top: 12px;
			right: 39px;
			display: flex;
			gap: 12px;
			.btn {
				display: flex;
				justify-content: center;
				align-items: center;
				width: 88px;
				height: 36px;
				gap: 8px;
				box-sizing: border-box;
				border: 1px solid rgba(230, 231, 232, 1);
				border-radius: 6px;
				background: rgba(255, 255, 255, 1);
				cursor: pointer;
				.icon {
					width: 16px;
					height: 16px;
					img {
						width: 100%;
						height: 100%;
					}
				}
				.text {
					width: 32px;
					height: 24px;
					color: rgba(95, 101, 108, 1);
					font-family: Microsoft YaHei;
					font-size: 16px;
					font-weight: 400;
					line-height: 24px;
				}
				.text1 {
					color: #fff;
				}
			}
			.btn1 {
				background: rgba(5, 95, 194, 1);
			}
		}
	}
	.writting-main {
		display: flex;
		height: calc(100% - 60px);
		position: relative;
		.process-box {
			position: absolute;
			left: 0;
			top: 0;
			width: 520px;
			height: 100%;
			z-index: 9999;
			background: #fff;
			.back {
				margin-top: 21px;
				height: 24px;
				line-height: 24px;
				margin-left: 22px;
				color: var(--color-main-active);
				font-family: Microsoft YaHei;
				font-size: 16px;
				font-weight: 400;
				line-height: 24px;
				cursor: pointer;
			}
			.process-main-box {
				margin-top: 20px;
				margin-left: 22px;
				width: 476px;
				height: 900px;
				// background: orange;
				.analysis-box {
					.analysis-header {
						display: flex;
						.icon {
							margin-top: 5px;
							width: 20px;
							height: 20px;
							img {
								width: 100%;
								height: 100%;
							}
						}
						.text {
							height: 30px;
							line-height: 30px;
							font-family: Microsoft YaHei;
							color: #333;
							font-size: 20px;
							font-weight: 700;
							margin-left: 5px;
						}
					}
					.analysis-content {
						height: 90px;
						line-height: 30px;
						color: #555;
						font-family: Microsoft YaHei;
						font-size: 16px;
						font-weight: 400;
						text-indent: 32px;
					}
				}
				.steps-box {
					margin-top: 20px;
					.steps-header {
						display: flex;
						.icon {
							margin-top: 5px;
							width: 20px;
							height: 20px;
							img {
								width: 100%;
								height: 100%;
							}
						}
						.text {
							height: 30px;
							line-height: 30px;
							font-family: Microsoft YaHei;
							color: #333;
							font-size: 20px;
							font-weight: 700;
							margin-left: 5px;
						}
					}
					.steps-content {
						max-height: 500px;
						width: 100%;
						background: skyblue;
						overflow-x: hidden;
						overflow-y: auto;
						.steps {
							display: flex;
							width: 410px;
							margin-left: 40px;

							color: #555;
							font-family: Microsoft YaHei;

							line-height: 35px;
							.steps-id {
								width: 20px;
								font-size: 18px;
								font-weight: 700;
							}
							.steps-content {
								font-size: 16px;
								font-weight: 400;
								width: 430px;
								word-wrap: break-word;
							}
						}
					}
				}
				.doing-box {
					height: 40px;
					line-height: 40px;
					color: #555;
					font-family: Microsoft YaHei;
					font-size: 16px;
					font-weight: 400;
					margin-left: 20px;
				}
				.tool-box {
					width: 440px;
					height: 160px;
					margin: 10px auto;
					background: #f6f9fe;
					border-radius: 10px;
					.tool-header {
						height: 30px;
						line-height: 30px;
						margin-left: 20px;
						color: var(--color-main-active);
					}
					.tool-main {
						height: 110px;
						width: 400px;
						margin: 0 auto;
						background: #fff;
					}
				}
			}
			.process-tips-box {
				position: absolute;
				left: 22px;
				bottom: 81px;
				height: 22px;
				display: flex;
				.tips-icon {
					width: 14px;
					height: 16px;
					margin-top: 3px;
					img {
						width: 100%;
						height: 100%;
					}
				}
				.tips-text {
					margin-left: 8px;
					color: rgba(132, 136, 142, 1);
					font-family: Microsoft YaHei;
					font-size: 14px;
					font-weight: 400;
					line-height: 22px;
				}
			}
			.process-footer-box {
				height: 36px;
				display: flex;
				position: absolute;
				left: 22px;
				bottom: 29px;
				.footer-left {
					width: 348px;
					height: 36px;
					border-radius: 4px;
					background: rgba(234, 236, 238, 1);
					color: rgba(132, 136, 142, 1);
					font-family: Microsoft YaHei;
					font-size: 16px;
					font-weight: 400;
					text-align: center;
					line-height: 36px;
				}
				.footer-right {
					margin-left: 8px;
					display: flex;
					width: 120px;
					height: 36px;
					box-sizing: border-box;
					border: 1px solid var(--color-main-active);
					border-radius: 4px;
					background: rgba(246, 250, 255, 1);
					justify-content: center;
					align-items: center;
					gap: 8px;
					cursor: pointer;
					.icon {
						width: 8px;
						height: 8px;
						border-radius: 2px;
						background: var(--color-main-active);
					}
					.text {
						color: var(--color-main-active);
						font-family: Microsoft YaHei;
						font-size: 16px;
						font-weight: 400;
						line-height: 24px;
					}
				}
			}
		}
		.sider {
			width: 520px;
			box-sizing: border-box;
			border-right: 1px solid rgba(234, 236, 238, 1);
			border-top: 1px solid rgba(234, 236, 238, 1);
			background: rgba(255, 255, 255, 1);
			position: relative;
			.sider-box1 {
				margin-top: 21px;
				margin-left: 22px;
				.header {
					color: rgba(59, 65, 75, 1);
					font-family: Microsoft YaHei;
					font-size: 16px;
					font-weight: 700;
					line-height: 24px;
				}
				.title-box {
					margin-top: 15px;
					.title {
						color: rgba(95, 101, 108, 1);
						font-family: Microsoft YaHei;
						font-size: 16px;
						font-weight: 400;
						line-height: 24px;
					}
					.title-input {
						margin-top: 15px;
					}
				}
				.description-box {
					margin-top: 24px;
					.title {
						height: 24px;
						color: rgba(95, 101, 108, 1);
						font-family: Microsoft YaHei;
						font-size: 16px;
						font-weight: 400;
						line-height: 24px;
					}
					.description-input {
						margin-top: 12px;
						height: 200px;
					}
				}
			}
			.sider-box2 {
				margin-top: 24px;
				margin-left: 22px;
				.header {
					height: 24px;
					color: rgba(59, 65, 75, 1);
					font-family: Microsoft YaHei;
					font-size: 16px;
					font-weight: 700;
					line-height: 24px;
				}
				.template-box {
					margin-top: 19px;
					height: 260px;
					display: flex;
					flex-wrap: wrap;
					gap: 16px;
					.template {
						width: 230px;
						height: 120px;
						box-sizing: border-box;
						border: 1px solid rgba(234, 236, 238, 1);
						border-radius: 4px;
						position: relative;
						cursor: pointer;
						.active-icon {
							width: 24px;
							height: 24px;
							position: absolute;
							top: 0;
							right: 0;
							z-index: 99;
							img {
								width: 100%;
								height: 100%;
							}
						}
						.selected-icon {
							width: 8px;
							height: 6px;
							position: absolute;
							top: -4px;
							right: 3px;
							z-index: 100;
							img {
								width: 8px;
								height: 6px;
							}
						}
						.header {
							display: flex;
							justify-content: space-between;
							height: 50px;
							.title {
								height: 24px;
								// color: rgba(59, 65, 75, 1);
								color: #333;
								font-family: Microsoft YaHei;
								font-size: 16px;
								font-weight: 700;
								line-height: 24px;
								margin-left: 15px;
								margin-top: 16px;
							}
							.icon {
								margin-top: 15px;
								margin-right: 16px;
								width: 30px;
								height: 30px;
								border-radius: 15px;
								background: rgba(231, 243, 255, 1);
								img {
									width: 17px;
									height: 14px;
									margin-top: 8px;
									margin-left: 7px;
								}
							}
						}
						.content {
							margin: 0 auto;
							width: 200px;
							height: 48px;
							margin-top: 10px;
							color: rgba(132, 136, 142, 1);
							font-family: Microsoft YaHei;
							font-size: 16px;
							font-weight: 400;
							line-height: 24px;
						}
					}
					.tempActive {
						border: 1px solid rgba(5, 95, 194, 1);
						background: rgba(246, 250, 255, 1);
					}
				}
				.tips {
					margin-top: 19px;
					height: 22px;
					display: flex;
					.tips-icon {
						width: 14px;
						height: 16px;
						margin-top: 3px;
						img {
							width: 100%;
							height: 100%;
						}
					}
					.tips-text {
						margin-left: 8px;
						color: rgba(132, 136, 142, 1);
						font-family: Microsoft YaHei;
						font-size: 14px;
						font-weight: 400;
						line-height: 22px;
					}
				}
			}
			.submit-btn {
				position: absolute;
				left: 22px;
				bottom: 13px;
				width: 476px;
				height: 36px;
				border-radius: 4px;
				background: rgba(5, 95, 194, 1);
				display: flex;
				justify-content: center;
				cursor: pointer;
				&:hover {
					background: rgba(5, 95, 194, 0.8);
				}
				.submit-icon {
					/* AI-logo */
					width: 21px;
					height: 15px;
					margin-top: 10px;
					img {
						width: 100%;
						height: 100%;
					}
				}
				.submit-text {
					height: 24px;
					margin-top: 5px;
					color: rgba(255, 255, 255, 1);
					font-family: Microsoft YaHei;
					font-size: 16px;
					font-weight: 400;
					line-height: 24px;
					margin-left: 8px;
				}
			}
		}
		.main-box {
			flex: 1;
			background: #f7f8f9;
			.edit-panel {
				width: calc(100% - 100px);
				height: calc(100% - 40px);
				margin: 20px 50px;
			}
			.content-box {
				width: calc(100% - 100px);
				height: calc(100% - 40px);
				margin: 20px 50px;
				// height: 500px;
				overflow-y: auto;
				padding: 20px;
				border: 1px solid #dcdfe6;
				border-radius: 8px;
				background: #fafafa;
				line-height: 1.7;
				// font-size: 20px;
				font-size: 16px;
			}
		}
	}
}

:deep(.el-input__wrapper) {
	background: #f7f8f9;
}

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

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

:deep(.el-textarea__inner) {
	background: #f7f8f9;
}

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

:deep(.el-textarea__inner::placeholder) {
	color: rgba(132, 136, 142, 1);
	font-family: Microsoft YaHei;
	font-size: 16px;
	font-weight: 400;
	line-height: 24px;
}
</style>