import React, { isValidElement } from 'react';
import { Provider } from 'mobx-react';

import { WeaLocaleProvider, WeaAlertPage, WeaLoadingGlobal } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

function transRoute(mod) {
  const { Route, store } = mod;
  const hasStore = store && Object.keys(store).length > 0;
  const loop = (r) => {
    let childRoutes = [];
    if (Array.isArray(r)) {
      // child: Array
      return r.map(l => loop(l));
    } else if (isValidElement(r)) {
      // child: React.Element
      if (Array.isArray(r.props.children)) {
        r.props.children.forEach((c) => {
          if (Array.isArray(c)) {
            childRoutes = childRoutes.concat(loop(c));
          } else {
            childRoutes.push(loop(c));
          }
        });
      } else if (typeof r.props.children === 'object') {
        childRoutes = [loop(r.props.children)];
      }
      // filter child not Route
      childRoutes = childRoutes.filter(Boolean);
      // IndexRoute
      const childIndexRoute = childRoutes.filter(c => c.type === 'IndexRoute');
      // IndexRedirect
      const childIndexRedirect = childRoutes.filter(c => c.type === 'IndexRedirect');
      // Route
      childRoutes = childRoutes.filter(c => c.type === 'Route');
      // return
      const newProps = { ...r.props };
      const type = r.type.displayName;
      delete newProps.children;
      return {
        ...newProps,
        ...(hasStore && r.props.component ? {
          component: props => (
            <Provider {...store}>
              <r.props.component {...props} />
            </Provider>
          ),
        } : {}),
        childRoutes,
        type,
        ...(childIndexRoute.length === 1 ? {
          indexRoute: childIndexRoute[0],
        } : {}),
        ...(childIndexRedirect.length === 1 ? {
          indexRoute: {
            onEnter: (nextState, replace) => {
              const { location: { basename, pathname, search } } = nextState;
              const { to } = childIndexRedirect[0];
              if (to.indexOf('/') === 0) return replace(to);
              return replace(`${basename}${pathname}/${to}${search}`);
            },
          },
        } : {}),
      };
    }
  };
  if (Array.isArray(Route)) {
    return Route.map(r => loop(r));
  } else if (isValidElement(Route)) {
    return loop(Route);
  }
  return null;
}

export default class LibRoute {
  static transRoute = transRoute
  constructor(type) {
    const csAppRoute = {
      path: 'cs',
      childRoutes: [{
        path: 'app',
        childRoutes: [{
          path: ':uuid',
          component: props => (
            <div id={props.params.uuid} />
          ),
        }],
      }],
    };
    this.libRouteLoaded = {
      keys: [],
      routes: [{
        path: 'com',
        childRoutes: [{
          path: 'auth',
          component: () => (
            <WeaAlertPage iconSize={100} >
              <p>{getLabel(2012, '对不起，您暂时没有权限！')}</p>
            </WeaAlertPage>
          ),
        }],
      }],
    };
    if (type === 'main') {
      this.libRouteLoaded.routes.push(csAppRoute);
    } else if (type === 'bs_main') {
      this.libRouteLoaded.routes.push({
        path: 'main',
        childRoutes: [csAppRoute],
      });
    }
  }

  getLibRoute = (regName, libName, routeName, resolve) => {
    const mod = window[libName];
    if (mod) {
      const routes = transRoute(mod);
      if (Array.isArray(routes)) {
        if (!this.libRouteLoaded.keys.some(key => key === regName)) {
          this.libRouteLoaded.routes = this.libRouteLoaded.routes.concat(routes);
          this.libRouteLoaded.keys.push(regName);
        }
      } else if (typeof routes === 'object') {
        if (!this.libRouteLoaded.keys.some(key => key === regName)) {
          this.libRouteLoaded.routes.push(routes);
          this.libRouteLoaded.keys.push(regName);
        }
      }
    } else {
      // window.console.warn(`${libName} 不存在`);
    }
    resolve && resolve();
  };

  getLibRouteAsync(regName, libName, routeName, times = 1) {
    return new Promise((resolve, reject) => {
      WeaLoadingGlobal.start();
      window.eventRegister && window.eventRegister.loadModule(regName,
        () => {
          // bug for js loaded...
          this.getLibRoute(regName, libName, routeName, resolve);
          WeaLoadingGlobal.destroy();
        },
        () => {
          const msg = `${regName} 第 ${times} 次加载失败`;
          reject(msg);
          WeaLoadingGlobal.destroy();
          // window.console.error(msg);
        },
      );
    });
  }
}
