import { Avatar, Icon, Menu, Spin } from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
import React from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import ShowPassword from './ShowPassword'

class AvatarDropdown extends React.Component {

  constructor(props) {
    super()
    this.state = { visible: false }
  }

  onMenuClick = event => {
    const { key } = event;

    if (key === 'logout') {
      console.log(this.props)
      const { dispatch } = this.props;

      if (dispatch) {
        dispatch({
          type: 'login/logout',
        });
      }

      return;
    }

    if (key === 'updatePassword') {
      this.setState({ visible: true })
      return;
    }

    router.push(`/account/${key}`);
  };

  onCancel = (e) => {
    this.setState({ visible: false })
  }

  onReset = (e) => {
    const { dispatch } = this.props;

      if (dispatch) {
        dispatch({
          type: 'login/logout',
        });
      }

      return;
  }
  
  render() {
    const {
      currentUser = {
        avatar: '',
        name: '',
      },
      menu,
    } = this.props;
    const menuHeaderDropdown = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={this.onMenuClick}>
        {menu && (
          <Menu.Item key="center">
            <Icon type="user" />
            <FormattedMessage id="menu.account.center" defaultMessage="account center" />
          </Menu.Item>
        )}
        {menu && (
          <Menu.Item key="settings">
            <Icon type="setting" />
            <FormattedMessage id="menu.account.settings" defaultMessage="account settings" />
          </Menu.Item>
        )}
        {menu && <Menu.Divider />}
        <Menu.Item key="updatePassword">
          <Icon type="key" />
          <FormattedMessage id="menu.account.updatePassword" defaultMessage="updatePassword" />
        </Menu.Item>   
        <Menu.Item key="logout">
          <Icon type="logout" />
          <FormattedMessage id="menu.account.logout" defaultMessage="logout" />
        </Menu.Item>
      </Menu>
    );
    return currentUser && currentUser.userName ? (
      <>
        <HeaderDropdown overlay={menuHeaderDropdown}>
          <span className={`${styles.action} ${styles.account}`}>
            <Avatar size="small" className={styles.avatar} src={currentUser.channelImg} alt="avatar" />
            <span className={styles.name}>{currentUser.userName}</span>
          </span>
        </HeaderDropdown>
        <ShowPassword visible={this.state.visible} onCancel={(e) => this.onCancel(e)} onReset={(e => this.onReset(e))} />
      </>  
    ) : (
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(AvatarDropdown);
