<!-- layout/components/Sidebar/index.vue -->
<template>
  <div class="sidebar-container" :class="{ collapsed: isCollapse }">
    <el-menu
      :default-active="activeMenu"
      :collapse="isCollapse"
      background-color="#ffffff"
      text-color="#606266"
      active-text-color="#409eff"
      :collapse-transition="false"
      unique-opened
      class="sidebar-menu"
    >
      <template v-for="item in menuList" :key="item.path">
        <!-- 有子菜单的项 -->
        <el-sub-menu
          v-if="item.children && item.children.length > 0"
          :index="getFullPath(item.path)"
        >
          <template #title>
            <svg-icon v-if="item.meta?.icon" :icon-class="item.meta.icon" />
            <span>{{ item.meta?.title }}</span>
          </template>
          <!-- 二级菜单 -->
          <template v-for="child in item.children" :key="child.path">
            <el-sub-menu
              v-if="child.children && child.children.length > 0"
              :index="getFullPath(child.path, item.path)"
            >
              <template #title>
                <svg-icon
                  v-if="child.meta?.icon"
                  :icon-class="child.meta.icon"
                />
                <span>{{ child.meta?.title }}</span>
              </template>
              <!-- 三级菜单 -->
              <el-menu-item
                v-for="subChild in child.children"
                :key="subChild.path"
                :index="getFullPath(subChild.path, child.path, item.path)"
                @click="handleMenuClick(subChild, child, item)"
              >
                <svg-icon
                  v-if="subChild.meta?.icon"
                  :icon-class="subChild.meta.icon"
                />
                <span>{{ subChild.meta?.title }}</span>
              </el-menu-item>
            </el-sub-menu>
            <!-- 二级菜单（无子菜单） -->
            <el-menu-item
              v-else
              :index="getFullPath(child.path, item.path)"
              @click="handleMenuClick(child, item)"
            >
              <svg-icon v-if="child.meta?.icon" :icon-class="child.meta.icon" />
              <span>{{ child.meta?.title }}</span>
            </el-menu-item>
          </template>
        </el-sub-menu>

        <!-- 没有子菜单的一级菜单项 -->
        <el-menu-item
          v-else
          :index="getFullPath(item.path)"
          @click="handleMenuClick(item)"
        >
          <svg-icon v-if="item.meta?.icon" :icon-class="item.meta.icon" />
          <span>{{ item.meta?.title }}</span>
        </el-menu-item>
      </template>
    </el-menu>

    <div class="collapse-btn" @click="toggleCollapse">
      <span class="btn-text">{{ isCollapse ? "▶" : "◀" }}</span>
    </div>
  </div>
</template>

