<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="menus"
          :collapsed-width="64"
          :collapsed-icon-size="20"
          :indent="24"
          :expanded-keys="state.openKeys"
          :value="getSelectedKeys"
          @update:value="clickMenuItem"
          @update:expanded-keys="menuExpanded"
        />
      </aside>
    </div>
  </n-layout-sider>
</template>

<script setup lang="ts">
import { useRoute } from "vue-router";
import { routerTurnByName, generatorMenu } from "@/utils";
import { useAsyncRouteStore } from "@/store/modules/asyncRoute";

// 当前路由
const currentRoute = useRoute();
// 获取当前打开的子菜单
const matched = currentRoute.matched;
const getOpenKeys =
  matched && matched.length ? matched.map((item) => item.name) : [];

const asyncRouteStore = useAsyncRouteStore();
const menus = ref<any[]>([]);
const selectedKeys = ref<string>(currentRoute.name as string);

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

// 跟随页面路由变化，切换菜单选中状态
watch(
  () => currentRoute.fullPath,
  () => {
    console.log(123);
    updateMenu();
  }
);

function updateSelectedKeys() {
  const matched = currentRoute.matched;
  state.openKeys = matched.map((item) => item.name);
  const activeMenu: string = (currentRoute.meta?.activeMenu as string) || "";
  selectedKeys.value = activeMenu
    ? (activeMenu as string)
    : (currentRoute.name as string);

  console.log(selectedKeys.value);
}

function updateMenu() {
  menus.value = generatorMenu(asyncRouteStore.getMenus);
  updateSelectedKeys();
}

const getSelectedKeys = computed(() => {
  return unref(selectedKeys);
});

const clickMenuItem = (key: string) => {
  if (/http(s)?:/.test(key)) {
    window.open(key);
  } else {
    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[] = [];
  for (const { children, key } of unref(menus)) {
    if (children && children.length) {
      subRouteChildren.push(key as string);
    }
  }
  return subRouteChildren.includes(key);
}

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

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