import { BasicLayout, UserLayout } from '@/components/layouts'
import RouterNotFound from '@/views/exception/RouterNotFound'

/**
 * 基础路由
 * @type { *[] }
 */
export const constantRouterMap = [
  {
    path: '/user',
    component: UserLayout,
    redirect: '/user/login',
    hidden: true,
    children: [
      {
        path: 'login',
        name: 'login',
        component: () => import('@/views/system/Login')
      }
    ]
  },

  {
    path: '*',
    component: () => import('@/views/exception/404')
  }

]

/**
 * 动态路由生成
 * @param target
 * @param init
 * @returns {Array}
 */
export const initRouterTree = (target, init = []) => {

  for (let i = 0; i < target.length; i++) {
    let item = target[i]
    let routerItem = {
      meta: {}
    };
    routerItem.path = item.path
    routerItem.name = item.vrName
    routerItem.meta.title = item.name
    routerItem.hidden = !item.isShow

    if (routerItem.path == '/') {
      routerItem.component = BasicLayout
    } else {
      try {
        if (item.component) {
          routerItem.component = () => import(`@/${item.component}`)
        } else {
          routerItem.component = RouterNotFound
        }
      } catch (e) {
        routerItem.component = RouterNotFound
        console.info('not found', item)
      }
    }
    if (item.vrRedirect) {
      routerItem.redirect = item.vrRedirect
    }
    if (item.icon) {
      routerItem.meta.icon = item.icon
    }
    if (item.permission) {
      routerItem.meta.permission = item.permission
    }
    if (item.isCache) {
      routerItem.meta.keepAlive = true
    }


    if (item.children) {
      routerItem.children = []
      initRouterTree(item.children, routerItem.children);
    }
    init.push(routerItem);
  }
  return init;
}
