import React, { useEffect, useState } from 'react';
//导入logo图片
import LogoImg from '@/assets/img/logo.png';
//导入菜单组件
import Language from './Language';
import User from './User';
import { history } from 'umi';
import './layout.less';
import { Logout  } from '@/servers/api/login';

const HeaderComponent: React.FC = () => {
  // 用 state 保存 userId
  const [userId, setUserId] = useState(() => sessionStorage.getItem('userId'));

  const handLogout = () => {
    Logout()
    sessionStorage.clear();
    history.replace('/login');
  }

  useEffect(() => {
    // 定义一个方法用于手动刷新 userId
    const refreshUserId = () => setUserId(sessionStorage.getItem('userId'));
    // 登录后你可以手动调用 refreshUserId
    // 或者监听页面 storage 事件（多窗口/多tab同步）
    window.addEventListener('storage', refreshUserId);
    // 页面内操作，比如登录成功后，也可以在登录回调里调用 setUserId
    return () => window.removeEventListener('storage', refreshUserId);
  }, []);

  return (
    <div className="headerComponent">
      <img className="logo" src={LogoImg} alt="logo" />
      <div className="flex">
        <Language />
        {!userId ? (
          <User />
        ) : (
          <div style={{cursor: 'pointer'}} onClick={handLogout}>退出</div>
        )}

      </div>
    </div>
  );
};
export default HeaderComponent;
