<template>
	<div class="module-header-wrapper">
		<div class="nav-content">
			<div class="nav-left" :class="{ 'flex-start': isShowSearchBar }">
				<div class="icon">
					<img v-show="!isShowSearchBar" src="@/assets/icons/overview/logo.png" alt="" />
					<img v-show="isShowSearchBar" src="@/assets/icons/overview/logo-white.png" alt="" />
				</div>
				<SearchBar v-show="isShowSearchBar" />
				<div class="title-box" v-show="!isShowSearchBar">
					<!-- <div class="title-box" v-if="false"> -->
					<div class="title" v-for="(item, index) in homeTitleList" :key="index"
						@mouseenter="handleShowMenu(index, true)" @click="handleClickTitle(item, index)">
						<div class="text text-title-1-show" :class="{ textActive: homeActiveTitleIndex === index }">
							{{ item.name }}
						</div>
						<div class="bottom-line" v-if="homeActiveTitleIndex === index"></div>
					</div>
				</div>
			</div>

			<div class="nav-right">
				<div class="info-box">
					<div class="mail" @click="handleClickToolBox">
						<img src="@/assets/icons/overview/mail.png" alt="" />
					</div>
					<div class="user-trigger">
						<div class="user" @click.stop="handleToggleUserPanel">
							<img src="@/assets/icons/overview/user.png" alt="" />
						</div>
					</div>
					<div v-if="isShowUserPanel" class="user-panel">

						<div class="user-panel-row">
							<div class="blue-solid"></div>
							<span class="user-panel-value user-panel-value--nickname">{{ userNickname }}</span>
							<div class="role-box">
								<span class="user-panel-value user-panel-value--role">{{ roleName }}</span>
							</div>
						</div>


						<div class="user-panel-row user-panel-row--single">
							<span class="user-panel-value user-panel-value--organ">{{ organName }}</span>
						</div>
						<div class="solid"></div>



						<div class="user-panel-logout" @click.stop="handleUserCommand('logout')"><img src="./back.png"
								class="back-image" />{{ "退出登录" }}
						</div>
					</div>
				</div>
			</div>
			<div class="menu-box" v-show="isShowMenu" @mouseenter="handleHoverMenu(true)"
				@mouseleave="handleHoverMenu(false)">
				<div class="menu-content">
					<div class="menu-item" v-for="(item, index) in menuList" :key="index" @click="handleToModule(item, 1)">
						<div class="icon">
							<img :src="item.icon" alt="" />
						</div>
						<div class="title" :class="{ 'active-title': item.active }">{{ item.title }}</div>
					</div>
				</div>
			</div>
			<div class="tool-box" v-show="isShowTool" @mouseenter="handleHoverTool(true)"
				@mouseleave="handleHoverTool(false)">
				<div class="menu-content">
					<div class="menu-item" v-for="(item, index) in toolList" :key="index" @click="handleToModule(item, 2)">
						<div class="icon">
							<img :src="item.icon" alt="" />
						</div>
						<div class="title">{{ item.title }}</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, watchEffect, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { useRoute } from "vue-router";
import { getPersonType } from "@/api/common/index";
import request, { removeToken } from "@/api/request.js";
import { broadcastAuthLogout } from "@/utils/authCrossTabLogout.js";
import SearchBar from "@/components/layout/SearchBar.vue";

import Menu1 from "@/assets/icons/overview/menu1.png";
import Menu2 from "@/assets/icons/overview/menu2.png";
import Menu3 from "@/assets/icons/overview/menu3.png";
import Menu4 from "@/assets/icons/overview/menu4.png";
import Menu5 from "@/assets/icons/overview/menu5.png";
import Menu6 from "@/assets/icons/overview/menu6.png";
import Menu7 from "@/assets/icons/overview/menu7.png";
import Menu8 from "@/assets/icons/overview/menu8.png";
import Menu9 from "@/assets/icons/overview/menu9.png";
import Menu10 from "@/assets/icons/overview/menu10.png";
import Menu11 from "@/assets/icons/overview/menu11.png";
import Menu12 from "@/assets/icons/overview/menu12.png";
import Tool1 from './tool1.svg'
import Tool2 from './tool2.svg'
import { ElMessage } from "element-plus";
import { useWrittingAsstaintStore } from "@/stores/writtingAsstaintStore";
const store = useWrittingAsstaintStore();
let isShowSearchBar = computed(() => {
	return store.isShowSearchBar;
});
const router = useRouter();
const route = useRoute()

