<!-- layout/components/Sidebar/index.vue -->
<template>
  <div class="sidebar-container" :class="{ collapsed: isCollapse, empty: !menuList.length }">
    <el-menu
      v-if="menuList.length > 0"
      :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._fullPath">
        <!-- 有子菜单的项 -->
        <el-sub-menu
          v-if="item.children && item.children.length > 0"
          :index="item._fullPath"
        >
          <template #title>
            <svg-icon v-if="item.meta?.icon" :icon-class="item.meta.icon" />
            <span>{{ item.meta?.title }}</span>
          </template>
          <el-menu-item
            v-for="child in item.children"
            :key="child._fullPath"
            :index="child._fullPath"
            @click="handleMenuClick(child)"
          >
            <svg-icon v-if="child.meta?.icon" :icon-class="child.meta.icon" />
            <span>{{ child.meta?.title }}</span>
          </el-menu-item>
        </el-sub-menu>

        <!-- 没有子菜单的一级菜单项 -->
        <el-menu-item
          v-else
          :index="item._fullPath"
          @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;
    });

    // 给路由添加完整路径标记
    function enrichWithFullPath(routes, basePath) {
      return routes.map((item) => {
        const itemPath = item.path || "";
        // 如果子项路径已经包含斜杠（绝对路径），直接使用；否则拼接
        const fullPath = itemPath.startsWith("/")
          ? itemPath
          : basePath
          ? basePath + "/" + itemPath
          : "/" + itemPath;
        const enriched = { ...item, _fullPath: fullPath };
        if (item.children && item.children.length > 0) {
          enriched.children = enrichWithFullPath(item.children, fullPath);
        }
        return enriched;
      });
    }

    // 获取菜单列表
    const menuList = computed(() => {
      const allRoutes = permissionStore.sidebarRouters || [];
      if (!allRoutes.length) return [];

      // 归一化路径：去掉前导斜杠用于比较
      const normalize = (p) => (p || "").replace(/^\//, "");

      // 1. 按 topMenuKey 匹配
      if (props.topMenuKey) {
        const normKey = normalize(props.topMenuKey);
        const found = allRoutes.find(
          (r) => normalize(r.path) === normKey
        );
        if (found && found.children) {
          const items = found.children.filter((c) => !c.hidden);
          return enrichWithFullPath(items, "/" + normKey);
        }
      }

      // 2. 按当前路由第一级路径匹配
      const segs = route.path.split("/").filter(Boolean);
      if (segs.length > 0) {
        const firstSeg = segs[0];
        const found = allRoutes.find(
          (r) => normalize(r.path) === firstSeg
        );
        if (found && found.children) {
          const items = found.children.filter((c) => !c.hidden);
          return enrichWithFullPath(items, "/" + firstSeg);
        }
      }

      // 3. 兜底：返回第一个有子菜单的路由
      for (const r of allRoutes) {
        if (r.children && r.children.length) {
          const items = r.children.filter((c) => !c.hidden);
          return enrichWithFullPath(items, "/" + normalize(r.path));
        }
      }

      return [];
    });

    // 点击菜单（支持 query 参数）
    const handleMenuClick = (item) => {
      if (typeof item === "string") {
        router.push(item);
        return;
      }
      const fullPath = item._fullPath || item.path;
      if (item.query) {
        try {
          const query = JSON.parse(item.query);
          router.push({ path: fullPath, query });
          return;
        } catch (e) {
          // query 解析失败则直接跳转
        }
      }
      router.push(fullPath);
    };

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

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

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

.sidebar-container.empty {
  display: none;
}

.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>
