import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { browserHistory } from 'amos-react-router';
import { Layout } from 'amos-framework';
import { Store, utils } from 'amos-tool';
import SysConsts from 'amos-processor/lib/config/consts';
import { getPermissionsMenus } from '../../../services/securityService';
import Header from './Header';
import './style/index.scss';
import { isArray } from 'amos-pluggable/lib/_utils';

const { Content } = Layout;
const lsTool = Store.lsTool;
/**
 * root
 *
 * @class MainFrame
 * @extends {Component}
 */
class MainFrame extends Component {
  static propTypes = {
    children: PropTypes.node,
    logoImg: PropTypes.string,
    logoExtra: PropTypes.oneOfType([
      PropTypes.node,
      PropTypes.bool
    ]),
    opSearchMenusUrl: PropTypes.string,
    // 菜单获取完成之后的操作[可进行打开默认页面] (menus) => {}
    onMenuLoadCompleted: PropTypes.func,
    defaultLink: PropTypes.string,
    // 执行注销是跳转的路由，或者注销之后手动执行的方法
    loginLink: PropTypes.oneOfType([
      PropTypes.func
    ]),
    sysToolPorps: PropTypes.object,
    isLoginout: PropTypes.bool,
    logout: PropTypes.func,
    sweepReducers: PropTypes.func,
    selectedSubMenuKey: PropTypes.string,
    onLogoClick: PropTypes.func,
    renderSubmenu: PropTypes.func,
    // 菜单宽度
    menuWidth: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number
    ]),
    // 系统中使用到的 amos-icon组件，设置统一的 prefix，默认为 `amosicon`
    iconPrefix: PropTypes.string
  };

  static defaultProps = {
    iconPrefix: 'amosicon',
    defaultLink: '/main',
    loginLink: () =>{},
    onMenuLoadCompleted: () => {},
    menuWidth: '160px',
    logoImg: require('./../../../assets/logo/amos-logo.png')
  };

  constructor(props) {
    super(props);
    this.state = {
      collapsed: false,
      extendSystem: [],
      defaultHomeUrl: '',
      is3dview:true
    };
    this.selectedSubMenuKey = '';
  }

  componentDidMount() {
    this.onPermissionFetch();
  }

  componentWillReceiveProps(nextProps) {
    const { loginLink } = this.props;
    if (nextProps.isLoginout) {
      if (utils.isFunction(loginLink)){
        loginLink();
      }
    }
  }

  onPermissionFetch = () => {
    const { onMenuLoadCompleted } = this.props;
    let role = lsTool.read('selectedRole');
    getPermissionsMenus(role).then((menus = []) => {
      let userMenus = [];
      isArray(menus) && menus.forEach(element => {
        if (element.permissionType === 'MENU' && element.path === 'biz') {
          userMenus.push(element.children);
        } else if(element.permissionType === 'MENU' && element.path === 'main') {
          userMenus.push(element.children);
        }
      });
      const lsTool = Store.lsTool;
      lsTool.write(SysConsts.permissions, JSON.stringify(menus));
      let bizMenus = [];
      let allMenus = [];
      for (let i = 0; i < userMenus.length; i++) {
        for ( let j = 0; j < userMenus[i].length; j++) {
          allMenus.push(userMenus[i][j])
        }
      }
      bizMenus = this.filterMenusButton(allMenus);
      this.setState({
        extendSystem: bizMenus
      }, () => onMenuLoadCompleted(bizMenus));
    });
  };

  onLogoClick = () => {
    const { defaultLink } = this.props;
    // if (defaultLink){
    //   this.context.router ? this.context.router.push(defaultLink) : browserHistory.push(defaultLink);
    // }
    browserHistory.push('/main/3dview');
    this.props.onLogoClick && this.props.onLogoClick();
  }

  filterMenusButton = (menus) => {
    return menus.filter(
      menu => {
        if (menu.children && menu.permissionType === 'SUBMENU') {
          menu.children = this.filterMenusButton(menu.children);
          return true;
        }
        if (!menu.children && menu.permissionType === 'SUBMENU') {
          return true;
        }
        if (!menu.children || menu.permissionType === 'BUTTON') {
          return false;
        }
      }
    );
  }
  is3dviewChange=(falg)=> {
    this.setState({
      is3dview:falg
    })
  }

  render() {
    const { children, logoImg, sysToolPorps, logout, sweepReducers, logoExtra, renderSubmenu, menuWidth, iconPrefix } = this.props;
    const { extendSystem, is3dview } = this.state;
    const authProps = {
      logout,
      sweepReducers
    };
    return (
      <div className="view-port">
        <Header
          navs={extendSystem}
          logoText={'运维安全预控执行系统'}
          onLogoClick={this.onLogoClick}
          onNavItemClick={this.handleMenuClick}
          renderSubmenu={renderSubmenu}
          authProps={authProps}
          logoExtra={logoExtra}
          menuWidth={menuWidth}
          iconPrefix={iconPrefix}
          {...sysToolPorps}
          is3dviewChange={this.is3dviewChange}
        />
        <div className={is3dview?'content-body indexContent': 'content-body'}>
          <Layout style={{ height: '100%' }}>
            <Content style={{ height: '100%' }}>
              <div className="amos-main-content" style={{ width: '100%', height: '100%' }}>
                {children}
              </div>
            </Content>
          </Layout>
        </div>
      </div>
    );
  }
}

export default MainFrame;
