import router from './router'
import store from './store'
import { getItem } from '@/utils/index'
import { TOKEN } from '@/utils/constant'
import { getMenusData, flatMenus } from '@/utils/route'
import { privateRoutes } from '@/router/private-routes'

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

/**
 * @param {*} to 到哪去
 * @param {*} from 从哪来
 * @param {*} next 是否要去
 */
router.beforeEach(async (to, from, next) => {
  if (getItem(TOKEN)) {
    if (to.path === '/login') {
      next('/')
    } else {
      // console.log(store.getters.hasUserInfo)
      // 判断用户资料是否存在 如果不存才 则需要获取用户信息

      if (!store.getters.hasUserInfo) {
        // todo: 做权限的时候解开
        // 拿到后台返回的权限列表
        const { permissions } = await store.dispatch('user/getUserInfo')

        // 这里是在做排序
        const allMenus = flatMenus(getMenusData()) // Array.from(new Set())
        const orderPermissions = allMenus.filter((item) => permissions.includes(item))
        // 通过比对路由 动态添加
        const filterRoutes = await store.dispatch('permission/filterRoutes', orderPermissions)

        filterRoutes.forEach((item) => {
          router.addRoute(item)
        })

        return next(to.path)
        next({ ...to, replace: true })
      }
      next()
    }
  } else {
    // 2. 用户未登录，只允许进入白名单
    if (whiteList.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login')
    }
  }
})
