import router from './router';
import store from './store';
import { Message } from 'element-ui';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { getToken, getThirdPlatform } from '@/utils/auth';
import { isRelogin } from '@/utils/request';

NProgress.configure({ showSpinner: false });

const whiteList = ['/login', "/404", "/401"];

router.beforeEach((to, from, next) => {
  // 默认跳转路径 本系统跳转首页，第三方跳转宏观市场
  const platFormKey = getThirdPlatform();
  let defaultRedirectPath = platFormKey ? "/macro/nationalEconomies" : "/";
  NProgress.start();
  if (getToken()) {
    // tab页签title
    const { tabTitle, url } = to.query;
    if (tabTitle) to.meta.title = decodeURIComponent(tabTitle);
    if (!tabTitle && to.meta.isSubSystem && url) to.meta.title = decodeURIComponent(url);
    to.meta.title && store.dispatch('settings/setTitle', to.meta.title);
    /* has token*/
    if (to.path === '/login') {
      next({ path: defaultRedirectPath });
      NProgress.done();
    } else {
      if (!store.state?.user?.userId && !store.state?.user?.roles?.length) {
        isRelogin.show = true;
        // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(() => {
          isRelogin.show = false;
          store.dispatch('GenerateRoutes').then(accessRoutes => {
            // 根据roles权限生成可访问的路由表
            router.addRoutes(accessRoutes); // 动态添加可访问路由表
            next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
          });
        }).catch(err => {
          if (platFormKey) {
            store.dispatch('FedLogOut').then(() => {
              next({
                path: "/401",
                query: {
                  isSecretFreeLogin: true
                }
              });
            });
          } else {
            store.dispatch('LogOut').then(() => {
              Message.error(err);
              sessionStorage.removeItem('views');
              next({ path: '/' });
            });
          }
        });
      } else {
        next();
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      // 非白名单 没有token 判断是否有app key 属于第三方平台
      // 第三方平台 获取到 platFormKey 直接通过key 登录
      if (platFormKey) {
        store.dispatch("secretFreeLogin", platFormKey).then((res) => {
          next({
            path: defaultRedirectPath
          });
        }).catch(err => {
          // appkey 登陆失败 跳转到401
          next({
            path: "/401",
            query: {
              isSecretFreeLogin: true
            }
          });
        });
      } else {
        next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
        NProgress.done();
      }
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
