<template>
	<BaseDecreeOriginal
		:summary-info="summaryInfo"
		:report-data="reportData"
		@download="handleDownload"
	/>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { getDecreeSummary } from "@/api/decree/introduction";
import { getDecreeReport } from "@/api/decree/introduction";
import BaseDecreeOriginal from "@/components/base/DecreeOriginal/index.vue";

const route = useRoute();
const handleDownload = async () => {
	if (summaryInfo.value?.url) {
		try {
			const response = await fetch(summaryInfo.value.url, {
				method: 'GET',
				headers: { 'Content-Type': 'application/pdf' },
			});
			
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}
			
			const blob = await response.blob();
			
			// 创建 Blob URL
			const blobUrl = window.URL.createObjectURL(blob);
			
			// 创建隐藏的下载链接
			const link = document.createElement('a');
			link.href = blobUrl;
			link.download = `${summaryInfo.value.name}.pdf`;
			
			// 添加到文档中并点击
			document.body.appendChild(link);
			link.click();
			
			// 清理
			document.body.removeChild(link);
			window.URL.revokeObjectURL(blobUrl);
			
		} catch (error) {
			console.error('下载失败:', error);
			// 可以在这里提示用户下载失败
			alert('PDF 下载失败，请稍后重试');
		}
	} else {
		ElMessage.warning("暂无下载链接!");
	}
}

// 获取全局信息
const summaryInfo = ref({});
const handleGetSummary = async () => {
	const params = {
		id: route.query.id
	};
	try {
		const res = await getDecreeSummary(params);
		console.log("全局信息", res);
		if (res.code === 200 && res.data) {
			summaryInfo.value = res.data;
		}
	} catch (error) { }
};

// 获取报告原文 - 修改为获取分段数组
const reportData = ref([]);
const handleGetReport = async () => {
	try {
		const res = await getDecreeReport({id: route.query.id});
		console.log("报告原文", res);
		if (res.code === 200 && res.data) {
			const originData = [];
			let num = Math.max(res.data.content.length, res.data.contentEn.length)
			for (let i = 0; i < num; i++) {
				let obj = {
					content: res.data.content[i] || "",
					contentEn: res.data.contentEn[i] || "",
					num: i + 1,
				}
				originData.push(obj);
			}
			reportData.value = JSON.parse(JSON.stringify(originData));
		}
	} catch (error) { }
};

onMounted(() => {
	handleGetSummary();
	handleGetReport();
});
</script>

<style lang="scss" scoped>
</style>