/**
 *
 * @authors ilex
 * @date    2016-07-18 16:42:35
 * @description 主入口模块
 */

import React, { Component } from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router, browserHistory } from 'amos-react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { browerSupport, consts, Store, LocationParam } from 'amos-tool';
import { DownloadBrowsers,AmosAlert } from 'amos-framework';
import { loginURI } from './../consts/urlConsts';
import { sessionConsts } from '../consts/storageConsts';
import SysConsts from 'amos-processor/lib/config/consts';
import { getSystemAllMenu } from '../services/securityService';
import rootRoutes from './../routes';
import configureStore from './../store';

// 引入主体样式文件
import './../styles';

const lsTool = Store.lsTool;
const store = configureStore();

const history = syncHistoryWithStore(browserHistory, store);
const support = browerSupport(['firefox/', 'chrome/'], {
  'firefox/': { limit: consts.GREATER_EQUAL, version: 50 },
  'chrome/': { limit: consts.GREATER_EQUAL, version: 55 }
});

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      rootRoutes: rootRoutes(),
      visible: false
    };
  }

  componentWillMount() {
    let token = LocationParam.getLocationParamByName('token');
    if (!token) {
      let systemMenu = JSON.parse(lsTool.read(sessionConsts.systemMenu));
      if (!systemMenu) {
        window.location.href = loginURI;
        return;
      }
      this.setState({ rootRoutes: rootRoutes(systemMenu), visible: true });
      return;
    } else {
      lsTool.write(SysConsts.token, token);
    }

    getSystemAllMenu().then(
      menus => {
        let systemMuens = this.filterSystemMenus(menus);
        let routeMenus = [];
        systemMuens.forEach(item => {
          if (item.children && item.children.length > 0) {
            routeMenus = [...routeMenus, ...item.children];
          }
        });
        lsTool.write(sessionConsts.systemMenu, JSON.stringify(routeMenus));
        this.setState({ rootRoutes: rootRoutes(routeMenus), visible: true });
      },
      err => {
        AmosAlert.error('警告', err || '获取初始化菜单失败!');
      }
    );
  }
  filterSystemMenus = (menus = []) => {
    return menus.filter(menu => menu.permissionType === 'MENU');
  }
  render() {
    if (this.state.visible){
      return (
        <Provider store={store}>
          <Router history={history} routes={this.state.rootRoutes} />
        </Provider>
      );
    } else {
      return null;
    }
  }
}

const main = support ? <App /> : <DownloadBrowsers />;

render(main, document.getElementById('app'));
