import router from './router'
import { useStore } from 'vuex';
/* import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css' // Progress 进度条样式 */
import { ElMessage } from 'element-plus'
import Storage from '@/utils/storage'

const whiteList = ['/login', '/boxed-signup','/platformLogin']

let toFirstRoute = function getTopRoutePath(router, next) {
  const excludes = [
    "",
    "*",
    '/404',
    '/401',
    '/500',
    '/login',
    '/cashier/login',
    '/boxed-signup',
    '/payType'
  ]
  const paths = router.getRoutes().map(item => item.path)
  const path = paths.filter(item => !excludes.includes(item) && item.indexOf('/:') === -1)[0]
  if (typeof next === 'function') {
    next(path)
  } else {
    router.replace(path)
  }
}
router.beforeEach(async (to, from, next) => {
  const store = useStore()
  if (to?.meta?.layout == 'auth') {
    store.dispatch("setMainLayout", 'auth');
  } else {
    store.dispatch("setMainLayout", 'app');
  }
 /*  next(true); */
  const refreshToken = Storage.getItem('admin_refresh_token')
  if (refreshToken) {
    if ((to.path === '/login' || to.path === '/boxed-signup' || to.path ==='/platformLogin') && store.getters.addRouters.length) {
      return next(toFirstRoute(router))
      /* toFirstRoute(router, next) */
     /*  NProgress.done() */
    } else {
      if (store.getters.addRouters.length === 0) {
        try {
          await store.dispatch('GenerateRoutes')
          const routers = store.getters.addRouters
          router.addRoute(routers)
          if (routers.length) {
            const paths = router.getRoutes().map(item => item.path)
            if (paths.includes(to.path)) {
              return  next({ ...to, replace: true })
            } else {
              return  next(toFirstRoute(router))
              /* toFirstRoute(router, next) */
            }
          } else {
            return next('/404')
          }
        } catch {
          await store.dispatch('fedLogoutAction')
          ElMessage.error('验证失败,请重新登录')
          const toPath = Storage.getItem('admin_franchise') ? '/boxed-signup' : '/login'
          return next(toPath)
          /* const toPath = Storage.getItem('admin_franchise') ? '/boxed-signup' : '/login'
          window.location.replace(router.resolve(toPath).href) */
        }
      } else {
        return next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      return  next()
    } else {
      const toPath = Storage.getItem('admin_franchise') ? '/boxed-signup' : '/login'
      return next(toPath)
    /*   NProgress.done() */
    }
  }
})

router.afterEach(() => {
/*   NProgress.done() */
})
