/** @format */

import * as React from 'react';
import {Form, Switch, InputNumber, Spin, notification} from 'antd';

import {addId} from '../../../../../utils/operation';
import message from '../../../../../components/message';
import Button from '../../../../../components/button';
import SourceSet from './components/sourceSet';
import Params from '../../../../../components/params';
import Filters from '../../../../../components/filters';
import InterfaceModal from './components/interfaceModal';
import PermissionManger from '../../../../../components/AccessControl';
import Input from '../../../../../components/input';
import Select from '../../../../../components/select/select';
import {FormComponentProps} from 'antd/es/form';
import {decodeBase64} from '../../../../../utils/base64';
import {useDataApiQueryTypeDetail} from '../../../../../service/configQueryType';
import {useUpdateDataApiToBaseApiInfo} from '../../../../../service/dataApi';

const formItemLayout = {
    labelCol: {
        xs: {span: 24},
        sm: {span: 2},
    },
    wrapperCol: {
        xs: {span: 24},
        sm: {span: 6},
    },
};
const intrefaceConfig: React.FC<FormComponentProps> = props => {
    const id = new URLSearchParams(decodeBase64(location.search.slice(1))).get('id');
    const {form} = props;
    const requestRef: any = React.useRef(null);
    const responseRef: any = React.useRef(null);
    const {getFieldDecorator, setFieldsValue, validateFieldsAndScroll, getFieldValue} = form;
    const [baseApiListState, requestBaseApilist] = useDataApiQueryTypeDetail(Number(id));
    const [updateState, requestUpdate] = useUpdateDataApiToBaseApiInfo();
    const handleAddInterfaceOk = () => {
        requestBaseApilist(Number(id));
    };

    React.useEffect(() => {
        if (baseApiListState.dataSource.data_api_base_apis.length) {
            setFieldsValue({
                data_api_base_api_id: baseApiListState.dataSource.data_api_base_apis[0].id,
            });
            handleChangeInterface(baseApiListState.dataSource.data_api_base_apis[0].id);
        }
    }, [baseApiListState.dataSource.data_api_base_apis]);

    const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        validateFieldsAndScroll((error, values) => {
            if (error) return;
            const request_params = requestRef.current.getParams();
            const response_params = responseRef.current.getParams();
            const {
                permissionManger,
                reuse_time,
                sale_name,
                filters,
                force_update,
                is_crypto,
                provider_group_list,
                data_api_base_api_id,
            } = values;
            requestUpdate({
                data_api_base_api_id,
                reuse_time,
                sale_name,
                ...permissionManger,
                filters,
                force_update,
                is_crypto,
                provider_group_list,
                request_params,
                response_params,
            }).then(error => {
                if (error) {
                    return notification.error({
                        message: '更新失败!',
                        description: error,
                    });
                }
                message.success('更新成功!');
            });
        });
    };
    const handleChangeInterface = (id: any) => {
        const currentValue = baseApiListState.dataSource.data_api_base_apis.filter(element => {
            return element.id === id;
        })[0];
        setFieldsValue({
            sale_name: currentValue.sale_name,
            is_crypto: currentValue.is_crypto,
            force_update: currentValue.force_update,
            reuse_time: currentValue.reuse_time,
            permissionManger: {
                count_type: currentValue.count_type,
                count_code: currentValue.count_code,
            },
            request_params: addId(currentValue.request_params || [], 'request_params'),
            response_params: addId(currentValue.response_params || [], 'response_params'),
            provider_group_list: currentValue.provider_group_list,
        });
        if (currentValue.request_params && currentValue.request_params.length > 0) {
            setFieldsValue({
                filters: currentValue.filters || [],
            });
        }
    };
    getFieldDecorator('filters', {initialValue: []});

    const handleAddFilter = () => {
        const currentFilters = getFieldValue('filters');
        setFieldsValue({
            filters: currentFilters.concat({
                name: '',
                value: '',
                id: Date.now(),
            }),
        });
    };
    const handleChangeFilters = (values: any) => {
        setFieldsValue({
            filters: values,
        });
    };
    getFieldDecorator('response_params', {initialValue: []});
    getFieldDecorator('request_params', {initialValue: []});
    return (
        <Spin spinning={baseApiListState.loading}>
            <Form {...formItemLayout} onSubmit={handleSubmit}>
                <Form.Item label='接口'>
                    {getFieldDecorator('data_api_base_api_id', {
                        rules: [
                            {
                                required: true,
                                message: '请选择要设置的接口!',
                            },
                        ],
                    })(
                        <Select
                            onChange={handleChangeInterface}
                            placeholder='请选择接口!'
                            options={baseApiListState.dataSource.data_api_base_apis.map(element => {
                                return {
                                    key: element.id,
                                    label: `${element.api_name}(${element.router})`,
                                    value: element.id,
                                };
                            })}
                        />,
                    )}
                    <InterfaceModal
                        onOk={handleAddInterfaceOk}
                        defaultDataSource={baseApiListState.dataSource.data_api_base_apis}
                    >
                        <Button type='primary'>添加</Button>
                    </InterfaceModal>
                </Form.Item>
                <Form.Item label='销售名称'>
                    {getFieldDecorator('sale_name', {
                        rules: [
                            {
                                required: false,
                                message: '请输入销售名称!',
                            },
                            {
                                whitespace: true,
                                message: '请输入销售名称!',
                            },
                        ],
                    })(<Input placeholder='请输入销售名称!' />)}
                </Form.Item>
                <h3>基本配置</h3>
                <Form.Item label='是否加密'>
                    {getFieldDecorator('is_crypto', {
                        valuePropName: 'checked',
                        initialValue: false,
                    })(<Switch unCheckedChildren='否' checkedChildren='是' />)}
                </Form.Item>
                <Form.Item label='是否强制更新'>
                    {getFieldDecorator('force_update', {
                        valuePropName: 'checked',
                        initialValue: false,
                    })(<Switch unCheckedChildren='否' checkedChildren='是' />)}
                </Form.Item>
                <Form.Item label='复用时效(天)'>
                    {getFieldDecorator('reuse_time', {
                        rules: [
                            {
                                required: true,
                            },
                        ],
                        initialValue: 0,
                    })(<InputNumber min={0} />)}
                </Form.Item>
                <Form.Item label='权限控制' wrapperCol={{xs: {span: 24}, sm: {span: 18}}}>
                    {getFieldDecorator('permissionManger', {
                        initialValue: {
                            count_type: 0,
                            count_code: '',
                        },
                    })(<PermissionManger form={form} />)}
                </Form.Item>
                <h3>参数设置</h3>
                <h4>请求参数</h4>
                <Form.Item labelCol={{xs: {span: 24}, sm: {span: 0}}} wrapperCol={{xs: {span: 24}, sm: {span: 24}}}>
                    <Params
                        ref={requestRef}
                        chooseAll
                        value={getFieldValue('request_params')}
                        requestType='request'
                        isEditable={false}
                    />
                </Form.Item>
                {getFieldValue('request_params').length !== 0 ? (
                    <>
                        <Button onClick={handleAddFilter} type='primary'>
                            添加过滤规则
                        </Button>
                        <Form.Item
                            labelCol={{xs: {span: 24}, sm: {span: 0}}}
                            wrapperCol={{xs: {span: 24}, sm: {span: 24}}}
                        >
                            <Filters
                                form={form}
                                onChange={handleChangeFilters}
                                value={getFieldValue('filters')}
                                options={getFieldValue('request_params').map(element => {
                                    return {
                                        key: element.id,
                                        label: element.name,
                                        value: element.name,
                                    };
                                })}
                            />
                        </Form.Item>
                    </>
                ) : null}
                <h4>响应参数</h4>
                <Form.Item labelCol={{xs: {span: 24}, sm: {span: 0}}} wrapperCol={{xs: {span: 24}, sm: {span: 24}}}>
                    <Params
                        ref={responseRef}
                        isEditable={false}
                        value={getFieldValue('response_params')}
                        requestType='response'
                    />
                </Form.Item>
                <h3>数据源设置</h3>
                <Form.Item labelCol={{xs: {span: 24}, sm: {span: 0}}} wrapperCol={{xs: {span: 24}, sm: {span: 24}}}>
                    {getFieldDecorator('provider_group_list', {initialValue: []})(<SourceSet />)}
                </Form.Item>
                <Form.Item>
                    <Button type='primary' htmlType='submit' loading={updateState.loading}>
                        保存
                    </Button>
                </Form.Item>
            </Form>
        </Spin>
    );
};
export default Form.create<FormComponentProps>({name: 'intrefaceConfig'})(intrefaceConfig);
