<template>
	<div class="layout-container">
		<!-- 导航菜单 -->
		<div class="layout-main">
			<BillHeader :billInfo="billInfoGlobal" :defaultLogo="USALogo" :tabs="mainHeaderBtnList"
				:activeTitle="activeTitle" :showTabs="showHeaderTabs" :showActions="showHeaderActions"
				:showForsee="showForseeAction" @tab-click="handleClickMainHeaderBtn"
				@open-analysis="handleAnalysisClick" />

			<div class="layout-main-center">
				<router-view />
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from "vue";
import router from "@/router";
import { useRoute } from "vue-router";
import { getBillInfoGlobal, getBillInfo } from "@/api/bill";
import BillHeader from "./components/BillHeader.vue";

const route = useRoute();

import icon1 from "./assets/icons/icon1.svg";
import icon1Active from "./assets/icons/icon1_active.svg";
import icon2 from "./assets/icons/icon2.svg";
import icon2Active from "./assets/icons/icon2_active.svg";
import icon3 from "./assets/icons/icon3.svg";
import icon3Active from "./assets/icons/icon3_active.svg";
import icon4 from "./assets/icons/icon4.svg";
import icon4Active from "./assets/icons/icon4_active.svg";
import USALogo from "./assets/images/USA-logo.png";

// 获取法案全局信息
const billInfoGlobal = ref({});
const getBillInfoGlobalFn = async () => {
	const res = await getBillInfoGlobal({
		id: route.query.billId
	});
	if (res.code === 200) {
		console.log("法案全局信息", res);
		if (res.data) {
			billInfoGlobal.value = res.data;
		}
	}
};

const mainHeaderBtnList = ref([
	{
		icon: icon1,
		activeIcon: icon1Active,
		name: "法案概况",
		path: "/billLayout/bill"
	},
	{
		icon: icon2,
		activeIcon: icon2Active,
		name: "深度挖掘",
		path: "/billLayout/deepDig"
	},
	{
		icon: icon3,
		activeIcon: icon3Active,
		name: "影响分析",
		path: "/billLayout/influence"
	},
	// {
	// 	icon: icon4,
	// 	activeIcon: icon4Active,
	// 	name: "相关情况",
	// 	path: "/billLayout/relevantCircumstance"
	// }
]);

const activeTitle = ref("法案概况");
const showHeaderTabs = ref(true);
const showHeaderActions = ref(true);

const billBasicInfo = ref({});
const getBillBasicInfoFn = async () => {
	const billId = route.query.billId;
	if (!billId) return;
	try {
		const res = await getBillInfo({ id: billId });
		billBasicInfo.value = res?.data || {};
	} catch (error) {
		console.error(error);
		billBasicInfo.value = {};
	}
};

const showForseeAction = computed(() => {
	const stageList = Array.isArray(billBasicInfo.value?.stageList) ? billBasicInfo.value.stageList : [];
	const latestStage = stageList.length ? String(stageList[stageList.length - 1] || "").trim() : "";
	return !latestStage.includes("完成立法");
});

const getActiveTitleByRoutePath = path => {
	if (path.startsWith("/billLayout/deepDig")) return "深度挖掘";
	if (path.startsWith("/billLayout/influence")) return "影响分析";
	if (path.startsWith("/billLayout/relevantCircumstance")) return "相关情况";
	// /billLayout/bill 及其子路由（introduction/background/template）都归为“法案概况”
	return "法案概况";
};

const syncHeaderStateFromRoute = () => {
	const currentPath = route.path || "";
	activeTitle.value = getActiveTitleByRoutePath(route.path);
	const isVersionCompare = currentPath.startsWith("/billLayout/versionCompare");
	showHeaderTabs.value = !isVersionCompare;
	showHeaderActions.value = !isVersionCompare;
};

const handleClickMainHeaderBtn = item => {
	// if (["影响分析", "相关情况"].includes(item.name)) {
	// 	ElMessage.warning("当前功能正在开发中，敬请期待！");
	// 	return;
	// }
	activeTitle.value = item.name;
	window.sessionStorage.setItem("activeTitle", activeTitle.value);
	router.push({
		path: item.path,
		query: {
			billId: route.query.billId
		}
	});
};

const handleAnalysisClick = analysisType => {
	const billId = route.query.billId;
	if (!billId) return;

	// 进展预测 -> 法案简介页（法案进展）
	if (analysisType === "forsee") {
		const target = router.resolve({
			path: `/billLayout/ProgressForecast/${billId}`,
		});
		window.open(target.href, "_blank");
		return;
	}

	// 分析报告 -> 写作助手
	router.push({
		path: "/writtingAsstaint",
		query: {
			topic: "法案",
			fileId: String(billId)
		}
	});
};

onMounted(() => {
	getBillInfoGlobalFn();
	getBillBasicInfoFn();
	// 以当前路由为准，避免 sessionStorage 造成高亮错乱
	syncHeaderStateFromRoute();
	// 兜底：如果未来出现未知路由且有缓存，再用缓存
	const cachedTitle = window.sessionStorage.getItem("activeTitle");
	if (!activeTitle.value && cachedTitle) activeTitle.value = cachedTitle;
});

watch(
	() => route.path,
	() => {
		syncHeaderStateFromRoute();
	}
);

watch(
	() => route.query.billId,
	() => {
		getBillInfoGlobalFn();
		getBillBasicInfoFn();
	},
	{ immediate: true }
);
</script>

<style lang="scss" scoped>
.layout-container {
	width: 100%;
	// height: 1016px;
	background: rgba(249, 250, 252, 1);
	position: relative;

	// margin: 0 auto;
	.layout-main {
		width: 100%;
		height: 100vh;
		overflow-y: auto;
		overflow-x: hidden;

		.layout-main-center {
			width: 1600px;
			max-width: 100%;
			margin: 0 auto;
		}
	}
}
</style>