/** @format */

import * as React from 'react';
import message from '../../../../../../components/message';
import Modal from '../../../../../../components/modalForm';
import Table from '../../../../../../components/table';
import Button from '../../../../../../components/button';
import {decodeBase64} from '../../../../../../utils/base64';
import {useInsertInterfaceOnQueryType, IqueryIntrefaceProps} from '../../../../../../service/configQueryType';
import {InterfaceType} from '../../../../../../const/status';
import AddInterface from './addInterface';

import {ColumnProps} from 'antd/es/table';

interface IState {
    visible: boolean;
    list: IqueryIntrefaceProps[];
}
interface Iprops {
    onOk?: () => void;
    defaultDataSource: any[];
}
const Interface: React.FC<Iprops> = props => {
    const {children, onOk, defaultDataSource} = props;
    const id = new URLSearchParams(decodeBase64(location.search.slice(1))).get('id');
    const [state, setState] = React.useState<IState>({
        visible: false,
        list: defaultDataSource.map(element => {
            return {
                ...element,
                id: element.api_id,
            };
        }),
    });
    const [insertInterfaceState, requetInsert] = useInsertInterfaceOnQueryType();
    const handleUpdateModalVisible = () => {
        setState(preState => ({...preState, visible: !preState.visible}));
    };
    React.useEffect(() => {
        setState(preState => ({
            ...preState,
            list: defaultDataSource.map(element => {
                return {
                    ...element,
                    id: element.api_id,
                };
            }),
        }));
    }, [defaultDataSource]);
    const handleAddInterface = (values: any[]) => {
        setState(preState => ({
            ...preState,
            list: values.map((element, index) => {
                return {...element, priority: index + 1};
            }),
        }));
    };
    const handleSubmit = () => {
        requetInsert({
            query_type_id: Number(id),
            base_api_list: state.list.map(element => element.id),
        }).then(error => {
            if (error) return message.error(error);
            handleUpdateModalVisible();
            onOk && onOk();
        });
    };
    const handleRemove = (record: IqueryIntrefaceProps) => {
        setState(preState => ({...preState, list: preState.list.filter(element => element.id !== record.id)}));
    };
    const handleMove = (record: IqueryIntrefaceProps, type: 'up' | 'down') => {
        const willMoveIndex = state.list.findIndex(element => element.id === record.id);
        const moveResultValues = JSON.parse(JSON.stringify(state.list));
        if (type === 'down') {
            moveResultValues.splice(willMoveIndex + 1, 0, ...moveResultValues.splice(willMoveIndex, 1));
        } else {
            moveResultValues.splice(willMoveIndex - 1, 0, ...moveResultValues.splice(willMoveIndex, 1));
        }
        setState(preState => ({
            ...preState,
            list: moveResultValues,
        }));
    };

    const tableCoulmns = React.useMemo(() => {
        const columns: ColumnProps<IqueryIntrefaceProps>[] = [
            {
                title: '优先级',
                dataIndex: 'priority',
                key: 'priority',
                width: 80,
                render: (text, record, index) => {
                    return index + 1;
                },
            },
            {
                title: '接口',
                dataIndex: 'api_name',
                key: 'api_name',
            },
            {
                title: '接口路径',
                dataIndex: 'router',
                key: 'router',
            },
            {
                title: '类别',
                dataIndex: 'api_type',
                key: 'api_type',
                width: 100,
                render: text => {
                    return InterfaceType[text];
                },
            },
            {
                title: '操作',
                width: 230,
                render: (_, record, index) => {
                    return (
                        <>
                            <Button type='link' disabled={index === 0} onClick={() => handleMove(record, 'up')}>
                                上移
                            </Button>
                            <Button
                                type='link'
                                disabled={index === state.list.length - 1}
                                onClick={() => handleMove(record, 'down')}
                            >
                                下移
                            </Button>
                            <Button type='link' onClick={() => handleRemove(record)}>
                                删除
                            </Button>
                        </>
                    );
                },
            },
        ];
        return columns;
    }, [state.list]);
    return (
        <>
            {React.isValidElement(children) &&
                React.cloneElement(children, {
                    onClick: handleUpdateModalVisible,
                })}
            <Modal
                loading={insertInterfaceState.loading}
                onOk={handleSubmit}
                onCancel={handleUpdateModalVisible}
                visible={state.visible}
                width={1000}
                title='添加'
            >
                <AddInterface onSubmit={handleAddInterface} values={state.list.map(element => String(element.id))}>
                    <Button type='primary' style={{marginBottom: 15}}>
                        添加
                    </Button>
                </AddInterface>
                <Table
                    size='small'
                    rowKey='id'
                    columns={tableCoulmns}
                    bordered={false}
                    pagination={false}
                    dataSource={state.list}
                />
            </Modal>
        </>
    );
};
export default Interface;
