/**
 *
 * @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 RProgress from 'ray-progress';
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 * as endConf from 'amos-processor/lib/config/endconf';
// import 'amos-security/lib/style';
import rootRoutes from './../routes';
import configureStore from './../store';
import { getSystemAllMenu } from '../services/securityService';
import SysConsts from 'amos-processor/lib/config/consts';


// import { loginAuth } from 'amos-security/lib/model/auth';

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

const store = configureStore();

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

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('systemMenu'));
      if (!systemMenu) {
        window.location.href = loginURI;
        return;
      }
      this.setState({ rootRoutes: rootRoutes(systemMenu), visible: true });
      return;
    }else{
      lsTool.write(SysConsts.token, token);
    }
    getSystemAllMenu(token).then(
      menus => {
        let systemMuens = this.filterSystemMenus(menus);
        let routeMenus = [];
        systemMuens.forEach(item => {
          if (item.children && item.children.length > 0) {
            routeMenus = [...routeMenus, ...item.children];
          }
        });
        let a = rootRoutes(routeMenus);
        this.setState({ rootRoutes: rootRoutes(routeMenus), visible: true });
        lsTool.write('systemMenu', JSON.stringify(routeMenus));
      },
      err => {
        AmosAlert.error('警告', err || '获取初始化菜单失败!');
      }
    );
  }

  onUpdate = () => {
    RProgress.done();
    window.scrollTo(0, 0);
  };

  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} onUpdate={() => this.onUpdate()} />
        </Provider>
      );
    } else {
      return null;
    }
  }
}

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

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

// 开发模式下开启 热加载 (不需要开启时，屏蔽一下代码即可)
if (module.hot) {
  module.hot.accept();
}
