/**
 *
 * @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 SysConsts from 'amos-processor/lib/config/consts';
import { DownloadBrowsers } from 'amos-framework';
import * as endConf from 'amos-processor/lib/config/endconf';
import rootRoutes from './../routes';
import configureStore, { configureStoreWithDev } from './../store';
import { sessionConsts } from '../consts/storageConsts';
import { getSystemAllMenu } from '../services/securityService';
import { AmosAlert } from 'amos-framework';
import { secExtUrl } from 'CONSTS/urlConsts';
import { amosRequest } from 'amos-processor';

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

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

const store = configureStoreWithDev({});

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



    



    // amosRequest(secExtUrl.systemMenusUrl, {
    //   method: 'GET',
    //   headers:{
    //     'appKey': 'YH-PATROL',
    //     'product': 'YH-PATROL_WEB',
    //     //'product': 'YH-PATROL_WEB,YH-PATROL_APP',
    //     'token': token
    //   },
    // }).then(data => {
    //   if(!data.error){
    //     let menus = data.result ? data.result.filter(e => e.appCode === "YH-PATROL") : {};
    //     this.setState({ rootRoutes: rootRoutes(menus), visabled: true });
    //     lsTool.write(sessionConsts.systemMenu, JSON.stringify(menus));
    //   }else{
    //     AmosAlert.error('警告', err || '获取初始化菜单失败!');
    //   }
    // });

    //let token = LocationParam.getLocationParamByName('token') || 0;
    // let code = LocationParam.getLocationParamByName('code');
    // let userId = LocationParam.getLocationParamByName('userId');
    
    // debugger;
    // if (!(code || userId)) {
    //   let systemMenu = JSON.parse(lsTool.read(sessionConsts.systemMenu));
    //   if (!systemMenu) {
    //     window.location.href = loginURI;
    //     return;
    //   }
    //   this.setState({ rootRoutes: rootRoutes(systemMenu), visabled: true });
    //   return;
    // }

    // getSystemAllMenu(code, userId).then(
    //   menus => {
    //     let systemMuens = this.filterSystemMenus(menus);
    //     let routeMenus = [];
    //     systemMuens.forEach(item => {
    //       if (item.children && item.children.length > 0) {
    //         routeMenus = [...routeMenus, ...item.children];
    //       }
    //     });
    //     debugger;
    //     this.setState({ rootRoutes: rootRoutes(routeMenus), visabled: true });
    //     lsTool.write(sessionConsts.systemMenu, JSON.stringify(routeMenus));
    //   },
    //   err => {
    //     AmosAlert.error('警告', err || '获取初始化菜单失败!');
    //   }
    // );
  }

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

  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() {
    console.log(this.state.rootRoutes);
    return (
      this.state.visabled && (support ?
        <Provider store={store}>
       
          <Router history={history} routes={this.state.rootRoutes} onUpdate={() => this.onUpdate()} />
        </Provider>
        :
        <DownloadBrowsers />)
    );
  }
}

render(<App />, document.getElementById('app'));

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