import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { browserHistory } from 'amos-react-router';
import { Layout } from 'amos-antd';
import { Dropdown, Avatar, Menu  } from 'amos-framework';
import Icon from 'amos-icon';
import { utils } from 'amos-tool';
import enhanceAuthorization from 'amos-security/lib/view/auth/enhanceAuthorization';
import { opSearchMenusAction } from 'amos-security/lib/services';
import SiderMenus from './SiderMenus';
import ThemeConsts from '../../consts/themeConsts';
import { currentUser } from 'amos-security/lib/model/auth';
import { Store } from 'amos-tool';
import { searchMenusByRoleAction } from '../../services/securityService';
import SysConsts from 'amos-processor/lib/config/consts';
import { amosRequest } from 'amos-processor';
import formatUrl from 'amos-processor/lib/utils/urlFormat';
import { secExtUrl } from 'CONSTS/urlConsts';
// import './style/index.scss';

const lsTool = Store.lsTool;

const { Content, Sider } = Layout;
const width = 180;
const collapsedWidth = 45;
const menus = [
  { key: '1', text: '个人信息', icon: 'danwei' },
  { key: '2', text: '注销', icon: 'yichu' }
];
/**
 * root
 *
 * @class RootView
 * @extends {Component}
 */
class RootView extends Component {
  static propTypes = {
    children: PropTypes.node,
    logoImg: PropTypes.string,
    opSearchMenusUrl: PropTypes.string,
    // 菜单获取完成之后的操作[可进行打开默认页面] (menus) => {}
    onMenuLoadCompleted: PropTypes.func,
    defaultLink: PropTypes.string,
    loginLink: PropTypes.string,
    sysToolPorps: PropTypes.object,
    isLoginout: PropTypes.bool,
    logout: PropTypes.func,
    sweepReducers: PropTypes.func,
    siderMenusList: PropTypes.array,
    selectedSubMenuKey: PropTypes.string,
    showSysExchange: PropTypes.bool,
    externalSys: PropTypes.array,
    onLogoClick: PropTypes.func
  };

  static defaultProps = {
    defaultLink: '/main',
    loginLink: '/login',
    onMenuLoadCompleted: () => {}
  };

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

  componentDidMount() {
    this.onPermissionFetch();
  }

  componentWillReceiveProps(nextProps) {
    const { loginLink } = this.props;
    if (nextProps.isLoginout) {
      this.context.router ? this.context.router.push(loginLink) : browserHistory.push(loginLink);
    }
    // 触发菜单转换
    if (nextProps.siderMenusList && this.props.siderMenusList !== nextProps.siderMenusList) {
      this.setState({
        siderMenusList: nextProps.siderMenusList
      });
    }
    // 触发sider menu 选中
    if (nextProps.selectedSubMenuKey && this.props.siderMenusList !== nextProps.siderMenusList) {
      this.selectedSubMenuKey = nextProps.siderMenusList;
    }
  }

