import router from './index'

const hasChildren = (item: any) => {
  return item.children && item.children.length > 0
}

const viewPage = import.meta.glob('/src/views/**/index.vue')

const getRoute = (item: any) => {
  if (item.path.indexOf('http') >= 0) {
    return null
  }
  return {
    path: item.path,
    name: item.path,
    meta: {
      name: item.name,
      keepAlive: item.keepAlive === '1'
    },
    component: viewPage[`/src/views${item.path}/index.vue`]
  }
}

const addRoute = (routerCtx: any, route: any) => {
  if (route) {
    routerCtx.addRoute('首页', route)
  }
}

export default function addRoutes(menus: any, tempRouter?: any) {
  let routerCtx = tempRouter
  if (!routerCtx) {
    routerCtx = router
  }
  menus.forEach((item: any) => {
    if (hasChildren(item)) {
      item.children.forEach((child: any) => {
        addRoute(routerCtx, getRoute(child))
      })
    } else {
      addRoute(routerCtx, getRoute(item))
    }
  })
}
