import React, { useState, forwardRef, useRef, useImperativeHandle } from 'react';
import { Avatar, Button, Dropdown, Menu, Form, Input, Modal } from 'antd';
import { useModel } from '@/store'

const ChangePassword = forwardRef((props, ref) => {
  const [visible, setVisible] = useState(false);

  const onFinish = (values) => {
    console.log('Success:', values);
  };

  useImperativeHandle(ref, () => {
    return {
      show: () => setVisible(true),
    }
  });

  return (
    <Modal title="修改密码" visible={visible} onCancel={() => setVisible(false)}>
      <Form
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="原始密码"
          name="password"
          rules={[{ required: true, message: '请输入原始密码!' }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          label="新密码"
          name="newPassword"
          rules={[{ required: true, message: '请输入新密码!' }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          label="确认新密码"
          name="newPassword2"
          rules={[{ required: true, message: '请输入新密码!' }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>
    </Modal>
  )
});

export default (props) => {
  const menuItems = [
    {
      key: 'changePassword',
      label: '修改密码',
    }
  ];

  const passRef = useRef();
  const { user = {} } = useModel('user');

  const onClick = ({ key }) => {
    if (key === 'changePassword') {
      passRef.current.show();
    }
  };

  const menu = <Menu items={menuItems} onClick={onClick} />;

  return (
    <Dropdown overlay={menu}>
      <div className="user-info">
        <Avatar size={24} src="https://joeschmoe.io/api/v1/random" />
        <span className='font'>{user.name}</span>
        <ChangePassword ref={passRef} />
      </div>
    </Dropdown>
  )
}
