import { SpecialPage } from '@/common/router/constants.ts'
import type { RouteRecordRaw } from 'vue-router'
import Strings from '@/common/utils/strings.ts'

// 导入 src/pages 目录下的所有 page.ts 文件
// K：文件路径，V：PageConfig 对象
const configPath_routeConfig_map: Record<string, RouterTypes.RouteConfig> = import.meta.glob('@/pages/**/page.ts', {eager: true, import: 'default'})

// 处理页面配置，如：默认值填充
const routeConfigs = Object.entries(configPath_routeConfig_map).map(([ configPath, pageConfig ]) => {
  const routePath = configPath.replace(/\S*pages\/(\S*)\/page.ts/, '$1')
  const {
    parent = SpecialPage.Main,
    path = routePath,
    name = routePath.substring(routePath.lastIndexOf('/') + 1),
    title = name,
    componentName = Strings.pascalCase(name),
    keepAlive = false,
    icon = '',
    component,
    meta,
    props,
    beforeEnter,
  } = pageConfig

  return {
    parent,
    path,
    name,
    componentName,
    title,
    icon,
    keepAlive,
    meta,
    props,
    component,
    beforeEnter,
  } as RouterTypes.RouteConfig
})

export const pageConfigs = routeConfigs.map(it => ({
  title: it.title!,
  name: it.name!,
  path: it.path!,
  parent: it.parent!,
  keepAlive: it.keepAlive!,
} as RouterTypes.PageConfig))

export function getRoutes(routeNames?: string[]): RouterTypes.RouteInfo[] {
  const configs = routeNames == null ? routeConfigs : routeConfigs.filter(it => routeNames.includes(it.name!))
  return configs.map(({parent, path, name, meta, props, component, beforeEnter}) => {
    return {
      parent: parent!,
      route: {
        path,
        name,
        meta,
        props,
        component,
        beforeEnter,
        children: [],
      } as RouteRecordRaw,
    }
  })
}

export function getRoute(routeName?: string): RouterTypes.RouteInfo | null {
  const config = routeConfigs.find(it => routeName === it.name)
  if (config == null) {
    return null
  } else {
    const {parent, path, name, meta, props, component, beforeEnter} = config
    return {
      parent: parent!,
      route: {
        path,
        name,
        meta,
        props,
        component,
        beforeEnter,
        children: [],
      } as RouteRecordRaw,
    }
  }
}
