import { Button, Form, Modal, Select } from 'antd';
import { useState } from 'react';

interface ChildAccountModalProps {
    visible: boolean;
    childAccountList: APIChildAccount.FetchChildAccountListResponse;
    onCancel: () => void;
    onConfirm: (id: number) => Promise<boolean>;
}

export default function (props: ChildAccountModalProps) {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState<boolean>(false);
    return (
        <Modal title="选择子账号" open={props.visible} footer={null} destroyOnClose>
            <Form form={form} layout="vertical">
                <Form.Item
                    label="请选择分配子账号"
                    name="child_account"
                    rules={[{ required: true, message: '子账号不可为空' }]}
                >
                    <Select>
                        {props.childAccountList.map((item) => {
                            return (
                                <Select.Option key={item.id} value={item.id}>
                                    {item.contractName}
                                </Select.Option>
                            );
                        })}
                    </Select>
                </Form.Item>
                <Button
                    block
                    type="primary"
                    loading={loading}
                    onClick={() => {
                        form.validateFields().then(() => {
                            setLoading(true);
                            props
                                .onConfirm(form.getFieldValue('child_account'))
                                .then((success) => {
                                    setLoading(false);
                                    if (success) {
                                        props.onCancel();
                                    }
                                })
                                .catch(() => {
                                    props.onCancel();
                                    setLoading(false);
                                });
                        });
                    }}
                >
                    确认
                </Button>
            </Form>
        </Modal>
    );
}
