<!-- layout/index.vue -->
<template>
  <div
    class="app-wrapper"
    :style="{
      '--current-color': theme,
      '--current-color-light': theme + '1a',
      '--current-color-dark-bg': theme + '33',
    }"
  >
    <!-- 顶部一级菜单栏 -->
    <top-navbar
      v-if="!sidebar.hide"
      :active-menu="activeTopMenu"
      @menu-click="handleTopMenuClick"
      @setLayout="openSettings"
    />

    <!-- 下方区域：左右结构 -->
    <div class="main-layout">
      <!-- 左侧二三级菜单（页面内部面板的模块隐藏系统导航） -->
      <div class="sidebar-wrapper" :class="{ collapsed: isCollapse, hidden: !showSystemSidebar }">
        <sidebar v-if="!sidebar.hide && showSystemSidebar" :top-menu-key="activeTopMenu" />
      </div>

      <!-- 右侧内容区域 -->
      <div class="content-wrapper">
        <app-main />
        <settings ref="settingRef" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, watch, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import TopNavbar from "./components/TopNavbar/index.vue";
import Sidebar from "./components/Sidebar/index.vue";
import { AppMain, Settings } from "./components";
import useAppStore from "@/store/modules/app";
import useSettingsStore from "@/store/modules/settings";
import usePermissionStore from "@/store/modules/permission";

const settingsStore = useSettingsStore();
const permissionStore = usePermissionStore();
const appStore = useAppStore();
const route = useRoute();
const router = useRouter();

// 首页路径
const HOME_PATH = "/index";
// 默认业务入口（工程基本信息 - 内部首页）
const DEFAULT_BIZ_PATH = "/proj/index";

// 计算属性
const theme = computed(() => settingsStore.theme);
const sidebar = computed(() => appStore.sidebar);
const isCollapse = computed(() => appStore.sidebar.isCollapse);

// 使用页面内部面板的顶级菜单（隐藏系统左侧导航）
const INTERNAL_PANEL_MENUS = ["/proj", "/zggc", "/gis", "/assess", "/standard", "/legal"];
const showSystemSidebar = computed(() => !INTERNAL_PANEL_MENUS.includes(activeTopMenu.value));

// 当前选中的顶级菜单
const activeTopMenu = ref("");

// 获取当前选中的顶级菜单
const getCurrentTopMenu = () => {
  const currentPath = route.path;

  // 首页统一映射到工程基本信息
  if (currentPath === HOME_PATH || currentPath === "/") {
    return "/proj";
  }

  try {
    const routes = permissionStore.topbarRouters || [];
    // 取第一段路径
    const segs = currentPath.split("/").filter(Boolean);
    if (segs.length === 0) return "/proj";
    const firstSegment = segs[0];
    // 归一化比较
    const normSeg = firstSegment.toLowerCase();
    const matched = routes.find((r) => {
      const rp = (r.path || "").replace(/^\//, "").toLowerCase();
      return rp === normSeg;
    });
    return matched ? ("/" + matched.path.replace(/^\//, "")) : "/proj";
  } catch (error) {
    return "/proj";
  }
};

// 处理顶级菜单点击
function handleTopMenuClick(menuPath) {
  activeTopMenu.value = menuPath;

  // 跳转到第一个子路由
  const routes = permissionStore.topbarRouters || [];
  // 归一化路径比较
  const normPath = (p) => (p || "").replace(/^\//, "");
  const normClick = normPath(menuPath);

  // 页面内部面板模块：固定跳转内部首页（路由在前端静态注册，不依赖后端菜单）
  const INTERNAL_HOME = { proj: "/proj/index", zggc: "/zggc/index" };
  if (INTERNAL_HOME[normClick]) {
    router.push(INTERNAL_HOME[normClick]);
    return;
  }

  const targetRoute = routes.find((r) => normPath(r.path) === normClick);
  if (targetRoute) {
    if (targetRoute.children && targetRoute.children.length > 0) {
      // 有子菜单的目录路由 → 跳转到第一个子路由（含隐藏的内部首页）
      const firstChild = targetRoute.children.find((child) => !child.hidden) || targetRoute.children[0];
      if (firstChild) {
        let childPath = firstChild.path;
        if (!childPath.startsWith("/")) {
          childPath = "/" + normClick + "/" + childPath;
        }
        if (firstChild.query) {
          try {
            router.push({ path: childPath, query: JSON.parse(firstChild.query) });
            return;
          } catch (e) {
            // query 解析失败则直接跳转
          }
        }
        router.push(childPath);
      }
    } else {
      // 叶节点路由（如直管工程）→ 直接跳转
      router.push("/" + normClick);
    }
  }
}

// 打开设置面板
const settingRef = ref(null);
function openSettings() {
  if (settingRef.value) {
    settingRef.value.openSetting();
  }
}

// 监听路由变化，更新选中的顶级菜单
watch(
  () => route.path,
  () => {
    activeTopMenu.value = getCurrentTopMenu();
  },
  { immediate: true },
);

onMounted(() => {
  // 如果当前是根路径或首页，跳转到工程基本信息-堤防管理（默认页面）
  if (route.path === "/" || route.path === HOME_PATH) {
    router.push(DEFAULT_BIZ_PATH);
  }
  activeTopMenu.value = getCurrentTopMenu();
});
</script>

<style scoped>
.app-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.main-layout {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.sidebar-wrapper {
  width: 210px;
  transition: width 0.3s;
  flex-shrink: 0;
}

/* 页面内部面板的模块（工程基本信息/直管工程）隐藏系统左侧导航 */
.sidebar-wrapper.hidden {
  width: 0;
}

/* 侧边栏无菜单时自动隐藏 */
.sidebar-wrapper:has(.sidebar-container.empty) {
  width: 0;
}

.sidebar-wrapper.collapsed {
  width: 64px;
}

.content-wrapper {
  flex: 1;
  overflow: auto;
  background: #f0f2f6;
}
</style>