const personTypeList = ref([]);
const ssoUserInfo = ref(null);
const isShowUserPanel = ref(false);

// 用户面板展示兜底：接口无数据时不显示 "-"，改为默认文案
const userNickname = computed(() => ssoUserInfo.value?.userInfo?.userNickname || "管理员");
const organName = computed(() => ssoUserInfo.value?.organInfo?.organName || "开发部门");
const roleName = computed(() => {
	const roles = ssoUserInfo.value?.roles;
	return Array.isArray(roles) && roles.length ? (roles[0]?.roleName || "系统管理员") : "系统管理员";
});

// 获取人物类别
const handleGetPersonType = async () => {
	try {
		const res = await getPersonType();
		console.log("res", res);
		if (res.code === 200) {
			personTypeList.value = res.data;
		} else {
			personTypeList.value = [];
		}
		window.sessionStorage.setItem("personTypeList", JSON.stringify(personTypeList.value));
	} catch (error) { }
};

// 获取当前登录用户信息（不展示，仅缓存；Authorization 由全局 request 拦截器自动注入）
const handleGetSsoUserInfo = async () => {
	try {
		const res = await request({
			method: "GET",
			// 通过 Vite 代理：/api -> 172.19.21.228:28080（rewrite 去掉 /api，后端收到 /sso/user/info）
			url: "/api/sso/user/info"
		});
		ssoUserInfo.value = res?.data ?? null;
		console.log("用户信息", ssoUserInfo.value);
	} catch {
		ssoUserInfo.value = null;
	}
};

// 概览页标题列表
const homeTitleList = ref([

	{
		name: "首页",
		path: "/ZMOverView",
		disabled: false
	},

	{
		name: "中美科技博弈",
		path: "/billHome",
		disabled: false
	},
	{
		name: "智能工具",
		path: "/chat",
		disabled: false
	},
	{
		name: "数据资源库",
		path: "/dataLibrary",
		disabled: false
	}
]);

const homeActiveTitleIndex = computed(() => {
	let activeIndex = 1
	if (route.fullPath.includes('/ZMOverView')) {
		activeIndex = 0
	} else if (route.fullPath.includes('/dataLibrary')) {
		activeIndex = 3
	} else if (route.fullPath.includes('/chat') || route.fullPath.includes('/writtingAsstaint')) {
		activeIndex = 2
	} else {
		activeIndex = 1
	}
	return activeIndex
})

const isShowMenu = ref(false);
const handleShowMenu = (index, isShow) => {
	if (index === 1) {
		isShowMenu.value = isShow;
		isShowTool.value = false;
	} else if (index === 2) {
		isShowMenu.value = false
		isShowTool.value = isShow;
	} else {
		isShowMenu.value = false
		isShowTool.value = false;
	}
};

const handleHoverMenu = isShow => {
	isShowMenu.value = isShow;
};

