import { Form, Input, InputRef } from "antd";
import React, { useEffect, useRef, useState } from "react"

interface Props {
    title: string,
    dataIndex: string
    record: any;
    handleSave: (data: any) => void
    isNum?: boolean
}

const InputUpdate: React.FC<Props> = ({ title, dataIndex, record, handleSave, isNum }) => {
    const [form] = Form.useForm();
    const [editing, setEditing] = useState(false);
    const inputRef = useRef<InputRef>(null);

    useEffect(() => {
        if (editing) {
            inputRef.current!.focus({ cursor: 'all' });
        }
    }, [editing]);

    const toggleEdit = () => {
        setEditing(!editing);
        form.setFieldsValue({ [dataIndex]: record[dataIndex] });
    };

    const save = async () => {
        try {
            const values = await form.validateFields();
            if (values?.[dataIndex] !== (record as any)?.[dataIndex]) {
                handleSave({ ...record, ...values });
            }
            toggleEdit();
        } catch (errInfo) {
            console.log('Save failed:', errInfo);
        }
    };

    let childNode = editing ? (<Form form={form}><Form.Item
        style={{ margin: 0 }}
        name={dataIndex}
        rules={[
            { required: true, message: `${title} is required.` },
            {
                required: isNum, message: `大于0，并且填写数字`, validator(rule, value, callback) {
                    let regPos = /^[0-9]+.?[0-9]*/; //判断是否是数字。
                    if (!isNum) {
                        return Promise.resolve()
                    } else {
                        if (!regPos.test(value)) {
                            return Promise.reject()
                        }
                        if (value >= 0) {
                            return Promise.resolve()
                        } else {
                            return Promise.reject()
                        }
                    }
                },
            }
        ]}
    >
        <Input ref={inputRef} size="small" onPressEnter={save} onBlur={save} bordered />
    </Form.Item></Form>) : (<span className="editable-cell-value-wrap ellipsisText" onClick={toggleEdit}>
        {title}
    </span>)

    return childNode;
}


export default React.memo(InputUpdate)