<script>
import { computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import useAppStore from "@/store/modules/app";
import usePermissionStore from "@/store/modules/permission";

export default {
  name: "Sidebar",
  props: {
    topMenuKey: {
      type: String,
      default: "",
    },
  },
  setup(props) {
    const route = useRoute();
    const router = useRouter();
    const appStore = useAppStore();
    const permissionStore = usePermissionStore();

    const isCollapse = computed(() => appStore.sidebar.isCollapse);

    // 当前激活的菜单
    const activeMenu = computed(() => {
      return route.path;
    });

    // 获取菜单列表
    const menuList = computed(() => {
      const routes = permissionStore.sidebarRouters || [];
      console.log('[Sidebar] sidebarRouters:', routes.length, routes);
      console.log('[Sidebar] topMenuKey:', props.topMenuKey, typeof props.topMenuKey);
      console.log('[Sidebar] route.path:', route.path);

      if (!routes.length) return [];

      // 1. 尝试按topMenuKey匹配（仅当topMenuKey是字符串且匹配到路由时）
      if (props.topMenuKey && typeof props.topMenuKey === 'string' && props.topMenuKey.startsWith('/')) {
        const current = routes.find((item) => item.path === props.topMenuKey);
        if (current && current.children) {
          console.log('[Sidebar] matched by topMenuKey:', current.path);
          return current.children.filter((child) => !child.hidden);
        }
      }

      // 2. 找当前路由所在的第一级父路由，返回其子菜单
      const currentSegs = route.path.split("/").filter(Boolean);
      if (currentSegs.length > 0) {
        const firstLevel = "/" + currentSegs[0];
        console.log('[Sidebar] looking for firstLevel:', firstLevel);
        const parentRoute = routes.find((r) => r.path === firstLevel);
        if (parentRoute && parentRoute.children) {
          console.log('[Sidebar] found parentRoute:', parentRoute.path, 'children:', parentRoute.children.length);
          return parentRoute.children.filter((child) => !child.hidden);
        } else {
          console.log('[Sidebar] no parentRoute found for:', firstLevel, 'available paths:', routes.map(r => r.path));
        }
      }

      // 3. 兜底：返回第一个有子菜单的路由
      for (const r of routes) {
        if (r.children && r.children.length) {
          console.log('[Sidebar] fallback route:', r.path);
          return r.children.filter((child) => !child.hidden);
        }
      }

      return [];
    });

    // 基准路径：以当前顶层菜单为基础，保证首页点击菜单时路径正确
    const basePath = computed(() => {
      if (props.topMenuKey && props.topMenuKey.startsWith('/')) {
        return props.topMenuKey;
      }
      const segs = route.path.split("/").filter(Boolean);
      return segs.length > 0 ? "/" + segs[0] : "";
    });

    // 获取完整路径
    const getFullPath = (path, parentPath = "", grandParentPath = "") => {
      if (path.startsWith("/")) {
        return path;
      }

      // 三级菜单
      if (grandParentPath && parentPath) {
        return basePath.value + "/" + grandParentPath + "/" + parentPath + "/" + path;
      }

      // 二级菜单
      if (parentPath) {
        return basePath.value + "/" + parentPath + "/" + path;
      }

      // 一级菜单
      return basePath.value + "/" + path;
    };

    // 点击菜单
    const handleMenuClick = (
      item,
      parentItem = null,
      grandParentItem = null,
    ) => {
      let fullPath = "";

      if (grandParentItem && parentItem) {
        fullPath =
          basePath.value +
          "/" +
          grandParentItem.path +
          "/" +
          parentItem.path +
          "/" +
          item.path;
      } else if (parentItem) {
        fullPath = basePath.value + "/" + parentItem.path + "/" + item.path;
      } else {
        fullPath = basePath.value + "/" + item.path;
      }

      router.push(fullPath);
    };

    // 收起/展开
    const toggleCollapse = () => {
      appStore.sidebar.isCollapse = !appStore.sidebar.isCollapse;
    };

    return {
      menuList,
      isCollapse,
      activeMenu,
      getFullPath,
      handleMenuClick,
      toggleCollapse,
    };
  },
};
</script>

<style scoped>
.sidebar-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  border-right: 1px solid #e4e7ed;
}

.sidebar-menu {
  flex: 1;
  border: none;
  overflow-y: auto;
  overflow-x: hidden;
}

:deep(.el-menu) {
  border-right: none;
  background-color: #ffffff;
}

:deep(.el-sub-menu__title) {
  color: #606266;
  background-color: #ffffff;
}

:deep(.el-sub-menu__title:hover) {
  background-color: #f5f7fa !important;
  color: #303133 !important;
}

:deep(.el-menu-item) {
  color: #606266;
  background-color: #ffffff;
}

:deep(.el-menu-item:hover) {
  background-color: #f5f7fa !important;
  color: #303133 !important;
}

:deep(.el-menu-item.is-active) {
  background-color: #ecf5ff !important;
  color: #409eff !important;
}

.sidebar-container.collapsed :deep(.el-sub-menu__title span) {
  display: none;
}

.sidebar-container.collapsed :deep(.el-menu-item span) {
  display: none;
}

.collapse-btn {
  height: 44px;
  line-height: 44px;
  text-align: center;
  color: #606266;
  cursor: pointer;
  border-top: 1px solid #e4e7ed;
  background-color: #ffffff;
}

.collapse-btn:hover {
  background-color: #f5f7fa;
  color: #303133;
}

.btn-text {
  font-size: 16px;
}
</style>
