import { LogoutOutlined, UserOutlined } from '@ant-design/icons';
import { message } from 'antd';
import { history, useModel } from '@umijs/max';
import { Avatar, Menu } from 'antd';
import type { ItemType } from 'antd/lib/menu/hooks/useItems';
import type { MenuInfo } from 'rc-menu/lib/interface';
import React, { useCallback, useState } from 'react';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
export type GlobalHeaderRightProps = {
  menu?: boolean;
};

/**
 * 退出登录，并且将当前的 url 保存
 */
const loginOut = async () => {
  // await outLogin();
  const urlParams = new URL(window.location.href).searchParams;
  /** 此方法会跳转到 redirect 参数所在的位置 */
  const redirect = urlParams.get('redirect');
  // Note: There may be security issues, please note
  // 从 sessionStorage 删除保存的数据
  sessionStorage.removeItem('Authorization');
  // sessionStorage.removeItem('password');
  // sessionStorage.removeItem('username');
  message.info('账户已退出');

  if (window.location.pathname !== '/user/login' && !redirect) {
    history.replace({
      pathname: '/user/login',
    });
  }
};

const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu }) => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [httpUrl, setHttpUrl] = useState('http://192.168.0.50:8080/');
  const [name, setName] = useState('');

  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const { key } = event;
      if (key === 'logout') {
        setInitialState((s) => ({ ...s, currentUser: undefined }));
        loginOut();
        return;
      }
      history.push(`/user/${key}`);
    },
    [setInitialState],
  );

  // 从 sessionStorage 获取数据
  const Authorization = window.sessionStorage.getItem('Authorization')
  const username = window.sessionStorage.getItem('username')

  // 未登录 返回
  if (!Authorization) {
    history.replace({
      pathname: '/user/login',
    });
  }

  const menuItems: ItemType[] = [
    {
      key: 'center',
      icon: <UserOutlined />,
      label: '个人中心',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
    },
  ];

  const menuHeaderDropdown = (
    <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick} items={menuItems} />
  );

  return (
    <HeaderDropdown overlay={menuHeaderDropdown}>
      <span className={`${styles.action} ${styles.account}`}>
        <Avatar
          size="small"
          style={{ backgroundColor: '#b37d12' }} 
          className={styles.avatar}
          icon={<UserOutlined />} 
          alt="avatar"
        />
        <span className={`${styles.name} anticon`}>{username}</span>
      </span>
    </HeaderDropdown>
  );
};

export default AvatarDropdown;
