/* Layout */
import Layout from '@/layout'

/**
 * 菜单转路由
 * @param {*} menus
 */
export function menuToRouter(menus) {
  const resultRouters = []
  if (!menus || menus.length === 0) {
    return resultRouters
  }
  convert(menus, null)
  function convert(menusList, menuItem) {
    if (!menusList || menusList.length === 0) {
      return
    }
    menusList.forEach(item => {
      if (item.menuType === 1 && !item.router) {
        console.error('错误目录配置：', item.router)
        return
      }

      if (item.menuType === 1 && item.menuName === 'dashboard') {
        return
      }

      if (item.menuType === 3) {
        return
      }

      let nextNode
      try {
        if (!menuItem) {
          nextNode = {
            path: item.router,
            component: Layout,
            hidden: false,
            meta: { title: item.menuName, icon: item.icon },
            children: []
          }
          resultRouters.push(nextNode)
          convert(item.childrens, nextNode)
          return
        }

        nextNode = {
          path: item.router,
          name: item.alias,
          meta: { title: item.menuName, icon: item.icon, keepAlive: true }
        }

        if (item.menuType === 2 && (!item.path || item.path.length <= 0)) {
          console.error('请删除无效菜单：', `[${item.menuName}]`, `/views/${item.path}.vue`)
          return
        }

        if (item.menuType === 2 && item.path) {
          nextNode.component = (resolve) => require([`@/views/${item.path}.vue`], resolve)
        }

        if (item.menuType === 1 && item.childrens && item.childrens.length > 0) {
          nextNode.component = (resolve) => require(['@/layout/components/AppMain.vue'], resolve)
        }

        if (!menuItem.children) {
          menuItem.children = []
        }
        menuItem.children.push(nextNode)

        convert(item.childrens, nextNode)
      } catch (er) {
        console.error('请删除无效菜单：', `[${item.menuName}]`, `/views/${item.path}.vue`)
      }
    })
  }
  return resultRouters
}

