import { type RouteRecordRaw } from 'vue-router'

// 菜单项接口
export interface MenuItem {
  name: string
  path: string
  meta: {
    title: string
    icon?: string
    sort?: number
    hidden?: boolean
    [key: string]: unknown
  }
  children?: MenuItem[]
}

// 排序函数
export const sortMenuItems = (items: MenuItem[]): MenuItem[] => {
  return items
    .filter((item) => !item.meta.hidden) // 过滤隐藏的菜单
    .sort((a, b) => {
      const aSort = a.meta.sort ?? 999 // 默认值确保未设置sort的排在后面
      const bSort = b.meta.sort ?? 999
      return aSort - bSort
    })
    .map((item) => {
      if (item.children) {
        return {
          ...item,
          children: sortMenuItems(item.children),
        }
      }
      return item
    })
}

// 将路由转换为菜单项
export const routesToMenuItems = (routes: RouteRecordRaw[]): MenuItem[] => {
  return routes.map((route) => ({
    name: route.name as string,
    path: route.path,
    meta: {
      ...route.meta,
      title: (route.meta?.title as string) || '',
      sort: (route.meta?.sort as number) || 999,
    },
    children: route.children ? routesToMenuItems(route.children) : undefined,
  }))
}
