import React, {useContext, useEffect, useRef, useState} from 'react';
import type {InputRef, MenuProps} from 'antd';
import {Button, Dropdown, Form, Input, Popconfirm, Space, Table} from 'antd';
import type {FormInstance} from 'antd/es/form';
import style from "./Http.module.less"
import {DownOutlined, PlusOutlined} from "@ant-design/icons";

const EditableContext = React.createContext<FormInstance<any> | null>(null);

interface Item {
    key: string;
    name: string;
    age: string;
    address: string;
}

interface EditableRowProps {
    index: number;
}


type EditableTableProps = Parameters<typeof Table>[0];

interface DataType {
    key: React.Key;
    name: string;
    value: string;
}

type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;

enum SelectAddEnum {
    ADD,
    IMPORT
}

interface EditableCellProps {
    title: React.ReactNode;
    editable: boolean;
    children: React.ReactNode;
    dataIndex: keyof Item;
    record: Item;
    handleSave: (record: Item) => void;
}

const EditableRow: React.FC<EditableRowProps> = ({index, ...props}) => {
    const [form] = Form.useForm();
    return (
        <Form form={form} component={false}>
            <EditableContext.Provider value={form}>
                <tr {...props} />
            </EditableContext.Provider>
        </Form>
    );
};
const EditableCell: React.FC<EditableCellProps> = ({
                                                       title,
                                                       editable,
                                                       children,
                                                       dataIndex,
                                                       record,
                                                       handleSave,
                                                       ...restProps
                                                   }) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef<InputRef>(null);
    const form = useContext(EditableContext)!;

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

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

    const save = async () => {
        try {
            const values = await form.validateFields();
            toggleEdit();
            handleSave({...record, ...values});
        } catch (errInfo) {
            console.log('Save failed:', errInfo);
        }
    };

    let childNode = children;

    if (editable) {
        childNode = editing ? (
            <Form.Item
                style={{margin: 0}}
                name={dataIndex}
                rules={[
                    {
                        required: true,
                        message: `${title} 不能为空`,
                    },
                ]}
            >
                <Input ref={inputRef} placeholder={`编辑 ${title}`} onPressEnter={save} onBlur={save}/>
            </Form.Item>
        ) : (
            <div className={children[1]&&children[1].length>0?"":style.HttpEditable} style={{paddingRight: 24}} onClick={toggleEdit}>
                {children[1]&&children[1].length>0?children:"点击编辑 "+title}
            </div>
        );
    }

    return <td {...restProps}>{childNode}</td>;
};


const addSelectItem: MenuProps['items'] = [
    {
        key: SelectAddEnum.ADD,
        label: (
            <div>添加一行</div>
        ),
    },
    {
        key: SelectAddEnum.IMPORT,
        label: (
            <div>导入</div>
        ),
    }
]
const Params: React.FC = () => {
    const [dataSource, setDataSource] = useState<DataType[]>([
        {
            key: '0',
            name: '',
            value: '',
        },
        {
            key: '1',
            name: '',
            value: '',
        },
    ]);

    const [count, setCount] = useState(2);

    const handleDelete = (key: React.Key) => {
        const newData = dataSource.filter((item) => item.key !== key);
        setDataSource(newData);
    };
    // 用户操作
    const TitleSelectClick: MenuProps['onClick'] = ({key}) => {
        const SelectKey = Number(key)
        switch (SelectKey) {
            case SelectAddEnum.ADD:
                handleAdd()
                break
            case SelectAddEnum.IMPORT:
                console.log("import")
                break
            default:
                break
        }
        console.log(key)
    }
    const defaultColumns: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[] = [
        {
            title: 'key',
            dataIndex: 'name',
            width: '30%',
            editable: true,
        },
        {
            title: 'value',
            dataIndex: 'value',
            editable: true,
        },
        {
            width: "80px",
            title: () => {
                return (
                    <div className={style.HttpHandleAdd}>

                        <Dropdown menu={{items: addSelectItem, onClick: TitleSelectClick}}>
                            <Space>
                                <div>
                                    <PlusOutlined/>
                                </div>
                            </Space>
                        </Dropdown>

                    </div>
                )

            },
            dataIndex: 'operation',
            render: (_, record: { key: React.Key }) =>
                dataSource.length >= 1 ? (
                    <span className={style.HttpHandleAdd} onClick={() => handleDelete(record.key)}>删除</span>
                ) : null,
        },
    ];

    const handleAdd = () => {
        const newData: DataType = {
            key: count,
            name: ``,
            value: ``,
        };
        setDataSource([...dataSource, newData]);
        setCount(count + 1);
    };

    const handleSave = (row: DataType) => {
        const newData = [...dataSource];
        const index = newData.findIndex((item) => row.key === item.key);
        const item = newData[index];
        newData.splice(index, 1, {
            ...item,
            ...row,
        });
        setDataSource(newData);
    };

    const components = {
        body: {
            row: EditableRow,
            cell: EditableCell,
        },
    };

    const columns = defaultColumns.map((col) => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record: DataType) => ({
                record,
                editable: col.editable,
                dataIndex: col.dataIndex,
                title: col.title,
                handleSave,
            }),
        };
    });

    return (
        <div>
            <Table
                components={components}
                rowClassName={() => 'editable-row'}
                bordered
                dataSource={dataSource}
                columns={columns as ColumnTypes}
            />
        </div>
    );
};

export default Params;
