<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<Splitpanes>
				<Pane :size="65">
					<el-card class="w-full border-0 rounded-lg shadow-none">
						<!-- Document Display -->
						<div class="relative flex flex-col w-full">
							<div class="flex-1 w-full h-full mx-auto">
								<div class="relative flex items-center justify-center w-full h-full">
									<div class="w-full h-full overflow-y-auto scrollbar-slim" style="max-height: calc(100vh - 80px)">
										<vue-office-docx
											v-if="docxUrl"
											:src="baseURL + docxUrl"
											class="w-full border border-gray-100 rounded-md shadow-sm"
											@error="handleDocError"
										/>
										<div
											v-else
											class="flex-col items-center justify-center h-full p-10 mt-16 bg-white border-2 border-gray-200 border-dashed rounded-lg"
										>
											<div class="w-full max-w-md mx-auto">
												<upload-file @change="handleDocRendered" @error="handleDocError" v-model="docxUrl" :fileType="['docx']">
													<template #empty>
														<div class="p-8 text-center">
															<el-icon class="mb-2 text-4xl text-gray-400"><Document /></el-icon>
															<div class="font-medium text-gray-500">请上传Doc模板文件</div>
															<div class="mt-2 text-xs text-gray-400">支持.docx格式</div>
														</div>
													</template>
												</upload-file>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</el-card>
				</Pane>
				<Pane :size="35">
					<Splitpanes horizontal>
						<Pane :size="10">
							<el-card class="h-full bg-white border-0 rounded-lg shadow-none">
								<ControlPanel @clearAll="clearDoc" @saveData="saveData" @generate="handleGenerate" :hasDocument="!!docxUrl" class="h-full" />
							</el-card>
						</Pane>
						<Pane :size="90">
							<el-card class="h-full overflow-hidden bg-white border-0 rounded-lg shadow-none">
								<div class="h-full overflow-auto scrollbar-slim">
									<DataDisplay :markerList="markerList" @removeMarker="handleRemoveMarker" @editMarker="handleEditMarker" class="h-full" />
								</div>
							</el-card>
						</Pane>
					</Splitpanes>
				</Pane>
			</Splitpanes>
			<generate-dialog ref="generateDialogRef" :reportId="String(route.query.id || '')" />
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { Splitpanes, Pane } from 'splitpanes';
import { Document } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import 'splitpanes/dist/splitpanes.css';
import ControlPanel from './components/ControlPanel.vue';
import DataDisplay from './components/DataDisplay.vue';
import { putObj, getObj, parseDoc } from '/@/api/knowledge/aiReportConf';
// @ts-ignore 
import VueOfficeDocx from '@vue-office/docx/lib/v3/vue-office-docx.mjs';
import '@vue-office/docx/lib/v3/index.css';
import other from '/@/utils/other';
import GenerateDialog from './components/GenerateDialog.vue';

const route = useRoute();
const id = ref(route.query.id);
const baseURL = import.meta.env.VITE_API_URL;

const docxUrl = ref<string | null>(null);
const markerList = ref<any[]>([]);
const markerTemplate = ref<any[]>([]); // 存储标记模板
const generateDialogRef = ref();

function clearDoc() {
	docxUrl.value = null;
}

function handleRemoveMarker(id: number) {
	const index = markerList.value.findIndex((marker) => marker.id === id);
	if (index !== -1) {
		markerList.value.splice(index, 1);

		// 重新编号
		markerList.value = markerList.value.map((marker, idx) => ({
			...marker,
			label: (idx + 1).toString(),
		}));
	}
}

// 处理生成报告按钮点击
function handleGenerate() {
	if (generateDialogRef.value) {
		generateDialogRef.value.openDialog(id.value);
	}
}

// DOCX 文档加载事件处理
async function handleDocRendered() {
	// Document rendered successfully
	if (docxUrl.value) {
		try {
			const fileName = other.getQueryString(docxUrl.value, 'fileName');

			// 调用后台接口解析文档
			const { data } = await parseDoc({ id: id.value, reportResource: fileName });
			if (data) {
				// 更新标记列表
				markerList.value = data;
				ElMessage.success('文档解析成功');
			}
		} catch (error) {
			ElMessage.error('文档解析失败');
		}
	}
}

function handleDocError() {
	ElMessage.error('文档加载失败');
}

async function saveData() {
	// 检查底图是否存在
	if (!docxUrl.value) {
		ElMessage.warning('请先上传文档');
		return;
	}

	// 检查是否有标记点
	if (markerList.value.length === 0) {
		ElMessage.warning('请至少添加一个标记点');
		return;
	}

	// 检查所有标记点是否都有名称和描述
	const incompleteMarker = markerList.value.find((marker) => !marker.name || !marker.description);
	if (incompleteMarker) {
		ElMessage.warning(`请完善标记点 ${incompleteMarker.name} 的信息`);
		return;
	}

	try {
		await putObj({
			id: id.value,
			reportResource: docxUrl.value,
			reportMarked: JSON.stringify({
				markerList: markerList.value,
			}),
		});
		ElMessage.success('保存成功');
	} catch (error) {
		ElMessage.error('保存数据时出错');
	}
}

// 加载数据
async function loadData() {
	if (!id.value) {
		// 如果没有 id，清空所有数据
		clearAll();
		return;
	}

	try {
		const { data } = await getObj(id.value as string);

		// 加载数据
		if (data.reportResource) {
			docxUrl.value = data.reportResource;
		}
		if (data.reportMarked) {
			const reportMarked = JSON.parse(data.reportMarked);
			if (reportMarked.markerList) {
				markerList.value = reportMarked.markerList;
				markerTemplate.value = reportMarked.markerList;
			}
		}
	} catch (error) {
		ElMessage.error('加载数据失败');
		// 加载失败时也清空所有数据
		clearAll();
	}
}

// 添加清空所有数据的函数
function clearAll() {
	docxUrl.value = null;
	markerList.value = [];
	markerTemplate.value = [];
}

// 处理编辑标记
function handleEditMarker(updatedMarker: any) {
	const index = markerList.value.findIndex((marker) => marker.name === updatedMarker.name);
	if (index !== -1) {
		// 保持原有的其他属性（如果有的话）
		markerList.value[index] = {
			...markerList.value[index],
			name: updatedMarker.name,
			description: updatedMarker.description,
		};
	}
}

// 在组件挂载时加载数据
onMounted(() => {
	loadData();
});
</script>

<style scoped>
.el-main {
	padding: 0;
	overflow: hidden;
}

.el-card {
	height: 100%;
	display: flex;
	flex-direction: column;
}

.splitpanes__pane {
	overflow: hidden;
}

/* 自定义滚动条样式 */
.scrollbar-slim::-webkit-scrollbar {
	width: 6px;
	height: 6px;
}

.scrollbar-slim::-webkit-scrollbar-track {
	background-color: #f1f1f1;
	border-radius: 4px;
}

.scrollbar-slim::-webkit-scrollbar-thumb {
	background-color: #cbd5e1;
	border-radius: 4px;
}

.scrollbar-slim::-webkit-scrollbar-thumb:hover {
	background-color: #94a3b8;
}
</style>
