import React, { useState, useCallback } from 'react';
import { LogoutOutlined, KeyOutlined } from '@ant-design/icons';
import { Avatar, Menu, message, Spin } from 'antd';
import { history, useModel } from 'umi';
import { stringify } from 'querystring';
import HeaderDropdown from '../HeaderDropdown';
import ChangePassword from './ChangePassword';
import styles from './index.less';

/**
 * 退出登录，并且将当前的 url 保存
 */
const loginOut = async (val) => {
  localStorage.removeItem('token');
  const { query = {}, pathname } = history.location;
  const { redirect } = query;
  if (window.location.pathname !== '/user/login' && !redirect) {
    if (val == 'org') {
      history.replace({
        pathname: '/user/orgLogin',
        search: stringify({
          redirect: pathname,
        }),      
      });
    } else {
      history.replace({
        pathname: '/user/login',
        search: stringify({
          redirect: pathname,
        }),
      });
    }
  }
};

const AvatarDropdown = ({ menu }) => {
  const [showPasswordModal, setShowPasswordModal] = useState(false);
  const { initialState, setInitialState } = useModel('@@initialState');

  const onMenuClick = useCallback(
    (event) => {
      const { key } = event;

      if (key === 'logout') {
        setInitialState((s) => ({ ...s, currentUser: undefined }));
        if (initialState.roleAlias == 'org') {
          loginOut('org');
        } else {
          loginOut('admin');
        }
        return;
      }

      if (key === 'changepassword') {
        setShowPasswordModal(true);
        return;
      }
    },
    [setInitialState],
  );

  const handleChangeSuccessful = () => {
    message.success('密码修改成功');
    setShowPasswordModal(false);
    setInitialState((s) => ({ ...s, currentUser: undefined }));
    loginOut();
    return;
  };

  const loading = (
    <span className={`${styles.action} ${styles.account}`}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }

  const { currentUser } = initialState;

  if (!currentUser || !currentUser.userName) {
    return loading;
  }

  const menuHeaderDropdown = (
    <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
      <Menu.Item key="changepassword">
        <KeyOutlined />
        修改密码
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="logout">
        <LogoutOutlined />
        退出登录
      </Menu.Item>
    </Menu>
  );

  return (
    <>
      <HeaderDropdown overlay={menuHeaderDropdown}>
        <span className={`${styles.action} ${styles.account}`}>
          {/* <Avatar size="small" className={styles.avatar} src={currentUser.avatar} alt="avatar" /> */}
          <span className={`${styles.name} anticon`}>{currentUser.userName}</span>
        </span>
      </HeaderDropdown>
      <ChangePassword
        visible={showPasswordModal}
        onCancel={() => setShowPasswordModal(false)}
        onSuccess={handleChangeSuccessful}
      />
    </>
  );
};

export default AvatarDropdown;
