import React, {useState} from 'react';
import { Dropdown, Menu, message } from 'antd';
import {YIcon} from '@/icon';
import {useModal} from '@/modal';
import {useModel} from './useModel';
import {ChangePassword} from './changePassword';
import {ChangePasswordPrams} from './auth.interface';
import {HeaderAvatarStyle} from './styles';

export const User : React.FC = () => {
  const { show } = useModal();
  const { loginout, changePassword, userName } = useModel();
  const [oldPasswd, setOldPasswd] = useState('');
  const [newPasswd, setNewPasswd] = useState('');
  const goToLogin = () => {
    if(typeof window === 'undefined'){

    } else {
      window.location.href='/login';
    }
    
  }

  const gotoLoginOut = async () => {
    const res = await loginout();
    res && message.success('退出成功！');
    if(typeof window !== 'undefined'){
      window.localStorage.setItem('token', '');
      window.localStorage.setItem('userName', '');
      window.localStorage.setItem('userPhone', '');
      goToLogin();
    }
    
  }

  const onChangePassword = (value: ChangePasswordPrams) => {
    setOldPasswd(value.oldPasswd);
    setNewPasswd(value.newPasswd);
  }

  const args = {
    title: '修改密码',
    size: 'large',
    content: () => <ChangePassword onChange={onChangePassword} />,
    onOk: () => {
      console.log('ok');
      // const res = await changePassword({
      //   oldPasswd,
      //   newPasswd
      // })
    },
    onCancel: () => {
      console.log('close');
    },
  }


  const menu = (
    <Menu>
      <Menu.Item onClick={() => show(args)}>
          修改密码
        
      </Menu.Item>
      <Menu.Item>
        <a onClick={gotoLoginOut}>
          退出
        </a>
      </Menu.Item>
    </Menu>
  );
    
  return (
    <>
      <HeaderAvatarStyle icon={<YIcon name="UserOutlined" />} />
      <Dropdown overlay={menu}>
        <a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
          {userName} <YIcon name="DownOutlined" />
        </a>
      </Dropdown>
    </>
  )
}