import React, { useState, SetStateAction } from 'react';
import Modal from 'antd/lib/modal/Modal';
import { Input } from 'antd';
import Form, { FormInstance } from 'antd/lib/form/Form';
import FormItem from 'antd/lib/form/FormItem';
import { trailwayAddUser } from '../../service';

type AddUserState = {
    isShow: boolean;
};

type AddUserProps = {
    onSuccess: () => void;
    showAddUser?: () => void;
};

class AddUser extends React.Component<AddUserProps, AddUserState> {
    private formRef = React.createRef<FormInstance>();

    constructor(props: AddUserProps) {
        super(props);
        this.state = {
            isShow: false,
        };
    }

    handleOk = () => {
        this.formRef.current?.submit();
    };

    handleCancel = () => {
        this.switchShow();
    };

    switchShow = () => {
        this.setState((state) => ({
            isShow: !state.isShow,
        }));
    };

    handleFinish = (values: any) => {
        trailwayAddUser(values).then((resp: any) => {
            if (resp.code == 200) {
                this.switchShow();
                this.props.onSuccess();
            }
        });
    };

    render() {
        return (
            <Modal
                title="增加用户"
                visible={this.state.isShow}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                closable={false}
            >
                <Form ref={this.formRef} onFinish={this.handleFinish}>
                    <FormItem name="username">
                        <Input placeholder="账户" />
                    </FormItem>
                    <FormItem name="password">
                        <Input placeholder="密码" />
                    </FormItem>
                </Form>
            </Modal>
        );
    }
}

export default AddUser;
