import { lst } from '../utils'
import { features, KeepAliveLayout } from './feature'
import { apps } from '@/utils/qiankun-init'
import routes from './routes'
const router = new window.VueRouter({
  mode: 'history',
  base: '',
  routes: [
    { path: '/login', meta: { noToken: true }, component: () => import('@/views/login') },
    { path: '/register', meta: { noToken: true }, component: () => import('@/views/register') },
    { path: '/404', meta: { noToken: true }, component: () => import('@/views/404') },
    { path: '/entry', meta: { noToken: true }, component: () => import('@/views/entry') }
  ]
})

const HomePage = {
  path: '/',
  meta: { title: '训练管理' },
  component: () => import('@/views/home'),
  children: [{ path: '/', meta: { title: '数据统计' }, component: () => import('@/views/statistic') },
    { path: '/print-paper/:paperId?', meta: { noToken: false, key: 'printPaper' }, component: () => import('@/views/assessment-evaluation/examination-paper-manage/components/PrintPaper.vue') }

  ]
}

export function initRoutes () {
  const moduleAuth = lst.get('module')
  if (!moduleAuth) return

  const fn = (list) => {
    const routeList = []
    const menuList = []
    for (const v of list) {
      if (moduleAuth.includes(v.path)) {
        const menu = { name: v.path, label: v.meta.title, icon: v.meta.icon }
        if (v.children && v.children.length) {
          const child = fn(v.children)
          routeList.push({ ...v, children: child.routeList })
          menu.children = child.menuList
        } else {
          routeList.push(v)

          if (routes[v.path]) {
            routeList.push({ path: v.path, meta: v.meta, component: KeepAliveLayout, children: routes[v.path] })
          }
        }
        menuList.push(menu)
      }
    }
    return { routeList, menuList }
  }
  apps && features.push(...apps.map(i => {
    return {
      path: i.activeRule,
      meta: { title: i.name }
    }
  }))
  const { routeList, menuList } = fn(features)
  console.log(menuList)
  lst.save('menu', menuList)
  HomePage.children.push(...routeList)
  // router.addRoutes([HomePage, { path: '*', redirect: '/404' }])
  router.addRoutes([HomePage])
}

initRoutes()

router.beforeEach((to, from, next) => {
  console.log(to.meta.noToken || lst.get('token', '').startsWith('Bearer '))
  if (to.meta.noToken || lst.get('token', '').startsWith('Bearer ')) {
    next()
  } else {
    next('/login')
  }
})

export default router
