import React, { useState, useCallback } from 'react';
import { Menu, message, Spin } from 'antd';
import { LogoutOutlined, KeyOutlined } from '@ant-design/icons';
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 () => {
  const loginPath = '/user/login'
  
  localStorage.removeItem('token');
  const { query = {}, pathname } = history.location;
  const { redirect } = query;
  if (window.location.pathname !== '/user/login' && !redirect) {
    history.replace({
      pathname: loginPath,
      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 }));
        loginOut();
        return;
      }

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

  const handleChangeSuccessful = () => {
    message.success('密码修改成功');
    setShowPasswordModal(false);
    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.name) {
    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.name}</span>
        </span>
      </HeaderDropdown>
      <ChangePassword
        visible={showPasswordModal}
        onCancel={() => setShowPasswordModal(false)}
        onSuccess={handleChangeSuccessful}
      />
    </>
  );
};

export default AvatarDropdown;
