import BlankLayout from '@/layouts/BlankLayout.vue'

const commRoutes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login/index.vue')
  }
]

const authRoutes = {
  path: '/',
  name: 'index',
  redirect: { name: 'dashboard' },
  component: () => import('@/layouts/UserLayout/index.vue'),
  meta: {
    title: '首页',
    icon: 'fa fa-home'
  },
  children: [
    {
      path: 'dashboard',
      name: 'dashboard',
      component: () => import('@/views/Dashboard/index.vue'),
      meta: {
        showMenu: true,
        title: 'Dashboard',
        icon: 'fa fa-dashboard'
      }
    },
    {
      path: 'user',
      name: 'user',
      redirect: { name: 'user.list' },
      component: BlankLayout,
      meta: {
        showMenu: true,
        title: '人员管理',
        icon: 'fa fa-user'
      },
      children: [
        {
          path: 'list',
          name: 'user.list',
          component: () => import('@/views/User/index.vue'),
          meta: {
            showMenu: true,
            title: '人员列表',
          }
        },
        {
          path: 'edit',
          name: 'user.edit',
          component: () => import('@/views/User/Edit.vue'),
          meta: {
            title: '人员编辑',
          }
        }
      ]
    }
  ]
}

const routes = commRoutes.concat(authRoutes)

const getMenu = routeList => routeList.reduce((menus, route) => {
  if (route.meta && route.meta.showMenu) {
    const menu = {
      title: route.meta.title,
      icon: route.meta.icon,
      route: {
        path: route.path,
        name: route.name
      }
    }

    if (route.children) {
      const menuChildren = getMenu(route.children)
      if (menuChildren || menuChildren.length) {
        menu['children'] = menuChildren
      }
    }

    return menus.concat(menu)
  }

  return menus
}, [])


const getBread = (routeList, parent, breadList) => routeList.reduce((breads, route) => {
  if (!route.name) {
    return breads
  }

  const meta = route.meta || {}
  if (!meta.title) {
    return breads
  }

  const bread = { name: route.name, path: route.path, icon: meta.icon, title: meta.title }
  const current = parent.concat(bread)

  if (!route.children || !route.children.length) {
    return breads.concat([current])
  } else {
    return getBread(route.children, current, breads)
  }
}, breadList)

const menus = getMenu(authRoutes.children)
const breads = getBread([authRoutes], [], [])

export {
  menus,
  breads,
}

export default routes
