import { layouts, staticRouters } from "@/router/modules/routerComponents"
import type { AppRouter } from '@/router/config/index'
import { validURL } from "@/utils/valid"
import type { Component } from "vue"
import { uuid } from '@/utils/util'


const constantRouterComponents: Component = {
  ...layouts,
  ...staticRouters
}

const menuTypeFormat = (type?: string) => {
  if (!type) return null
  const menuTypeObj: ExtraObj = {
    'G': 'group', // 分组
    'F': 'button', // 按钮
    'C': 'menu', // 菜单
    'M': 'catalogue', // 目录
  }
  return menuTypeObj[type] || null
}

// 构造路由
export const generator = async (routerMap: AppRouter[] | ExtraObj[], parent:AppRouter | null): Promise<AppRouter[]> => {
  const newRouter = await Promise.all(routerMap.map(async (item: AppRouter | ExtraObj) => {
    const { title, hideChildren, hiddenHeaderContent, hidden, icon,  isFrame, target } = item.meta || {}
    const currentRouter: AppRouter = {
      path: item.path,
      key: item.key,
      fullPath: (parent ? `${parent?.fullPath ?? ''}${item.path?.includes('/') ? item.path : '/' + item.path}` : `${item.path}`),
      // 路由名称，建议唯一
      name:  item.menuId || item.name || item.key || uuid(),
      // 该路由对应页面的 组件(动态加载)
      component: constantRouterComponents[item.component] || (() => import(`@/views/${item.component}`)),
      // hideChildrenInMenu: item.hideChildrenInMenu,
      // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
      hidden: item.hidden,
      parent: parent,
      parentId: item.parentId ?? parent?.name,
      icon: item?.meta?.icon || item.icon as string | undefined,
      meta: {
        icon: item?.meta?.icon || item.icon,
        isFrame: isFrame,
        title: title || item.menuName,
        hideChildrenInMenu: hideChildren,
        hiddenHeaderContent: hiddenHeaderContent,
        // 目前只能通过判断path的http链接来判断是否外链
        target: (validURL(item.path) ? '_blank' : ''),
        permission: item.name,
        hidden: hidden
      },
      type: item.type || menuTypeFormat(item.menuType),
      typeName: item.typeName || null,
      redirect: item.redirect
    }
    if (item.component && !constantRouterComponents[item.component]) {
      currentRouter.path = `${parent?.path ?? ''}/${item.path}`
    }
    // 是否设置了隐藏子菜单
    // 是否有子菜单，并递归处理，并将父path传入
    if (item.children && item.children.length > 0) {
      // Recursion
      currentRouter.children = await generator(item.children, currentRouter)
    }
    return currentRouter
  }))

  return newRouter
}
