<script lang="ts">
function formatMemu(list: RouteType[], path: string = ''): ItemType[] {
  return list.filter((i) => i.isMenu).map((item) => {
    const key = item.path.startsWith('/') ? item.path : `${path}/${item.path}`;
    return {
      key,
      icon: item.icon,
      children: item.children.length ? formatMemu(item.children, key) : void 0,
      label: item.meta.title || '-',
    };
  });
}
</script>

<script setup lang="ts">
import type { ItemType } from 'ant-design-vue';
import routeList, { type RouteType } from '@/router/routes';
import { computed, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const selectedKeys = ref<string[]>(['1']);
const openKeys = ref<string[]>(['sub1']);
const menuList = computed(() => formatMemu(routeList[0].children));

const route = useRoute();
const router = useRouter();

watch(() => route.path, (val) => {
  if (!selectedKeys.value.includes(val)) {
    selectedKeys.value = [val];
    openKeys.value = route.matched.slice(1).map((i) => i.path);
  }
}, { immediate: true });

const handleClick = (config: { key: string }) => {
  router.push(config.key);
};

</script>

<template>
  <a-menu
    v-model:openKeys="openKeys"
    v-model:selectedKeys="selectedKeys"
    mode="inline"
    :items="menuList"
    class="sider-root"
    @click="handleClick"
    v-bind="$attrs"
  ></a-menu>
</template>

<style lang="less" scoped>
.sider-root {
  flex-grow: 1;
  overflow-y: auto;
  border-inline-end: none !important;
}
</style>