  onPermissionFetch = () => {

    const { onMenuLoadCompleted } = this.props;
    let roleSeq = lsTool.read('selectedRole');
    const token = lsTool.read(SysConsts.token);
    searchMenusByRoleAction(roleSeq).then(res =>{
      console.log('searchMenusByRoleAction');




      let menus =this.get(res);
      if(menus!=null&&menus.length>0){
        var arr2 = []
        arr2 = menus[0].children.filter(function(item) {
          return item.isRoute ===true;
        })

        menus[0].children=arr2;
      }
      window.localStorage.setItem('permissionsMenus', JSON.stringify(menus));
      const sliderMenus = this.reloadSliderMenu(menus);
      this.setState({
        extendSystem: menus,
        siderMenusList: sliderMenus
      }, () => onMenuLoadCompleted(menus));
    });
  };




  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;
    }




  onCollapse = () => {
    this.setState({ collapsed: !this.state.collapsed });
  };

  onLogoClick = () => {
    const { defaultLink } = this.props;
    if (defaultLink){
      this.context.router ? this.context.router.push(defaultLink) : browserHistory.push(defaultLink);
    }

    this.props.onLogoClick && this.props.onLogoClick();
  }

  reloadSliderMenu = navs => {
    const url = location.pathname;

    const calc = p => {
      const result = p.substring(0, p.lastIndexOf('/'));
      return utils.isEmpty(result) ? p : result;
    };

    const parentUrl = calc(url);

    if (!utils.isEmpty(url)) {
      const item = navs.find(e => e.path === url || calc(e.path) === parentUrl) || {};
      const menus = item.children;
      return menus;
    }
    return [];
  };

  handleMenuClick = (menu = {}) => {
    this.setState({ siderMenusList: menu.children });
  };

  onMouseLeave =()=>{
    this.setState({ display: 'none' });
  }

  onMouseOver =()=>{
    this.setState({ display: 'block' });
  }

  onMenuClick =(key)=>{
    if (key === '1'){//用户信息
      const { userInfoLink } = this.props.sysToolPorps;
      browserHistory.push(userInfoLink);
    } else if (key === '2'){//注销
      this.handleLogOut();
    }
  }

  renderMenu = (subSys) => {
    return (
      <Menu>
        {this.getMenuItems(subSys)}
      </Menu>
    );
  }

  getMenuItems = () => {
    let items = new Array();
    for ( let i = 0; i < menus.length; i++) {
      let menu = menus[i];
      items.push(<Menu.Item onClick={() => this.onMenuClick(menu.key)}>{menu.text}</Menu.Item>);
    }
    return items;
  }

  handleLogOut = () => {
    const { sysToolPorps, sweepReducers, logout } = this.props;
    const { loginOutUrl } = sysToolPorps;
    const user = currentUser();
    logout && logout(loginOutUrl, user.userId);
    sweepReducers && sweepReducers();
  }

  render() {
    const { children, logoImg, sysToolPorps, logout, sweepReducers, userName, showSysExchange, company } = this.props;
    const { collapsed, extendSystem, siderMenusList } = this.state;
    const authProps = {
      logout,
      sweepReducers
    };
    let isSub = window.localStorage.getItem('isSub');

   // 获取部门名称
     let depname='';
     let keyd= lsTool.read('departmentname');

     if(keyd!='null'){
      depname='-'+keyd;
     }



    // window.isDisplayQR 是否显示二维码及注销功能
    return (
      <div className="patrol-view-port">
        {
          !isSub ? (
            <header className="patrol-view-header"  >
              {/* <Icon icon="logo" /> */}
                {/* <img src='/src/assets/auth/logs.jpg'></img> */}
               <span>{company +depname|| ''}</span>
              {window.isDisplayQR ? <div className="patrol-view-header-img">
                <Icon prefix='amosicon' icon="shouji" style={{ display: 'inline-block',fontSize: 15, color: 'white' }} />
                <span className="patrol-view-header-front" onMouseLeave={this.onMouseLeave} onMouseOver={this.onMouseOver} >APP下载&nbsp;</span>
                <Icon prefix='amosicon' icon="down" style={{ display: 'inline-block',fontSize: 14, color: 'white' }}  />
                <img src='/src/assets/auth/appUpload.png' className="upload-img" alt=''style={{ display: this.state.display }} />&nbsp;&nbsp;
                {window.isUserInfo?<Dropdown
                  className='header-drop-down'
                  customContent={this.renderMenu()}
                >
                  <Avatar src={sysToolPorps.userPic} />
                </Dropdown>:''}
              </div> : null}
            </header>) : null
        }
        <div className="patrol-view-content-body">
          <Layout style={{ height: '100%' }}>
            {siderMenusList &&
              siderMenusList.length > 0 && (
                <Sider trigger={null} collapsible collapsed={collapsed} width={width} collapsedWidth={collapsedWidth} className="amos-main-sider">
                  <div onClick={this.onCollapse} className="sidebar-fold">
                    <Icon icon={collapsed ? 'sandaogangwutianchong' : 'sandaogangwutianchong'} />
                    { !collapsed && <span>智能巡检</span> }
                  </div>
                  <div className="sidebar-user">
                    <Icon icon="user" color={ThemeConsts[window.CheckDefaultTheme]} />
                    { !collapsed && <span>您好！{userName}</span> }
                  </div>
                  <div className="sidebar-menus">
                    <SiderMenus collapsed={collapsed} siderMenusList={siderMenusList} selectedSubMenuKey={this.selectedSubMenuKey} />
                  </div>
                </Sider>
              )}
            <Layout style={{ height: '100%', width: `calc(100% - ${collapsed ? 45 : 180}px)` }}>
              <Content style={{ height: '100%' }}>
                <div className="amos-main-content" style={{ width: '100%', height: '100%' }}>
                  {children}
                </div>
              </Content>
            </Layout>
          </Layout>
        </div>
      </div>
    );
  }
}

export default enhanceAuthorization(RootView);
