// @author ilex.h
import React from 'react';
import { Store } from 'amos-tool';
import RProgress from 'ray-progress';
import * as endConf from 'amos-processor/lib/config/endconf';
import calcRoutes from './calcRoutes';
import addCustomRoutes, { customRoutes } from './customRoutes';
import pageCompontent, { AsyncRootView, AsyncLogin, AsyncUserInfo, AsyncRootBizView, AsyncConsoleView, AsyncRegionList } from './asyncView';
import AutoLogin from './../view/autoLogin/AutoLogin';

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


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

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: AsyncRegionList }, // 区域选择
    {
      path: 'main',
      component: AsyncRootView,
      childRoutes: [...mainChilds, { path: 'securityConfig', component: AsyncUserInfo }]
    },
    {
      path: 'biz',
      component: AsyncRootBizView,
      childRoutes:  [...bizChilds, ...customRoutes]
    },
    {
      path: 'console',
      component: AsyncConsoleView,
      childRoutes: consoleChilds
    }
  ];
  return routes;
};

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

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,
    indexRedirect: AsyncLogin,
    indexRoute: {
      component: AsyncLogin,
      onEnter(nextState, replace) {
        window.location.href = loginURI;
      }
    },
    childRoutes: injectRoutes(menus)
  };
};

export default rootRoutes;