const menuList = computed(() => {
	let menu = [
		// {
		// 	title: "中美科技博弈概览",
		// 	icon: Menu1,
		// 	path: "/ZMOverView"
		// },
		{
			title: "科技法案",
			icon: Menu2,
			path: "/billHome",
			active: false
		},
		{
			title: "科技政令",
			icon: Menu3,
			path: "/decree",
			active: false
		},
		{
			title: "美国科技智库",
			icon: Menu4,
			path: "/thinkTank",
			active: false
		},
		{
			title: "出口管制",
			icon: Menu5,
			path: "/exportControl",
			active: false
		},
		{
			title: "科研合作限制",
			icon: Menu6,
			path: "/cooperationRestrictions",
			active: false
		},
		{
			title: "投融资限制",
			icon: Menu7,
			path: "/finance",
			active: false
		},
		{
			title: "市场准入限制",
			icon: Menu8,
			path: "/marketAccessRestrictions",
			active: false
		},
		{
			title: "规则限制",
			icon: Menu9,
			path: "/ruleRestrictions",
			active: false
		},
		{
			title: "美国科技人物观点",
			icon: Menu10,
			path: "/technologyFigures",
			active: false
		},
		{
			title: "美国主要创新主体动向",
			icon: Menu11,
			path: "/innovationSubject",
			active: false
		},
		{
			title: "美国科研资助体系",
			icon: Menu12,
			path: "/scientificFunding",
			active: false
		}
	]
	switch (route.fullPath) {
		case '/billHome':
			menu.forEach(item => {
				item.active = false
			})
			menu[0].active = true
			break
		case '/decree':
			menu.forEach(item => {
				item.active = false
			})
			menu[1].active = true
			break
		case '/thinkTank':
			menu.forEach(item => {
				item.active = false
			})
			menu[2].active = true
			break
		case '/exportControl':
			menu.forEach(item => {
				item.active = false
			})
			menu[3].active = true
			break
		case '/cooperationRestrictions':
			menu.forEach(item => {
				item.active = false
			})
			menu[4].active = true
			break
		case '/finance':
			menu.forEach(item => {
				item.active = false
			})
			menu[5].active = true
			break
		case '/marketAccessRestrictions':
			menu.forEach(item => {
				item.active = false
			})
			menu[6].active = true
			break
		case '/ruleRestrictions':
			menu.forEach(item => {
				item.active = false
			})
			menu[7].active = true
			break
		case '/technologyFigures':
			menu.forEach(item => {
				item.active = false
			})
			menu[8].active = true
			break
		case '/innovationSubject':
			menu.forEach(item => {
				item.active = false
			})
			menu[9].active = true
			break
		case '/scientificFunding':
			menu.forEach(item => {
				item.active = false
			})
			menu[10].active = true
			break
	}
	return menu
})

const isShowTool = ref(false);

const handleHoverTool = isShow => {
	isShowTool.value = isShow;
};


const toolList = ref([
	{
		title: "智能问答",
		icon: Tool1,
		path: "/chat"
	},
	{
		title: "智能写报",
		icon: Tool2,
		path: "/writtingAsstaint"
	},
])

const handleToModule = (item, index) => {
	if (index === 1) {
		router.push({
			path: item.path
		})
	} else {
		const curRoute = router.resolve({
			path: item.path,
			query: {
				titleIndex: 2
			}
		});
		window.open(curRoute.href, "_blank");
	}

	isShowMenu.value = false
	isShowTool.value = false
};

const handleClickTitle = (item, index) => {
	if (index === 0 || index === 3) {
		router.push(item.path)
	}
};

const handleClickToolBox = () => {
	ElMessage.warning("当前功能正在开发中，敬请期待！");
};

const handleToggleUserPanel = () => {
	isShowUserPanel.value = !isShowUserPanel.value;
};

const handleHideUserPanel = () => {
	isShowUserPanel.value = false;
};

const handleUserCommand = async (command) => {
	if (command === "logout") {
		isShowUserPanel.value = false;
		// ===== 退出登录（外部重定向版，切线上接口时先注释保留） =====
		// const ssoOrigin = import.meta.env.VITE_SSO_GATEWAY_ORIGIN || "http://172.19.21.228:28080";
		// try {
		// 	// 走后端登出接口，返回统一登出页地址（能清 SSO Cookie，确保下次必须重新登录）
		// 	const res = await request({
		// 		method: "POST",
		// 		// 通过 Vite 代理：/api -> 172.19.21.228:28080（rewrite 去掉 /api，后端收到 /sso/logout）
		// 		url: "/api/sso/logout"
		// 	});
		//
		// 	// 无论成功失败，都清掉本地 token（确保后续请求不再带 Authorization）
		// 	removeToken();
		// 	try {
		// 		window.localStorage.removeItem("auth_token");
		// 	} catch {
		// 		// ignore
		// 	}
		// 	try {
		// 		window.sessionStorage.removeItem("auth_token");
		// 	} catch {
		// 		// ignore
		// 	}
		// 	try {
		// 		window.sessionStorage.setItem("force_sso_login", "1");
		// 	} catch {
		// 		// ignore
		// 	}
		//
		// 	const redirectUrl = res && typeof res.data === "string" ? res.data : "";
		// 	window.location.replace(redirectUrl || `${ssoOrigin}/api/v2`);
		// } catch (e) {
		// 	// 兜底：清本地并跳网关
		// 	removeToken();
		// 	try {
		// 		window.localStorage.removeItem("auth_token");
		// 	} catch {
		// 		// ignore
		// 	}
		// 	try {
		// 		window.sessionStorage.removeItem("auth_token");
		// 	} catch {
		// 		// ignore
		// 	}
		// 	try {
		// 		window.sessionStorage.setItem("force_sso_login", "1");
		// 	} catch {
		// 		// ignore
		// 	}
		// 	window.location.replace(`${ssoOrigin}/api/v2`);
		// }

		// ===== 退出登录（站内 login 版：清 token 后进入 /login） =====
		removeToken();
		try {
			window.localStorage.removeItem("auth_token");
		} catch {
			// ignore
		}
		// 退出后强制所有页面回到登录页（跨标签页/刷新生效）
		try {
			window.localStorage.setItem("force_login", "1");
		} catch {
			// ignore
		}
		broadcastAuthLogout();
		try {
			window.sessionStorage.removeItem("auth_token");
		} catch {
			// ignore
		}
		router.replace("/login");
	}
};

