import React, {ChangeEvent, Component, useContext, useEffect, useRef, useState} from "react";
import {Dropdown, Form, Input, InputRef, LabeledValue, MenuProps, Select, Space, Table} from "antd";
import {FormInstance} from "antd/es/form";
import style from "@/component/step/http/Http.module.less";
import {PlusOutlined} from "@ant-design/icons";

type EditableTableProps = Parameters<typeof Table>[0];
type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;
const EditableContext = React.createContext<FormInstance<any> | null>(null);

interface EditableRowProps {
    index: number;
}

type HandleSave = (record: DataType) => void;

interface EditableCellProps {
    title: React.ReactNode;
    editable: boolean;
    children: React.ReactNode;
    dataIndex: keyof DataType;
    record: DataType;
    handleSave: HandleSave

}

interface DataType {
    key: number
    obj: React.Key
    condition: CheckEnum
    check: string
}

enum SelectAddEnum {
    ADD,
    IMPORT
}

// 函数方法枚举
enum CheckEnum {
    Comparison,
    outweigh,
    outweighEqual,
    less,
    lessEqual,
    NotEqual,
    contain,
    notContain,
    exist,
    absent,
    list,
    notList,
    interval,
    notInterval
}

const FuncList = ["对象比较", '大于', "大于等于", "小于", "小于等于", '不等于', "包含", "不包含", "存在", "不存在", "属于集合", "不属于集合", "区间范围", "非区间范围"]

const FuncSelectItem: LabeledValue[] = []

// const Func
for (let func in FuncList) {
    FuncSelectItem.push({
        value: func,
        label: FuncList[func]
    })
}

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} onPressEnter={save} onBlur={save}/>
            </Form.Item>
        ) : (
            <div className={style.HttpEditable} style={{paddingRight: 24}} onClick={toggleEdit}>
                {children}
            </div>
        );
    }

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

const addSelectItem: MenuProps['items'] = [
    {
        key: SelectAddEnum.ADD,
        label: (
            <div>添加一行</div>
        ),
    },
    {
        key: SelectAddEnum.IMPORT,
        label: (
            <div>导入</div>
        ),
    }
]

const Check = () => {
    const [dataSource, setDataSource] = useState<DataType[]>([
        {
            key: 0,
            condition: CheckEnum.lessEqual,
            check: '',
            obj: '',
        },
    ]);

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

    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 funcChange = (key: number, value: number) => {
        console.log(key, value)
        const data = dataSource[Number(key)]
        console.log(data)
        data.condition = Number(value)
        handleSave(data)
    }
    const paramsRender = (type: CheckEnum, value: DataType, handleSave: HandleSave) => {
        return <div>123123</div>
    }
    const defaultColumns: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[] = [
        {
            title: '校验对象',
            dataIndex: 'index',
            width: '300px',
            editable: true,
        },
        {
            title: '检查条件',
            dataIndex: 'index',
            width: "200px",
            render: (_, record:DataType) => {
                return (<div>
                    <Select
                        defaultValue={String(CheckEnum.absent)}
                        style={{width: "100%"}}
                        onChange={(value: number) => funcChange(record.key, value)}
                        options={FuncSelectItem}
                    />
                </div>)
            }
        },

        {
            title: '校验内容',
            dataIndex: 'index',
            render: (_, record: DataType) => {
                return (<div key={record.condition}>
                    {paramsRender(Number(record.condition), record, handleSave)}
                </div>)
            }
        },
        {
            width: "80px",
            title: () => {
                return (
                    <div className={style.HttpHandleAdd}>

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

                    </div>
                )

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

    const handleAdd = () => {
        const newData: DataType = {
            key: count,
            obj: '0',
            condition: CheckEnum.absent,
            check: ''
        };
        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 Check