import React, { useEffect, useState } from 'react';
import { Link, useIntl, connect, history } from 'umi';
import { Dropdown, Button, Modal } from 'antd';
import { DownOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import type { ConnectProps, Dispatch } from 'umi';
import type { UserModelState } from '@/models/user';
import { message } from 'antd';

interface PageProps extends ConnectProps {
  user: UserModelState; // dva model状态
  dispatch: Dispatch; // dva dispatch方法
}
const User: React.FC<PageProps> = ({ user, dispatch }) => {

  
  const intl = useIntl();
  useEffect(() => {
    if (!user.userInfo) {
      const userinfoStr = sessionStorage.getItem('Userinfo');
      if (userinfoStr) {
        try {
          const userInfo = JSON.parse(userinfoStr);
          dispatch({
            type: 'user/saveUserInfo',
            payload: userInfo,
          });
        } catch (e) {
          // 解析失败时可以报错提示
          console.error('Userinfo 解析失败', e);
        }
      }
    } else  if (user.token) {
      dispatch({
        type: 'user/fetchUserInfo',
      });
    }
  }, [user.token]);
  const handleMenuClick = (e: any) => {
    if (e.key === 'logout') {
      Modal.confirm({
        title: '确定退出登录吗？',
        icon: <ExclamationCircleOutlined />,
        content: '退出登录后，您将需要重新登录',
        onOk() {
          dispatch({
            type: 'user/logout',
          }).then(() => {
            sessionStorage.clear();
            message.success('退出登录成功');
            history.push('/login');
          });
        },
        onCancel() {
          return;
        },
      });
    } else if(e.key === 'profile') {
      console.log(111);
      
      // history.push('/profile');
    }
  };
  return (
    <div className="user">
      {user.userInfo?.fullName ? (
        <Dropdown
          trigger={['hover']}
          menu={{
            items: [
              {
                key: 'profile',
                label: '个人中心',
              },
              {
                key: 'logout',
                label: '退出登录',
              },
            ],
            onClick: handleMenuClick,
          }}
        >
          <Button type="link">
            {`${user.userInfo?.fullName}`}
            <DownOutlined />
          </Button>
        </Dropdown>
      ) : (
        <Link to={'/login'}>{intl.formatMessage({ id: '登录' })}</Link>
      )}
    </div>
  );
};

export default connect(({ user }: { user: UserModelState }) => ({ user }))(User);
