<template>
  <n-layout-sider
    bordered
    collapse-mode="width"
    show-trigger="bar"
    :native-scrollbar="false"
    :collapsed-width="60"
    :width="200"
    @collapse="true"
    @expand="false"
  >
    <div class="sider-flex">
      <aside>
        <n-space vertical class="sider-top"> 中盛起元基础框架 </n-space>
        <n-menu
          :options="generatorMenu(asyncRoutes)"
          :collapsed-width="60"
          :collapsed-icon-size="22"
          :expanded-keys="state.openKeys"
          :value="currentRoute.meta?.activeMenu"
          @update:value="clickMenuItem"
          @update:expanded-keys="menuExpanded"
        />
      </aside>
    </div>
  </n-layout-sider>
</template>

<script setup lang="ts">
import { useRoute } from "vue-router";
import { asyncRoutes } from "@/router";
import { routerTurnByName, generatorMenu } from "@/utils";
// 当前路由
const currentRoute = useRoute();
// 获取当前打开的子菜单
const matched = currentRoute.matched;
const getOpenKeys =
  matched && matched.length ? matched.map((item) => item.name) : [];

const state = reactive({
  openKeys: getOpenKeys,
});

const clickMenuItem = (key: string) => {
  routerTurnByName(key);
};

//展开菜单
function menuExpanded(openKeys: string[]) {
  if (!openKeys) return;
  const latestOpenKey = openKeys.find(
    (key) => state.openKeys.indexOf(key) === -1
  );
  const isExistChildren = findChildrenLen(latestOpenKey as string);
  state.openKeys = isExistChildren
    ? latestOpenKey
      ? [latestOpenKey]
      : []
    : openKeys;
}

//查找是否存在子路由
function findChildrenLen(key: string) {
  if (!key) return false;
  const subRouteChildren: string[] = [];
  const menus = generatorMenu(asyncRoutes);
  for (const { children, key } of unref(menus)) {
    if (children && children.length) {
      subRouteChildren.push(key as string);
    }
  }
  return subRouteChildren.includes(key);
}

// onMounted(() => {});
</script>

<style lang="scss" scoped>
.sider-top {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  margin-top: 10px;
  // margin-bottom: 20px;
}
</style>
