import Qs from 'qs';
import Home from '../home';
import PageContainer from '../pageContainer';
import NotFound from '../modules/exception/404';
import App from './App';
import exclusive from '../pageContainer/exclusive';
import { PFetch } from '../system/fetch';
import { longRunExec } from '../system/longRunOpt';
import { savePageData, isInitDataFromServer } from '../service/CacheService';
import { trimStart } from '../utils/StringUtils';
import { getGlobalConfig } from '../index';

export const CONTAINER_PRE = getGlobalConfig() && getGlobalConfig().ContainerPre || 'page_container';

const getUrlPath = url => url;

// 要初始化数据的页面
const getPageInitData = (nextState, replace, callback, config) => {
  // 是否初始化了

  const domainLink = nextState.params.splat;
  if (domainLink && !exclusive().some(f => f(domainLink)) && !domainLink.endsWith('.html')) {
    const url = getUrlPath(trimStart(domainLink, '/'));
    const params = Object.assign({ ...nextState.params }, nextState.location.state);
    if (nextState.location) {
      const query = nextState.location.query && nextState.location.query.p && atob(nextState.location.query.p);
      Object.assign(params, Qs.parse(query));
    }
    // TODO: add process menu
    const handler = () => longRunExec(() => PFetch(url, params)
      .then(data => {
        // TODO: 如何保存此时的数据
        savePageData(data);
        callback();
      }).catch(err => {
        savePageData('EXCEPTION');
        callback();
        throw err;
      }));
    if (window.__showLogin) {
      window.__initPage = handler;
    } else {
      handler();
    }
  } else {
    savePageData([]);
    callback();
  }
};

/* eslint-disable global-require */
const routes = config => {
  const home = config.homePage || Home;
  return {
    path: '/',
    component: App,
    indexRoute: { component: home },
    childRoutes: [
      {
        path: '/' + CONTAINER_PRE + '/index.html', component: home
      },
      {
        path: '/' + CONTAINER_PRE + '/**',
        component: PageContainer,
        // getComponents(nextState, callback) {
        //   require.ensure([], require => {
        //     callback(null, require('./pageContainer/index').default);
        //   }, 'container');
        // },
        onEnter: (nextState, replace, callback) => getPageInitData(nextState, replace, callback, config)
      },
      { path: '*', component: NotFound },
    ],
  };
};

export default routes;
