import { userLogout } from '@/services/common/login';
import { CURRENT_MENU,CURRENT_USER,TOKEN } from '@/utils/constant';
import { SelectLang,useNavigate } from '@@/exports';
import {
DownOutlined,
LockOutlined,
LogoutOutlined,
UserOutlined,
} from '@ant-design/icons';
import { useIntl,useModel } from '@umijs/max';
import type { MenuProps } from 'antd';
import { AutoComplete,Button,Dropdown,Input,Space,message } from 'antd';
import 'dayjs/locale/zh-cn';
import React,{ useState } from 'react';
import { Link } from 'react-router-dom';
import { FormattedMessage } from 'umi';
import icon from '../../assets/user.png';
import styles from './index.less';
import searchIcon from '@/assets/search.svg';

export type SiderTheme = 'light' | 'dark';

const GlobalHeaderRight: React.FC = () => {
  const intl: any = useIntl();
  const navigate = useNavigate();
  const { initialState, setInitialState } = useModel('@@initialState');
  const menuTree = initialState?.menuData || [];
  const [menuOption, setMenuOption] = useState<any[]>([]);
  const [menuValue, setMenuValue] = useState<string>('');
  const [isClose, setIsClose] = useState<boolean>(true);
  const textColorStyles = {
    color: '#fff',
  };
  const langStyles = {
    color: '#fff',
    width: '32px',
    height: '32px',
    // backgroundColor: 'rgb(242, 243, 245)',
    borderRadius: '18px'

  };
  let person = 'admin';

  if (!initialState || !initialState.settings) {
    return null;
  } else {
    person = initialState?.currentUser?.nickname || 'user';
  }

  const { navTheme, layout } = initialState.settings;
  let className = styles.right;

  if ((navTheme === 'realDark' && layout === 'top') || layout === 'mix') {
    className = `${styles.right}  realDark`;
  }

  const logout = () => {
    userLogout().finally(() => {
      localStorage.removeItem(TOKEN);
      localStorage.removeItem(CURRENT_USER);
      localStorage.removeItem(CURRENT_MENU);
      setInitialState({
        ...initialState,
        currentUser: undefined,
        menuData: undefined,
      });
      navigate('/login');
    });
    // await userLogout();
  };

  const menuClick = (e:any) => {
    if(e.key === 'logout') {
      logout();
    } 
  };

  //获取用户首字母
  const userFirstWord = () => {
    return person;
    // if (person) {
    //   return person.toUpperCase();
    // } else {
    //   return 'M';
    // }
  };
  const items: MenuProps['items'] = [
    {
      label: (
        <Link to="/home/center">
          <FormattedMessage id="menu.account.center" />
        </Link>
      ),
      key: 'account',
      icon: <UserOutlined />,
    },
    {
      label: (
        <Link to="/home/settings">
          <FormattedMessage id="menu.account.settings" />
        </Link>
      ),
      key: 'settings',
      icon: <LockOutlined />,
    },
    { type: 'divider' },
    {
      label: (
        <FormattedMessage id="layout.logout" defaultMessage="Logout" />
      ),
      key: 'logout',
      icon: <LogoutOutlined />,
    },
  ];
  //跳转账号信息
  //  const goAccount = () => {
  //   navigate("/home/account");
  // };
  //退出登录
  //搜索菜单
  const inputSearch = (value: string, data: any[]) => {
    let optionArr: any[] = [];
    const handleSearch = (
      value: string, //搜索值
      data: any[], //菜单树
      name: string = '', //菜单名
      isChild: boolean = false, // 是否子级
    ) => {
     
      if (value !== '') {
        data.forEach((item: any) => {
          let option = item.name || '';
          if (option.toUpperCase().includes(value.toUpperCase())) {
            //子级关联父级设置选项
            if (isChild) {
              let optionParent = name || '';
              optionArr.push({
                label: optionParent + ' > ' + option,
                value: option,
              });
            } else {
              if (item.menuType === 'page') optionArr.push({ value: option });
            }
          }
          if (item.routes?.length > 0)
            handleSearch(value, item.routes, item.name, true);
        });
        setMenuOption(optionArr);
      } else {
        setMenuOption([]);
      }
    };
    handleSearch(value, data);
  };
  //搜索页面
  const searchMenu = (data: any[]) => {
    if (isClose) {
      setIsClose(false);
      let flag = false;
      const setMenu = (data: any[]) => {
        data.forEach((item: any) => {
          let option = item.name;
          if (option?.toUpperCase() === menuValue.trim().toUpperCase()) {
            if (item.menuType === 'page') {
              navigate(item.path);
              flag = true;
              setIsClose(true);
            }
          }
          if (item.routes?.length > 0) setMenu(item.routes);
        });
      };
      setMenu(data);
      if (!flag)
        message.warning({
          content: intl.formatMessage({ id: 'pages.menu.searchInvalid' }),
          duration: 2,
          onClose() {
            setIsClose(true);
          },
        });
    }
  };
  return (
    <Space className={className} size="middle">
      <AutoComplete
        style={{
          width: 200,
          borderRadius: 20,
          backgroundColor: 'rgba(242, 243, 245, 1)',
        }}
        allowClear={false}
        onChange={(e) => setMenuValue(e)}
        onSearch={(e) => inputSearch(e, menuTree)}
        options={menuOption}
        popupMatchSelectWidth={false}
      >
        <Input
          placeholder={intl.formatMessage({ id: 'pages.menu.search' })}
          allowClear={false}
          bordered={false}
          suffix={
            <img src={searchIcon} onClick={() => searchMenu(menuTree)} />
          }
          style={{ width: 200 }}
        />
      </AutoComplete>
      <div className="setLang">
      <SelectLang style={langStyles} />
      </div>
      <Dropdown menu={{ items,onClick:menuClick }} overlayStyle={{ width: 200 }}>
        <div>
          <img
            src={initialState?.currentUser?.avatar || icon}
            alt=""
            className={styles['content-heat-right']}
            onError={(e: React.SyntheticEvent<HTMLImageElement, Event>) => {
              const target = e.target as HTMLImageElement;
              target.src = icon;
            }}
          />
          <Button
            size="small"
            // icon={<UserOutlined />}
            style={textColorStyles}
            type="text"
          >
            {userFirstWord()}
            <DownOutlined />
          </Button>
        </div>
      </Dropdown>
    </Space>
  );
};
export default GlobalHeaderRight;
