import router from './router'
import store from './store'
import { getItem } from '@/utils/index'
import { TOKEN } from '@/utils/constant'
import { filterPermissionsRoutes, flattenedRoutes, buildTreeData } from '@/router/private-routes'
import Layout from '@/layout/index.vue'

// 白名单
const whiteList = ['/login']

/**
 * @param {*} to 到哪去
 * @param {*} from 从哪来
 * @param {*} next 是否要去
 */
router.beforeEach(async (to, from, next) => {
  if (getItem(TOKEN)) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.hasUserInfo) {
        const { permissions } = await store.dispatch('user/getUserInfo')
        const fRoutes = await filterPermissionsRoutes(flattenedRoutes, permissions)

        fRoutes.forEach(async (item) => {
          await router.addRoute(item)
        })

        const navMenus = fRoutes.map(({ name, meta, path }) => ({ name, meta, path, children: [] }))
        store.dispatch('permission/setNavMenus', buildTreeData(navMenus))

        await router.addRoute({
          path: '/*',
          name: 'Layout',
          component: Layout,
          children: [
            {
              path: '/*',
              name: 'redirect',
              component: () => import('@/views/err-page/404.vue')
            }
          ]
        })
        return next(to.path)
        next({ ...to, replace: true })
      }
      next()
    }
  } else {
    // 2. 用户未登录，只允许进入白名单
    if (whiteList.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login')
    }
  }
})
