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

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

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 }}
        className="minHeight"
        name={dataIndex}
    >
        <Input ref={inputRef} size="small" onPressEnter={save} onBlur={save} bordered style={{ fontSize: 12 }}  placeholder="请输入"/>
    </Form.Item></Form>) : (<span className="editable-cell-value-wrap ellipsisText" style={{ cursor: 'text' }} onClick={toggleEdit}>
        {title || '--'}
    </span>)

    return childNode;
}


export default React.memo(InputUpdate)