<template>
  <a-menu
    v-model:selectedKeys="selectedKeys"
    v-model:openKeys="openKeys"
    mode="inline"
    theme="dark"
    :inline-collapsed="props.collapsed"
    @click="handleMenuClick"
  >
    <template v-for="item in sortedMenuItems" :key="item.name">
      <a-menu-item v-if="!item.children" :key="item.name">
        <template #icon>
          <component :is="item.meta.icon" v-if="item.meta.icon" />
        </template>
        {{ item.meta.title }}
      </a-menu-item>

      <a-sub-menu v-else :key="item.name">
        <template #icon>
          <component :is="item.meta.icon" v-if="item.meta.icon" />
        </template>
        <template #title>{{ item.meta.title }}</template>
        <a-menu-item v-for="child in item.children" :key="child.name">
          {{ child.meta.title }}
        </a-menu-item>
      </a-sub-menu>
    </template>
  </a-menu>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRouter, useRoute, type RouteRecordRaw } from 'vue-router'
import { type MenuProps } from 'ant-design-vue'
import { routesToMenuItems, sortMenuItems } from '@/utils/menuUtils'

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

defineOptions({
  name: 'SideMenu',
})

const props = defineProps<{
  collapsed: boolean
}>()

const selectedKeys = ref<string[]>([])
const openKeys = ref<string[]>([])

// 获取排序后的菜单项
const sortedMenuItems = computed(() => {
  const menuItems = routesToMenuItems(
    router.options.routes.filter(
      (route) => route.meta && route.meta.title && !route.meta.hidden
    ) as RouteRecordRaw[]
  )
  return sortMenuItems(menuItems)
})

// 处理菜单点击
const handleMenuClick: MenuProps['onClick'] = ({ key }) => {
  router.push({ name: key as string })
}

// 根据当前路由更新菜单状态
const updateMenuStatus = () => {
  const currentRoute = route
  const routeName = currentRoute.name as string

  selectedKeys.value = [routeName]

  // 查找父级路由设置展开菜单
  const findParentRoute = (routes: RouteRecordRaw[], targetName: string): string | null => {
    for (const route of routes) {
      if (route.name === targetName) {
        return null
      }

      if (route.children) {
        for (const child of route.children) {
          if (child.name === targetName) {
            return route.name as string
          }
        }

        const parentName = findParentRoute(route.children, targetName)
        if (parentName) {
          return route.name as string
        }
      }
    }
    return null
  }

  const parentName = findParentRoute(router.options.routes as RouteRecordRaw[], routeName)
  if (parentName) {
    openKeys.value = [parentName]
  }
}

// 监听路由变化
watch(() => route.fullPath, updateMenuStatus)

// 初始化
updateMenuStatus()
</script>
