import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { browserHistory, Link } from 'amos-react-router';
import { utils } from 'amos-tool';
//  import MainFrame from 'amos-security/lib/view/mainframe';
import formatUrl from 'amos-processor/lib/utils/urlFormat';
import { Spin, Breadcrumb } from 'amos-framework';
import Icon from 'amos-icon';
import MainFrame from './Frame';
// import { Menu } from 'amos-framework';
import { secExtUrl, SecurityUrl } from './../../consts/urlConsts';
// import Help from './extratools/Help';
import getLastRoute from '../../routes/breadcrumb.config';
import { currentUserAction } from './../../services/securityService';
import { updateLinkCss } from './../common1/skin/invokeSkin';
import ThemeConsts from '../../consts/themeConsts';
import { Store } from 'amos-tool';
import { searchMenusByRoleAction } from '../../services/securityService';


const lsTool = Store.lsTool;
 
class RootView extends Component {

  static propTypes = {
    children: PropTypes.any
  };

  constructor(props) {
    super(props);
    this.breadItems = [];
    this.state = {
      siderMenusList: [],
      selectedSubMenuKey: 'patrol',
      extendSystem: [],
      loading: false,
      company: ''
    };
  }

  componentWillMount() {
    window.setLoading = this.onSettingLoading;
    //const company = window.localStorage.getItem('company');
    const company= lsTool.read('curCompanyName');
    currentUserAction().then(d => {
      window.localStorage.setItem('user', JSON.stringify(d));
      this.setState({ company: company, userName: d.userName });
    });
    // currentCompanyAction().then(d => {
    //   window.localStorage.setItem('company', JSON.stringify(d.company));
    //   window.localStorage.setItem('user', JSON.stringify(d.user));
    //   this.setState({ company: company.companyName, userName: d.user.name });
    // });
    updateLinkCss(`/themes/${window.CheckDefaultTheme}.css`);
  }

  onSettingLoading = (isLoading) => {
    this.setState({ loading: isLoading });
  }

  onOpenDefaultPage = (menus) => {
    // open first url
    if (location.pathname === '/main'){

      const item = menus.filter(e => e.path)[0] || {};
      if (!utils.isEmpty(item)){
        if (item.path){
          browserHistory.push(item.path);
          this.setState({ siderMenusList: item.children || [] });
        }
      }
    }
    this.setState({ extendSystem: menus });
  }

  
  getFrameConfig = () => {
    let roleSeq= lsTool.read('selectedRole');
    return {
    
      //opSearchMenusUrl: formatUrl(secExtUrl.opSearchMenusUrl, { nodeName: '', type: window.permissionType }),
     // opSearchMenusUrl: formatUrl(secExtUrl.curRoleMenusUrl),//根据角色查询菜单

      opSearchMenusUrl:formatUrl(secExtUrl.permissionsMenusUrl, { roleSeq }),
      // logoImg: '/src/assets/logo/maaslogo2.png',
      defaultLink: null,//此属性表示点击logo页面跳转的路由，设为null则点击无效
      loginLink: '/login'


      
    };

    
  }

  getSysToolProps = () => {
    return {
      userPic: '/src/assets/user/normal.png',
      loginOutUrl: SecurityUrl.loginOutUrl,
      userInfoLink: '/main/securityConfig',
      extraTools: this.renderExtraTools(),
      externalSub: this.renderExtraSub(),
      userExtra: true
    };
  }


  getBreadcrumb = (BreadArr) => {

    return (<Breadcrumb itemRender={this.itemRender} routes={BreadArr} />);
  }

  itemRender = (route, params, routes, paths) => {
    const last = routes.indexOf(route) === routes.length - 1;
    if (route.frontComponent === 'patrol') {
      return last ? <span><Icon icon="danwei" color={ThemeConsts[window.CheckDefaultTheme]} />首页</span> : <Link to={route.path}><Icon icon="danwei" color={ThemeConsts[window.CheckDefaultTheme]} />首页</Link>;
    }
    return last ? <span>{route.permissionName}</span> : <Link to={route.path}>{route.permissionName}</Link>;
  }

  renderExtraSub = () => {
    return [];
  }

  renderExtraTools = () => {
    return [
     // <MenuItem key="out" onClick={this.clickTestMenu}><Help /></MenuItem>
    ];
  }

  render() {

    const frameConfig = this.getFrameConfig();
    const sysToolPorps = this.getSysToolProps();
    const { state } = this.props.location;
    let { siderMenusList, selectedSubMenuKey, extendSystem, company, userName } = this.state;
    let pathname = (window.location.pathname || '').split('?')[0];
    let BreadArr = new Array();
    if (pathname) {
      const item = extendSystem.find(e => e.path.split('/')[2] === pathname.split('/')[2]) ? extendSystem.find(e => e.path.split('/')[2] === pathname.split('/')[2]) :
      pathname.split('/')[2] === 'securityConfig' ? extendSystem.find(e => e.path.split('/')[2] === 'patrol') : undefined ;
      if (!item) {
        siderMenusList = [];
      } else {
        siderMenusList = item.children;
        BreadArr.push(item);
      }
    }
    let childArr = siderMenusList.filter(item =>  window.location.pathname === item.path);
    BreadArr = BreadArr.concat(childArr);
    let length = pathname.split('/').length;
    if (BreadArr && BreadArr.length > 1) {
      this.breadItems = BreadArr;
    }else {
      if(length >3){
        Object.assign(BreadArr, this.breadItems);
      }
    }
    const minHeight = {
      minHeight: '100%'
    };
   
    for (let i = 3; i < length; i++) {
      let isDefault = state ? false : true;
      let lastItem = getLastRoute(pathname.split('/')[i], isDefault);
      if (lastItem) {
        BreadArr.push(lastItem);
      }
    }

    return (
      <MainFrame
        {...frameConfig}
        onMenuLoadCompleted={this.onOpenDefaultPage}
        sysToolPorps={sysToolPorps}
        siderMenusList={siderMenusList}
        selectedSubMenuKey={selectedSubMenuKey}
        showSysExchange={window.isIntegrate}
        company={company}
        userName={userName}
        {...this.props}
      >
        <div className="wh-r main-frame-cardpane" style={minHeight}>
          <div className="main-frame-cardpane-breadcrumb">
            {pathname.split('/')[2] === 'securityConfig' ? '用户信息' : this.getBreadcrumb(BreadArr)}
          </div>
          <div className="main-frame-cardpane-content">
            <Spin loading={this.state.loading} className="amos-page-spin" color="#345fa6" type="scale" size="large" />
            { this.props.children }
          </div>
        </div>
      </MainFrame>
    );
  }
}

export default RootView;
