<template>
	<div class="wrap">
		<div class="header">
			<div class="header-top">
				<div class="header-top-left">
					<img :src="thinkInfo.imageUrl" alt="" />
					<div>
						<div class="title">{{ thinkInfo.name }}</div>
						<div class="en-title">
							{{ thinkInfo.ename }}
						</div>
						<div class="tag-box">
							<!-- <div class="tag-box" v-for="value,index in thinkInfo.tags" :key="index">
								<div class="tag">{{ value.industryName }}</div>
								
							</div> -->
							<AreaTag v-for="(value, index) in thinkInfo.tags" :key="index" :tagName="value.industryName"></AreaTag>
						</div>
					</div>
				</div>
				<div class="header-top-right">
					<div class="image-name-box">
						<div class="image"><img :src="thinkInfo.thinkTankLogoUrl" alt="" /></div>
						<div class="name">{{ thinkInfo.thinkTankName }}</div>
					</div>
					<div class="time">{{ thinkInfo.times }}</div>
				</div>
			</div>
			<div class="header-bottom">
				<div class="tab-box">
					<div class="tab" :class="{ tabActive: tabActiveName === '报告分析' }" @click="switchTab('报告分析')">
						<div class="icon">
							<img v-show="tabActiveName === '报告分析'" src="./images/tab-icon-active.png" alt="" />
							<img v-show="tabActiveName !== '报告分析'" src="./images/tab-icon.png" alt="" />
						</div>
						<div class="text" :class="{ textActive: tabActiveName === '报告分析' }">{{ "报告分析" }}</div>
					</div>
					<div class="tab" :class="{ tabActive: tabActiveName === '政策追踪' }" @click="switchTab('政策追踪')">
						<div class="icon">
							<img v-show="tabActiveName === '政策追踪'" src="./images/tab-icon2-active.png" alt="" />
							<img v-show="tabActiveName !== '政策追踪'" src="./images/tab-icon2.png" alt="" />
						</div>
						<div class="text" :class="{ textActive: tabActiveName === '政策追踪' }">{{ "政策追踪" }}</div>
					</div>
				</div>
				<div class="btn-box">
					<!-- <div class="btn">
						<div class="icon">
							<img src="./images/btn-icon1.png" alt="" />
						</div>
						<div class="text">{{ "查看官网" }}</div>
					</div> -->
					<!-- <div class="btn">
						<div class="icon">
							<img src="./images/btn-icon2.png" alt="" />
						</div>
						<div class="text" @click="goToOfficialWebsite()">{{ "查看官网" }}</div>
					</div> -->
					<div class="btn">
						<div class="icon">
							<img src="./images/btn-icon2.png" alt="" />
						</div>
						<div class="text" @click="toReport()">{{ "报告原文" }}</div>
					</div>
					<!-- <div class="btn" @click="handleDownloadDocument">
						<div class="icon">
							<img src="./images/btn-icon3.png" alt="" />
						</div>
						<div class="text">{{ "文档下载" }}</div>
					</div> -->
					<div class="btn btn1" @click="handleAnalysisClick">
						<div class="icon">
							<img src="./images/btn-icon4.png" alt="" />
						</div>
						<div class="text">{{ "分析报告" }}</div>
					</div>
				</div>
			</div>
		</div>
		<div class="main">
			<ReportAnalysis v-if="tabActiveName === '报告分析'" :thinkInfo="thinkInfo" :reportList="reportList"></ReportAnalysis>
			<PolicyTracking v-else></PolicyTracking>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";

import ReportAnalysis from "./reportAnalysis/index.vue";
import PolicyTracking from "./policyTracking/index.vue";
import { getThinkTankReportSummary, getThinkTankReportRelated, getThinkTankReportcontentUrl } from "@/api/thinkTank/overview";
import { useRoute, useRouter } from "vue-router";
const router = useRouter();
const route = useRoute();