onMounted(() => {
	handleGetPersonType();
	handleGetSsoUserInfo();
});

</script>

<style lang="scss" scoped>
.module-header-wrapper {
	width: 100%;
	position: relative;
	z-index: 101;
	border-bottom: 1px solid rgba(234, 236, 238, 1);
	box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
	background: linear-gradient(180deg, rgba(246, 250, 255, 0.8) 0%, rgba(255, 255, 255, 0.8) 100%);
	padding: 12px 0;

	.nav-content {
		width: 1600px;
		margin: 0 auto;
		display: flex;
		justify-content: space-between;
		position: relative;
		align-items: flex-start;

		.nav-left {
			display: flex;
			align-items: center;

			&.flex-start {
				align-items: flex-start;

				.icon {
					flex-shrink: 0;
					width: 48px;
					height: 48px;
					border-radius: 50%;
					background: rgb(5, 95, 194);
					display: flex;
					align-items: center;
					justify-content: center;

					img {
						width: 29px;
						height: 30px;
					}
				}
			}

			.icon {
				width: 29px;
				height: 30px;
				margin-right: 17px;

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

			.title-box {
				display: flex;
				gap: 30px;

				.title {
					cursor: pointer;
					position: relative;

					&:hover {
						.text {
							color: var(--color-main-active);
						}
					}

					.text {
						color: var(--text-primary-80-color);
					}

					.textActive {
						color: var(--color-main-active);
					}

					.bottom-line {
						position: absolute;
						bottom: -15px;
						width: 90%;
						height: 20px;
						margin-top: 9px;

						&::after {
							display: block;
							content: "";
							width: 50%;
							height: 4px;
							background: var(--color-main-active);
							position: absolute;
							bottom: 2px;
							left: 0;
							right: 0;
							margin: 0 auto;
						}
					}
				}
			}
		}

		.nav-right {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			gap: 21px;

			.info-box {
				height: 40px;
				display: flex;
				justify-content: flex-end;
				align-items: center;
				position: relative;


				.mail {
					width: 32px;
					height: 32px;
					margin-right: 14px;
					cursor: pointer;

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

				.user {
					width: 32px;
					height: 32px;
					margin-right: 11px;
					cursor: pointer;

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

				.name {
					width: 48px;
					height: 30px;
					color: var(--text-primary-80-color);
				}

				.user-trigger {
					display: flex;
					align-items: center;
					cursor: pointer;
				}

				.user-panel {
					position: absolute;

					right: 0;
					top: calc(32px + 21px);
					width: 240px;
					height: 141px;
					background: rgba(255, 255, 255, 0.8);
					border: 1px solid rgba(255, 255, 255, 1);
					border-radius: 10px;

					box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
					display: flex;
					flex-direction: column;

					// 高度固定 141px，需要把内容控制在容器内，避免分割线被裁剪
					padding: 16px 15px 12px 24px;
					box-sizing: border-box;
					overflow: hidden;
					z-index: 999999;
				}

				.user-panel-row {
					display: flex;
					align-items: center;
					justify-content: space-between;
					flex-direction: row;
					gap: 12px;
					position: relative;
					padding-right: 3px;
				}

				.user-panel-row--single {
					justify-content: flex-start;
				}

				.blue-solid {
					position: absolute;
					left: -24px;
					width: 4px;
					height: 48px;
					background: rgb(5, 95, 194);
					top: 0;

				}

				.solid {
					width: 206px;
					height: 1px;
					background: rgb(234, 236, 238);
					margin-top: 13px;
				}

				.user-panel-label {
					color: rgba(59, 65, 75, 0.8);
					font-size: 14px;
					line-height: 20px;
					flex-shrink: 0;
				}

				.user-panel-value {
					font-family: "Source Han Sans CN";
					font-weight: 400;
					font-size: 14px;
					line-height: 22px;
					letter-spacing: 0px;
					text-align: left;

					text-overflow: ellipsis;
					white-space: nowrap;


				}

				.user-panel-value--nickname {
					font-family: "Source Han Sans CN";
					font-weight: 700;
					font-size: 18px;
					line-height: 24px;
					letter-spacing: 0px;
					text-align: left;
					color: rgb(59, 65, 75);
					margin-left: 8px;
				}

				.role-box {

					padding: 0px 8px;
					background-color: rgb(231, 243, 255);
					display: flex;
					border-radius: 4px;
				}

				.user-panel-value--role {
					font-family: "Source Han Sans CN";
					font-weight: 400;
					font-size: 14px;
					line-height: 22px;
					letter-spacing: 0px;
					text-align: justify;
					color: rgb(5, 95, 194);

				}

				.user-panel-value--organ {
					font-family: "Source Han Sans CN";
					font-weight: 400;
					font-size: 14px;
					line-height: 22px;
					letter-spacing: 0px;
					text-align: left;
					color: rgb(95, 101, 108);
					margin-top: 4px;
					margin-left: 8px;
				}

				.user-panel-logout {
					font-family: "Source Han Sans CN";
					font-weight: 400;
					font-size: 16px;
					line-height: 24px;
					letter-spacing: 0px;
					text-align: justify;
					color: rgb(59, 65, 75);
					cursor: pointer;
					height: 24px;
					margin-top: 12px;
					display: flex;
					align-items: center;
					margin-left: 8px;

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

						margin-right: 12px;

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


					}
				}
			}
		}

		.menu-box {
			// position: absolute;
			// z-index: 999999999;
			// width: 713px;
			// height: 413px;
			// top: 52px;
			// left: 0;
			// box-sizing: border-box;
			// border-radius: 10px;
			// backdrop-filter: blur(10px);
			// -webkit-backdrop-filter: blur(10px);
			// box-shadow: 0px 8px 32px 0px rgba(31, 38, 135, 0.15);
			// background: rgba(255, 255, 255, 0.25);
			// backdrop-filter: blur(10px);
			// -webkit-backdrop-filter: blur(10px);
			// border: 1px solid rgba(255, 255, 255, 0.3);
			// background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0.2) 100%);
			// box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.2);
			position: absolute;
			z-index: 999999;
			width: 713px;
			height: 413px;
			top: 52px;
			left: -2px;
			box-sizing: border-box;
			border: 1px solid rgba(255, 255, 255, 1);
			border-radius: 10px;
			backdrop-filter: blur(30px);
			box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
			background: rgba(255, 255, 255, 0.8);

			.menu-content {
				width: 562px;
				height: 348px;
				margin-top: 8px;
				margin-left: 72px;
				display: flex;
				flex-wrap: wrap;

				.menu-item {
					margin-top: 36px;
					width: 280px;
					height: 24px;
					display: flex;
					cursor: pointer;

					&:hover {
						.title {
							color: var(--color-main-active);
							font-size: 20px;
						}
					}

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

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

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

					.active-title {
						color: var(--color-main-active) !important;
						font-size: 20px !important;
					}
				}
			}
		}

		.tool-box {
			position: absolute;
			z-index: 999999;
			width: 273px;
			height: 171px;
			top: 52px;
			left: 300px;
			box-sizing: border-box;
			border: 1px solid rgba(255, 255, 255, 1);
			border-radius: 10px;
			backdrop-filter: blur(30px);
			box-shadow: 0px 0px 20px 0px rgba(25, 69, 130, 0.1);
			background: rgba(255, 255, 255, 0.8);

			.menu-content {
				width: 562px;
				height: 348px;
				margin-top: 8px;
				margin-left: 72px;

				.menu-item {
					margin-top: 36px;
					width: 280px;
					height: 24px;
					display: flex;
					cursor: pointer;



					&:hover {
						.title {
							color: var(--color-main-active);
							font-size: 20px;
						}
					}

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

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

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

					.active-title {
						color: var(--color-main-active) !important;
						font-size: 20px !important;
					}
				}
			}
		}
	}
}
</style>
