import React from 'react';
import { Button, Form, Input, Modal } from 'antd';

/**
 * 弹框输入
 * @param options
 * @returns {Promise<unknown>}
 */
export default function prompt(options: any) {
    const { title, content, layout = {}, onOk, ...others } = options || {};

    const _title = title ? <div style={{ marginBottom: 16 }}>{title}</div> : title;

    const customerForm = !!content;

    const _content = content || (
        <Form.Item name="name" rules={[ { required: true, message: '请输入！' } ]}>
            <Input placeholder="请输入"/>
        </Form.Item>
    );

    return new Promise((resolve, reject) => {
        const rootRef = { current: null };
        const formRef = { current: null };

        const modal = Modal.confirm({
            icon: false,
            title: _title,
            okText: '确定',
            cancelText: '取消',
            content: (
                <div ref={rootRef}>
                    <Form
                        ref={formRef}
                        {...layout}
                        onFinish={handleOk}
                    >
                        {_content}
                        <Button style={{ display: 'none' }} htmlType={'submit'}/>
                    </Form>
                </div>
            ),
            onOk: handleOk,
            onCancel: () => reject(new Error('cancel')),
            ...others,
        });

        // 确定时loading
        let loading = false;

        // 点击确定按钮
        async function handleOk() {
            if (loading) return;
            try {
                loading = true;
                modal.update({ okButtonProps: { loading: true } });
                const values = await formRef.current.validateFields();
                if (onOk) {
                    await onOk(values, formRef.current);
                }
                resolve(customerForm ? values : values?.name);
                modal.destroy();
            } finally {
                loading = false;
                modal.update({ okButtonProps: { loading: false } });
            }
        }

        // 输入框获取焦点
        setTimeout(() => {
            const $input = rootRef.current.querySelector('input,textarea');
            if (!$input) return;
            $input.focus();
        }, 300);
    });
}