const decodeRouteId = (raw) => {
	if (raw == null) return null;
	const s0 = String(raw);
	if (!s0) return null;

	// 明文 id（常见：Rand_... 或纯数字）直接返回，避免被误判为 base64
	if (/^\d+$/.test(s0) || /^Rand_/i.test(s0)) {
		return s0;
	}

	const tryParseJson = (str) => {
		if (typeof str !== "string") return null;
		const s = str.trim();
		if (!s) return null;
		try {
			return JSON.parse(s);
		} catch (_) {
			return null;
		}
	};

	const isProbablyBase64 = (s) => {
		// 过短的字符串（如 1/2）不参与 base64 解码，避免 atob 误解；
		// 但像 "Mg==" 这种带 padding 的短 base64 需要支持
		if (!s) return false;
		if (s.includes("=")) return true;
		if (s.length < 12) return false;
		return /^[A-Za-z0-9+/_-]+={0,2}$/.test(s);
	};
	const tryAtob = (val) => {
		if (val == null) return null;
		const s = String(val).trim();
		if (!s) return null;
		if (!isProbablyBase64(s)) return null;
		const normalized = s.replace(/-/g, "+").replace(/_/g, "/");
		const padded = normalized + "===".slice((normalized.length + 3) % 4);
		try {
			return atob(padded);
		} catch (_) {
			return null;
		}
	};

	// 1) 常规：base64(encodeURIComponent(id)) → atob → decodeURIComponent
	const atobStr = tryAtob(s0);
	if (atobStr != null) {
		try {
			const decoded = decodeURIComponent(atobStr);
			return tryParseJson(decoded) ?? decoded;
		} catch (_) {
			return tryParseJson(atobStr) ?? atobStr;
		}
	}

	// 2) 兜底：路由可能把二进制串 percent-encode（出现奇怪字符），尝试 latin1→utf8
	try {
		const utf8 = decodeURIComponent(escape(s0));
		if (utf8 && utf8 !== s0) {
			if (/^\d+$/.test(utf8) || /^Rand_/i.test(utf8)) return utf8;
			return tryParseJson(utf8) ?? utf8;
		}
	} catch (_) { }

	// 3) 明文 id：直接返回
	return s0;
};

const reportId = computed(() => decodeRouteId(route.params?.id));
const reportUrl = ref("");
const thinkInfo = ref({});
const reportList = ref({});

// 获取报告全局信息
const handleGetThinkTankReportSummary = async () => {
	try {
		const id = reportId.value;
		if (!id) return;
		const res = await getThinkTankReportSummary(id);
		console.log("报告全局信息", res);
		if (res.code === 200 && res.data) {
			reportUrl.value = res.data.reportUrl;
			thinkInfo.value = res.data;
			const title = String(res.data.name || "").trim();
			if (title) {
				document.title = title;
				window.sessionStorage.setItem("curTabName", title);
			}
			console.log(reportUrl.value, "reportUrl.value");
		}
	} catch (error) {
		console.error("获取报告全局信息error", error);
	}
};
// 获取相关报告信息
const handleGetThinkTankReport = async () => {
	try {
		const id = reportId.value;
		if (!id) return;
		const res = await getThinkTankReportRelated(id);
		console.log("报告全局信息", res);
		if (res.code === 200 && res.data) {
			reportList.value = res.data;
		}
	} catch (error) {
		console.error("获取相关报告error", error);
	}
};
const toReport = () => {
	console.log(reportUrl.value, "reportUrl.valuereportUrl.value");
	const id = reportId.value;
	if (!id) return;
	const encodedId = (() => {
		const s = String(id).trim();
		if (!s) return "";
		try { return btoa(encodeURIComponent(s)); } catch (_) { return s; }
	})();
	if (!encodedId) return;
	const route = router.resolve({
		name: "ReportOriginal",
		params: {
			id: encodedId
		}
	});
	console.log("route.href", route.href);
	window.open(route.href, "_blank");
};
const tabActiveName = ref("报告分析");

const switchTab = name => {
	tabActiveName.value = name;
};

const handleAnalysisClick = () => {
	const id = reportId.value;
	if (!id) return;
	router.push({
		path: "/writtingAsstaint",
		query: {
			topic: "智库",
			fileId: id
		}
	});
};
onMounted(async () => {
	handleGetThinkTankReportSummary();
	handleGetThinkTankReport();
});
const goToOfficialWebsite = () => {
	const url = thinkInfo.value?.reportUrl;
	if (!url) {
		return;
	}
	// 简单校验一下，防止空字符串
	window.open(url, "_blank");
};

// 文档下载：先拉取 PDF 地址，再中英文都下载（与报告原文页相同方式）
const downloadOnePdf = async (url, filename) => {
	const response = await fetch(url, {
		method: "GET",
		headers: { "Content-Type": "application/pdf" }
	});
	if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
	const blob = await response.blob();
	const blobUrl = window.URL.createObjectURL(blob);
	const link = document.createElement("a");
	link.href = blobUrl;
	link.download = filename;
	document.body.appendChild(link);
	link.click();
	document.body.removeChild(link);
	window.URL.revokeObjectURL(blobUrl);
};

