import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { utils } from 'amos-tool';
import { browserHistory } from 'amos-react-router';
import { Menu, User } from 'amos-framework';
import { getCurrentUser } from './../../../services/securityService';

class ExtraTools extends Component {
  static propTypes = {
    userPic: PropTypes.string,
    loginOutUrl: PropTypes.string,
    showText: PropTypes.bool,
    isLoginout: PropTypes.bool,
    // 权限相关，主要封装注销、清理reducer
    authProps: PropTypes.shape({
      logout: PropTypes.func,
      sweepReducers: PropTypes.func
    }),
    onNavItemClick: PropTypes.func,
    // 用户按钮额外内容
    userExtra: PropTypes.oneOfType([PropTypes.node, PropTypes.element, PropTypes.bool]),
    userInfoLink: PropTypes.string,
    // [MenuItem, MenuItem, ... ]
    extraTools: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.node, PropTypes.element]))
  };

  static defaultProps = {
    userInfoLink: '/main/userinfo'
  };

  constructor(props) {
    super(props);
    this.state = {
      userInfo: {}
    };
  }

  componentDidMount() {
    this.loadUserInfo();
  }


  loadUserInfo = () => {
    getCurrentUser().then(d => {
      this.setState({
        userInfo: d
      });
    });
  }

  handleClickUser = () => {
    const { userInfo } = this.state;
    const { userInfoLink, onNavItemClick, userPic } = this.props;
    onNavItemClick && onNavItemClick({});
    browserHistory.push({
      pathname: userInfoLink,
      state: {
        userId: userInfo.userId,
        userPic
      }
    });
  };

  handleLogOut = () => {
    const { userInfo } = this.state;
    const { loginOutUrl, authProps } = this.props;
    const { logout, sweepReducers } = authProps;
    logout && logout(loginOutUrl, userInfo.userId);
    sweepReducers && sweepReducers();
    window.localStorage.removeItem('cityLine');
  };

  render() {
    const { userInfo } = this.state;
    const { showText, userPic, userExtra, extraTools } = this.props;

    const cls = classnames('sys-tools', {
      'sys-tools-min': !showText
    });

    let userContent;
    if (userExtra) {
      userContent = utils.isBoolean(userExtra) ? (
        <ul>
          <li className="modify-pwd" onClick={this.handleClickUser}>修改密码</li>
        </ul>
      ) : userExtra;
    }

    const basicInfo = {
      userName: userInfo.userName,
      subInfo: userInfo.nickName
    };

    return (
      <div className={cls}>
        <Menu direction="horizontal">
          {extraTools && extraTools}
        </Menu>
        <User
          userPic={userPic}
          basicInfo={basicInfo}
          handleLogOut={this.handleLogOut}
          extra={userContent}
          onAvatarClick={this.handleClickUser}
        />
      </div>
    );
  }
}

export default ExtraTools;
