// @author ilex.h
import RProgress from 'ray-progress';
import * as endConf from 'amos-processor/lib/config/endconf';
import notFound from 'amos-security/lib/routes/notfound';
import redirect from 'amos-security/lib/routes/notfound/redirect';
import signUp, { signupRouters } from 'amos-security/lib/routes/signUp';
import routerFilter, { checkLogin } from 'amos-security/lib/routes/validateRouter';
import calcRoutes from './calcRoutes';
import addCustomRoutes, { customRoutesMain } from './customRoutes';
import pageCompontent, { AsyncRootView, AsyncLogin, AsyncUserInfo, AsyncOutter, AsyncRegionList } from './asyncView';
import AutoLogin from './../view/autoLogin/AutoLogin';

const AmosConfig = endConf.AmosConfig;
const loginURI = AmosConfig.httpURI.baseURI;

const progressStart = () => {
  RProgress.start();
};

const injectRoutes = (menus) => {
  const mainChilds = addCustomRoutes(calcRoutes(menus, pageCompontent));
  const routes = [
    //{ path: 'login', component: AsyncLogin },
    { path: 'autologin', component: AutoLogin },
    { path: 'outter', component: AsyncOutter },
    { path: 'region', component: AsyncRegionList }, // 区域选择
    ...signUp,
    {
      path: 'main' ,
      component: AsyncRootView,
      childRoutes: [...mainChilds, { path: 'securityConfig', component: AsyncUserInfo }, ...customRoutesMain]
    },
    notFound,
    redirect
  ];

  return routes;
};

const onEnterValidate = (next, replace, callback) => {
  progressStart();
  const pathname = next.location.pathname;
  const flag = routerFilter({
    filterPath: [].concat(signupRouters, 'login', 'outter'),
    pathname
  });

  if (!checkLogin() && flag ) {
    replace('/login');
  }
  callback();
};

const rootRoutes = (menus) => {
  return {
    path: '/',
    onEnter: onEnterValidate,
    onChange: progressStart,
    indexRedirect: AsyncLogin,
    indexRoute: {
      onEnter(nextState, replace) {
        //replace('/login');
        window.location.href = loginURI;
      }
    },
    childRoutes: injectRoutes(menus)
  };
};

export default rootRoutes;