const handleDownloadDocument = async () => {
	try {
		const { ElMessage } = await import("element-plus");
		const id = reportId.value;
		if (!id) return;
		const res = await getThinkTankReportcontentUrl(id);
		if (res.code !== 200 || !res.data) {
			ElMessage.warning("暂无下载链接");
			return;
		}
		const urlZh = res.data.content ? String(res.data.content).split("#")[0] : "";
		const urlEn = res.data.contentEn ? String(res.data.contentEn).split("#")[0] : "";
		if (!urlZh && !urlEn) {
			ElMessage.warning("暂无下载链接");
			return;
		}
		const baseName = (thinkInfo.value?.name || "报告原文").replace(/[/\\?%*:|"<>]/g, "-");
		if (urlZh) {
			await downloadOnePdf(urlZh, `${baseName}_中文.pdf`);
		}
		if (urlEn) {
			if (urlZh) await new Promise(r => setTimeout(r, 300));
			await downloadOnePdf(urlEn, `${baseName}_英文.pdf`);
		}
		ElMessage.success(urlZh && urlEn ? "已下载中文、英文两份 PDF" : "下载成功");
	} catch (error) {
		console.error("文档下载失败:", error);
		try {
			const { ElMessage } = await import("element-plus");
			ElMessage.error("PDF 下载失败，请稍后重试");
		} catch (_) { }
	}
};
</script>

<style lang="scss" scoped>
.wrap {
	width: 100%;
	height: 100%;
	overflow: hidden;
	overflow-y: auto;

	.header {
		width: 100%;
		height: 188px;
		box-sizing: border-box;
		border-bottom: 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);
		overflow: hidden;

		.header-top {
			margin: 0 auto;
			margin-top: 20px;
			width: 1600px;
			display: flex;
			justify-content: space-between;

			.header-top-left {
				display: flex;

				img {
					width: 178px;
					height: 88px;
				}

				.title {
					margin-left: 20px;
					height: 26px;
					color: rgba(59, 65, 75, 1);
					font-family: Microsoft YaHei;
					font-size: 20px;
					font-weight: 700;
					line-height: 26px;
					letter-spacing: 0px;
					text-align: left;
				}

				.en-title {
					margin-left: 20px;
					height: 24px;
					color: rgba(95, 101, 108, 1);
					font-family: Microsoft YaHei;
					font-size: 16px;
					font-weight: 400;
					line-height: 24px;
					letter-spacing: 0px;
					text-align: left;
				}

				.tag-box {
					margin-top: 11px;
					display: flex;
					gap: 8px;
					margin-left: 20px;
				}
			}

			.header-top-right {
				display: flex;
				flex-direction: column;
				text-align: right;
				align-items: flex-end;

				.image-name-box {
					width: 118px;
					height: 24px;
					gap: 6px;

					text-align: right;
					display: flex;
					justify-content: flex-end;

					.name {
						height: 24px;
						color: rgba(95, 101, 108, 1);
						font-family: Microsoft YaHei;
						font-size: 16px;
						font-weight: 400;
						line-height: 24px;
						letter-spacing: 0px;
						text-align: right;
					}

					.image {
						width: 16px;
						height: 16px;

						margin-top: 5px;

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

				.time {
					height: 24px;
					margin-top: 5px;
					color: rgba(95, 101, 108, 1);
					font-family: Microsoft YaHei;
					font-size: 16px;
					font-weight: 400;
					line-height: 24px;
					letter-spacing: 0px;
					text-align: right;
				}
			}
		}

		.header-bottom {
			margin: 0 auto;
			margin-top: 30px;
			width: 1600px;
			height: 48px;
			display: flex;
			justify-content: space-between;

			.tab-box {
				width: 224px;
				height: 48px;
				display: flex;
				gap: 24px;

				.tab {
					width: 94px;
					height: 48px;
					display: flex;
					align-items: center;
					justify-content: center;
					gap: 4px;
					cursor: pointer;
					border-bottom: 2px solid transparent;

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

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

					.text {
						height: 24px;
						color: rgba(59, 65, 75, 1);
						font-family: Microsoft YaHei;
						font-size: 18px;
						font-weight: 400;
						line-height: 24px;
					}

					.textActive {
						color: rgba(5, 95, 194, 1);
						font-weight: 700;
					}
				}

				.tabActive {
					border-bottom: 2px solid rgba(5, 95, 194, 1);
				}
			}

			.btn-box {
				display: flex;
				gap: 12px;

				.btn {
					width: 120px;
					height: 36px;
					box-sizing: border-box;
					border: 1px solid rgba(230, 231, 232, 1);
					border-radius: 6px;
					background: rgba(255, 255, 255, 1);
					display: flex;
					align-items: center;
					justify-content: center;
					gap: 8px;
					cursor: pointer;
					;

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

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

					.text {
						width: 66px;
						height: 22px;
						color: rgba(95, 101, 108, 1);
						font-family: Microsoft YaHei;
						font-size: 16px;
						font-weight: 400;
						line-height: 22px;
						letter-spacing: 0px;
						text-align: center;
					}
				}

				.btn1 {
					border-radius: 6px;
					background: var(--color-main-active);

					.text {
						color: rgba(255, 255, 255, 1);
					}
				}
			}
		}
	}

	.main {
		width: 100%;
	}
}
</style>
