// @author ilex.h
import { Store } from 'amos-tool';
import * as endConf from 'amos-processor/lib/config/endconf';
import RProgress from 'ray-progress';
import AutoLogin from './../view/autoLogin/AutoLogin';
import calcRoutes from './calcRoutes';
import addCustomRoutes, { customRoutes } from './customRoutes';
import pageCompontent, {
  RootView,
  RootBizView,
  ConsoleView,
  RegionList
} from './view';

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

const groups = [
  'main', 'biz', 'console', 'ruleConfig'
];

const injectRoutes = menus => {
  const { main = [], biz = [], console: consoleRoutes = [] } = calcRoutes(menus, pageCompontent, groups) || {};
  const mainChilds = addCustomRoutes(main);
  const bizChilds = addCustomRoutes(biz);
  const consoleChilds = addCustomRoutes(consoleRoutes);
  const routes = [
    { path: 'autologin', component: AutoLogin },
    { path: 'region', component: RegionList }, // 区域选择
    {
      path: 'main',
      component: RootView,
      childRoutes: [...mainChilds]
    },
    {
      path: 'biz',
      component: RootBizView,
      childRoutes: [...bizChilds, ...customRoutes]
    },
    {
      path: 'console',
      component: ConsoleView,
      childRoutes: consoleChilds
    }
  ];
  return routes;
};

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

const routerFilter = () => {

};

const checkLogin = () => {

};

const onEnterValidate = (next, replace, callback) => {
  progressStart();
  const pathname = next.location.pathname;
  const flag = routerFilter({
    filterPath: [].concat('autologin'),
    pathname
  });
  console.log('pathname|flag', pathname, flag);
  if (!checkLogin() && flag ) {
    window.location.href = loginURI;
  }
  callback();
};

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

export default rootRoutes;
