/** @format */

import * as React from 'react';

import {Input, Popconfirm, Form, Icon, Spin, Empty, Row, Col, notification} from 'antd';
import {FormComponentProps} from 'antd/es/form';

import message from '../../../../components/message';
import Result from '../../../../components/result';
import {
    useQueryTypeList,
    IQueryTypeProps,
    useUpdateQueryModo,
    useDeleteQueryType,
} from '../../../../service/configQueryType';
import Button from '../../../../components/button';
import {decodeBase64, encodeBase64} from '../../../../utils/base64';

const formItemLayout = {
    labelCol: {
        xl: {span: 3},
        xxl: {span: 2},
    },
    wrapperCol: {
        xl: {span: 21},
        xxl: {span: 22},
    },
};

const formItemLayoutWithOutLabel = {
    wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 20, offset: 2},
    },
};

export default Form.create<FormComponentProps>({name: 'dataApiConfig'})((props: FormComponentProps) => {
    const {form, history} = props;
    const {validateFieldsAndScroll, getFieldValue, setFieldsValue} = form;
    const search = new URLSearchParams(decodeBase64(location.search.slice(1)));
    const id = Number(search.get('id'));
    const name = decodeURIComponent(search.get('name') || '');
    const [listState, requetsList] = useQueryTypeList();

    const [updateState, requestUpdate] = useUpdateQueryModo();
    const [deleteState, requestDelete] = useDeleteQueryType();
    React.useEffect(() => {
        requetsList(id);
    }, [id]);

    const handleRetry = () => {
        requetsList(id);
    };
    const handleToConfig = (record: IQueryTypeProps) => {
        if (!record.query_type_id) {
            return message.error('请先保存您要修改的查询方式!');
        }
        const path =
            '/home/dataServer/queryModeConfig?' +
            encodeBase64('id=' + record.id + '&name=' + encodeURIComponent(name + '--' + record.query_type_name));
        history.push(path);
    };
    const handleAdd = () => {
        const keys = getFieldValue('keys');
        const nowId = Date.now();
        form.setFieldsValue({
            keys: keys.concat({
                id: nowId,
                query_type_name: '',
            }),
        });
    };
    const handleRemove = (record: IQueryTypeProps) => {
        const keys: IQueryTypeProps[] = form.getFieldValue('keys');
        if (record.query_type_id) {
            requestDelete(record.id).then(error => {
                if (error) {
                    return notification.error({
                        message: `删除${record.query_type_name}失败!`,
                        description: error,
                    });
                }
                return handleRetry();
            });
        }
        form.setFieldsValue({
            keys: keys.filter(element => element.id !== record.id),
        });
    };
    const handleSubmit = () => {
        validateFieldsAndScroll((error, values) => {
            if (error) return;
            const keys = form.getFieldValue('keys');
            const newValues = keys.map((element: IQueryTypeProps) => {
                if (!element.query_type_id) {
                    return {
                        query_type_name: values[element.id],
                    };
                } else {
                    return {
                        query_type_name: values[element.id],
                        query_type_id: element.query_type_id,
                    };
                }
            });
            //记录 判断 名字重复
            requestUpdate({
                data_api_id: id,
                query_types: newValues,
            }).then(error => {
                if (error) {
                    return notification.error({
                        message: '操作查询方式失败',
                        description: error,
                    });
                }
                handleRetry();
            });
        });
    };

    form.getFieldDecorator('keys', {initialValue: listState.dataSource});
    React.useEffect(() => {
        setFieldsValue({
            keys: listState.dataSource,
        });
    }, [listState.dataSource]);
    const keys: IQueryTypeProps[] = form.getFieldValue('keys');
    return (
        <Spin spinning={listState.loading}>
            <Result error={listState.error} onRetry={handleRetry}>
                <Form {...formItemLayout}>
                    {keys.length === 0 ? (
                        <Row gutter={24} style={{marginBottom: 15}}>
                            <Col span={8}>
                                <Empty description='暂未配置查询方式' />
                            </Col>
                        </Row>
                    ) : (
                        keys.map((element, index) => {
                            return (
                                <Form.Item key={element.id} label={`查询方式序号--${index + 1}`}>
                                    {form.getFieldDecorator(element.id.toString(), {
                                        initialValue: element.query_type_name,
                                        rules: [
                                            {
                                                required: true,
                                                message: '请输入查询方式名称!',
                                            },
                                        ],
                                    })(<Input style={{width: 230}} placeholder='请输入查询方式名称!' />)}
                                    <Button
                                        onClick={() => handleToConfig(element)}
                                        type='primary'
                                        style={{marginRight: 15, marginLeft: 15}}
                                    >
                                        配置
                                    </Button>
                                    <Popconfirm
                                        onConfirm={() => handleRemove(element)}
                                        title={`是否确认删除${element.query_type_name}!`}
                                        okText='确认'
                                        okType='danger'
                                        cancelText='取消'
                                    >
                                        <Button
                                            loading={deleteState.loading}
                                            type='danger'
                                            icon='delete'
                                            shape='circle'
                                        />
                                    </Popconfirm>
                                </Form.Item>
                            );
                        })
                    )}
                    <Form.Item {...formItemLayoutWithOutLabel}>
                        <Button type='dashed' onClick={handleAdd}>
                            <Icon type='plus' /> 添加查询方式
                        </Button>
                    </Form.Item>
                    {keys.length ? (
                        <Form.Item {...formItemLayoutWithOutLabel}>
                            <Button type='primary' onClick={handleSubmit} loading={updateState.loading}>
                                保存
                            </Button>
                        </Form.Item>
                    ) : null}
                </Form>
            </Result>
        </Spin>
    );
});
