import { createRouter, createWebHistory, type RouteRecordRaw, RouterView } from 'vue-router'
import { isExternal } from '@/utils/util'
import { constantRoutes } from './routes'

// 动态路由接口定义
export interface DynamicRoute {
  id: number
  pid: number
  type: number
  name: string
  icon_type: string
  icon: string
  sort: number
  perms: string
  paths: string
  component?: string
  selected: string
  params: Record<string, any> | string
  is_cache: number
  is_show: number
  is_disable: number
  create_time: string
  update_time: string
  children?: DynamicRoute[]
  path?: string
}

// 匹配views里面所有的.vue文件，动态引入
const modules = import.meta.glob('/src/views/**/*.vue')

// 构建组件映射表，提高查找效率
const componentMap = new Map<string, any>()
Object.keys(modules).forEach((key) => {
  const componentName = key.replace('/src/views/', '').replace('.vue', '')
  if (modules[key]) {
    componentMap.set(componentName, modules[key])
  }
})

export function getModulesKey() {
  return Array.from(componentMap.keys())
}

// 过滤路由所需要的数据
export function filterAsyncRoutes(routes: DynamicRoute[], firstRoute = true, parentPath = ''): RouteRecordRaw[] {
  return routes
    .filter((route) => route.is_disable === 0)
    .map((route) => {
      const fullPath = parentPath ? `${parentPath}/${route.paths}` : route.paths
      const routeRecord = createRouteRecord(route, firstRoute, fullPath)
      if (route.children && route.children.length > 0) {
        routeRecord.children = filterAsyncRoutes(route.children, false, fullPath)
        if (routeRecord.children.length === 0 && route.type === 1) {
          return null
        }
      }
      return routeRecord
    })
    .filter((route): route is RouteRecordRaw => route !== null)
}

// 创建一条路由记录
export function createRouteRecord(route: DynamicRoute, firstRoute: boolean, fullPath: string): RouteRecordRaw {
  let routePath: string
  if (isExternal(route.paths)) {
    routePath = route.paths
  } else {
    routePath = firstRoute ? `/${route.paths}` : route.paths
    routePath = routePath.replace(/\/+/g, '/')
  }
  let component: any
  switch (route.type) {
    case 1: // 目录类型
      component = null
      break
    case 2: // 菜单类型
      if (route.component && !isExternal(route.component)) {
        component = loadRouteView(route.component)
      } else {
        component = markRaw(RouterView)
      }
      break
    default:
      component = markRaw(RouterView)
  }
  if (route.type === 1 && route.children && route.children.length > 0) {
    const firstValidMenu = route.children.find(
      (child) => child.type === 2 && child.is_show === 1 && child.is_disable === 0
    )
    if (firstValidMenu) {
      return {
        path: routePath,
        name: fullPath.replace(/\//g, '_').replace(/^_/, '') || `route_${Date.now()}`,
        redirect: {
          name: `${fullPath}/${firstValidMenu.paths}`.replace(/\//g, '_').replace(/^_/, '')
        },
        meta: {
          hidden: route.is_show !== 1,
          keepAlive: route.is_cache === 1,
          title: route.name,
          perms: route.perms,
          query: route.params,
          iconType: route.icon_type,
          icon: route.icon,
          type: route.type,
          activeMenu: route.selected
        }
      }
    }
  }
  return {
    path: routePath,
    name: fullPath.replace(/\//g, '_').replace(/^_/, '') || `route_${Date.now()}`,
    component: component,
    meta: {
      hidden: route.is_show !== 1,
      keepAlive: route.is_cache === 1,
      title: route.name,
      perms: route.perms,
      query: route.params,
      iconType: route.icon_type,
      icon: route.icon,
      type: route.type,
      activeMenu: route.selected
    }
  }
}

// 动态加载组件
export function loadRouteView(component: string) {
  try {
    const componentLoader = componentMap.get(component)
    if (componentLoader) {
      return componentLoader
    }
    const formattedComponent = component.replace(/\./g, '/')
    const formattedLoader = componentMap.get(formattedComponent)
    if (formattedLoader) {
      return formattedLoader
    }
    throw Error(`找不到组件${component}，请确保组件路径正确`)
  } catch (error) {
    console.error(error)
    return markRaw(RouterView)
  }
}

// 找到第一个有效的路由
export function findFirstValidRoute(routes: RouteRecordRaw[]): string | undefined {
  for (const route of routes) {
    if (route.name && route.meta?.type == 2 && !route.meta?.hidden && !isExternal(route.path)) {
      return route.name as string
    }
    if (route.children && route.children.length > 0) {
      const name = findFirstValidRoute(route.children)
      if (name) {
        return name
      }
    }
  }
  return undefined
}

// 通过权限字符查询路由路径
export function getRoutePath(perms: string): string {
  const routerObj = router
  return routerObj.getRoutes().find((item) => item.meta?.perms === perms)?.path || ''
}

// 重置路由
export function resetRouter() {
  const routeNames = router
    .getRoutes()
    .map((route) => route.name)
    .filter(Boolean) as string[]
  routeNames.forEach((name) => {
    const isConstantRoute = constantRoutes.some((route) => route.name === name)
    if (!isConstantRoute && router.hasRoute(name)) {
      router.removeRoute(name)
    }
  })
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: constantRoutes
})

export default router
