/**
 *
 * @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 rootRoutes from './../routes/asyncRoutes';
import configureStore from './../store';
import beforeRender from './beforeRender';
import { getSystemAllMenu } from '../services/securityService';
import { sessionConsts } from '../consts/storageConsts';
import SysConsts from 'amos-processor/lib/config/consts';


// 引入主体样式文件（打包需要改此文件，记住）
import './../styles';

beforeRender();

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(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];
          }
        });
        this.setState({ rootRoutes: rootRoutes(routeMenus), visible: true });
        lsTool.write(sessionConsts.systemMenu, JSON.stringify(routeMenus));
      },
      err => {
        AmosAlert.error('警告', err || '获取初始化菜单失败!');
      }
    );
  }

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

  // filterSystemMenus = (menus = []) => {
  //   return menus.filter(menu => menu.permissionType === 'MENU');
  // }

  filterSystemMenus = (menus = []) => {
    let menus1 =this.get(menus);
    return menus1.filter(menu => menu.permissionType === 'MENU');
  }

  get= (res) =>{
    let tmp=[]
    for(var item11 of res){
      
      if(item11.children!=null&&item11.children.length>0){
        if(item11.children[0].permissionType==='BUTTON'){
          item11.children=[]
        }else{
          item11.children=this.get(item11.children);
        }
      }   
      tmp.push(item11)
       
    }
    return tmp;
    }



  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'));
