<script setup>
import {ref, watch} from 'vue'
import {useRoute} from 'vue-router'

const route = useRoute();
const menus = [
  {
    key: 'overview',
    path: '/management/overview',
    name: '概览',
  },
  {
    key: 'system',
    name: '系统管理',
    children: [
      {
        key: 'setting',
        path: '/management/setting',
        name: '设置',
      }
    ]
  }
]
const sideNavSelected = ref(['overview'])
const openKeys = ref([]) // 控制展开的子菜单

// 菜单项与其父菜单的映射关系
const menuItemToParent = ref({})

for (let index in menus) {
  let menu = menus[index]
  if (menu?.children) {
    for (let subIndex in menu.children) {
      let submenu = menu.children[subIndex]
      menuItemToParent.value[submenu.key] = menu.key
    }
  }
}

// 更新侧边栏选中状态
const updateSideMenu = () => {
  const pathSegments = route.path.split('/');
  // 获取最后一个路径段作为当前页面的标识
  const currentPage = pathSegments[pathSegments.length - 1];
  sideNavSelected.value = [currentPage];

  // 如果当前选中的菜单项在子菜单中，则自动展开父菜单
  if (menuItemToParent.value[currentPage]) {
    openKeys.value = [menuItemToParent.value[currentPage]];
  }
};

// 监听路由变化
watch(() => route.path, () => {
  updateSideMenu();
}, {immediate: true});
</script>

<template>
  <a-layout>
    <a-layout-sider>
      <a-menu
          class="h-full"
          v-model:selectedKeys="sideNavSelected"
          v-model:openKeys="openKeys"
          mode="inline"
      >
        <a-menu-item key="overview">
          <router-link to="/management/overview">概览</router-link>
        </a-menu-item>
        <a-sub-menu key="system">
          <template #title>
              <span>
                系统管理
              </span>
          </template>
          <a-menu-item key="setting">
            <router-link to="/management/setting">设置</router-link>
          </a-menu-item>
        </a-sub-menu>
      </a-menu>
    </a-layout-sider>
    <div class="p-3 h-full w-full">
      <router-view/>
    </div>
  </a-layout>
</template>

<style scoped>
</style>