import { Avatar, Dropdown, Menu, message, Modal } from 'antd';
import { DownOutlined, UserOutlined, UserSwitchOutlined, CarryOutOutlined, HomeOutlined, ImportOutlined } from '@ant-design/icons';
import React, { useEffect, useRef } from 'react';
import moment from 'moment'
import { connect, history, KeepAliveContext } from '@umijs/max';
import { ConnectState } from '@/models/connect';
import logo from '@/assets/logo.svg';
import './index.less';
import { getMenu, getLogout } from './services'
import { getSessionUserData, getSessionRoleData } from "@/utils/session";
import { getToSecondUrl } from '@/pages/LoadingPage/service';
import userIcon from '@/assets/user.svg';
import homeIcon from '@/assets/home.svg';
import shutdownIcon from '@/assets/shutdown.svg';
import { logout } from './services';
import cookie from 'react-cookies';
import divider from '@/assets/divider.png';
import useGoHome from '@/utils/useGoHome';

const theme = JSON.parse(PROJECT_THEME);

const GlobalHeaderRight: React.FC<{}> = (props) => {
  // let className = styles.right;
  const data = getSessionUserData();
  const roleData = getSessionRoleData();
  const [dataMenu, setDataMenu] = React.useState<any>([]);
  const urlRef = useRef(null);
  const goHome = useGoHome()
  const handelRole = (item: any) => {
    sessionStorage.setItem('roleData', JSON.stringify(item));
    sessionStorage.setItem('roleAuthority', JSON.stringify([item.roleCode]));
    const params = {
      roleIdList: [item.roleId]
    }
    history.push('/Dashboard')
    window.location.reload()
    // getMenu(params).then(res => {
    //   if (res?.code == 1) {
    //     setDataMenu(res?.data)
    //   } else {
    //     message.error("数据错误请联系管理员")
    //   }
    // })
  }
  //角色退出登录
  const toLogout = () => {
    // let _data = {
    //   mall3_token: sessionStorage.getItem('Authorization')
    // }
    // 获取用户类型，用于判断返回哪个登录页面
    const userType = localStorage.getItem('userType');
    
    Modal.info({
      title: '请确认是否退出？',
      content: false,
      onOk() {
        logout().then((res) => {
          if (res?.success) {
            // if (data?.userType == "0") {//联通智慧门户
            //   window.close();
            // } else if (data?.userType == "1") {//合作方
            //   window.close();
            // } else if (data?.userType == "2") {//专家
            //   window.location.href = "/userformal/login"
            // }
            message.success('退出登录成功');
            sessionStorage.clear();
            cookie.remove('mall3_token');
            
            // 清空用户类型
            localStorage.removeItem('userType');
            
            // 根据用户类型返回不同的登录页面
            setTimeout(() => {
              if (userType === 'internal') {
                history.push('/internal-login'); // 内部用户返回内部登录页
              } else {
                history.push('/login'); // 普通用户返回普通登录页
              }
            }, 1000);
          }
        })
      },
      closable: true,
      centered: true,
      okText: "确认退出",
      className: "layout-modal-logout",
    });
  }

  const droMenu = (
    <Menu style={{ top: "17px" }}>
      {data?.authorityList != undefined ?
        data?.authorityList?.map((item: any) => (
          <Menu.Item key={item.roleId}>
            <a target="_blank" rel="noopener noreferrer" onClick={() => handelRole(item)}>{item.roleName}</a>
          </Menu.Item>
        )) : null}
      {/* <>
        <Menu.Divider />
        <Menu.Item key="exit">
          <a key="1" onClick={() => toLogout()}>退出登录</a>
        </Menu.Item>
      </> */}
    </Menu>
  );

  useEffect(() => {
    const getUrl = async () => {
      const response = await getToSecondUrl();
      if (response?.success) {
        urlRef.current = response?.data;
      }
    }
    getUrl();
  }, [])

  return (
    <div className="top-menu" style={{ height: 56 }}>
      <div className="left-logo">
        <div className="logo-container" style={{ display: 'flex', alignItems: 'center' }}>
        <div className="logo-img">
          <img src={logo} alt="" style={{ width: '66.89px', height: '42.49px' }}/>
        </div>
          <div className="logo-text" style={{ display: 'flex', flexDirection: 'column', gap: '0' }}>
            <span style={{ fontSize: '24px', lineHeight: '24px', fontWeight: 700, letterSpacing: '2.5px' }}>中远海运集团采购信息系统</span>
            <span style={{ lineHeight: 'normal', fontSize: '12px', fontWeight: 400 }}>COSCO SHIPPING Group Procurement Information System</span>
          </div>
          <div style={{ margin: '0 9px' }}>
            <img src={divider} alt="" style={{ width: '1px', height: '100%', margin: 0 }}/>
          </div>
          <div className="logo-text" style={{ display: 'flex', flexDirection: 'column', gap: '0' }}>
            <span style={{ fontSize: '24px', lineHeight: '24px', fontWeight: 700, letterSpacing: '2.5px' }}>{roleData?.roleName}</span>
            <span style={{ lineHeight: 'normal', fontSize: '12px', fontWeight: 400 }}>{roleData?.roleCode}</span>
          </div>
        </div>
      </div>
      <ul className="right-btns">
        {/* <li><ImportOutlined /><a onClick={() => { urlRef.current && window.open(urlRef.current); }}>交易平台2.0</a></li> */}
        <li>
          <Avatar size="small" src={userIcon} style={{ width: '30px' }} />
          <Dropdown overlay={droMenu}>
            <a className="antd-dropdown-link" style={{ color: theme['text-color'], verticalAlign: '-2px' }}>
              {data?.fullName} <DownOutlined />
            </a>
          </Dropdown>
        </li>
        <li>
          <img src={homeIcon} style={{width: 13, cursor: 'pointer'}} alt="dashboard" onClick={() => {
            goHome()
          }} />
        </li>
        <li style={{ paddingRight: 16 }}>
          <img src={shutdownIcon} style={{width: 14, cursor: 'pointer' }} alt="shutdown" onClick={() => toLogout()}/>
        </li>
        {/* <li><CarryOutOutlined />{moment().format("YYYY-MM-DD")}</li> */}
        {/* {data?.organizationName == null ? null : (<li><UserSwitchOutlined />{data?.organizationName}</li>)} */}
        

      </ul>

    </div>
  );
};
export default connect(({ settings }: ConnectState) => ({
  theme: settings.navTheme,
  layout: settings.layout,
}))(GlobalHeaderRight);
