/** @format */

import * as React from 'react';
import {Form, Row, Col, Switch, Spin, Typography, Tooltip} from 'antd';

import Result from '../../../../components/result';
import {addId} from '../../../../utils/operation';
import MerchantSelect from '../../../../components/select/merchant';
import BaseApiSelect from '../../../../components/select/baseApiSelect';
import {FormComponentProps} from 'antd/es/form';
import JsonView from '../../../../components/jsonview';
import Button from '../../../../components/button';
import Params from '../../../../components/params';
import {useDataApiOnlineQuery} from '../../../../service/baseApi';
const {Paragraph} = Typography;

const formItemLayout = {
    labelCol: {
        xs: {span: 24},
        sm: {span: 5},
        lg: {span: 7},
    },
    wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        lg: {span: 17},
    },
};
interface Istate {
    merchant_id: number | '';
}
/**
 * 对请求参数新增value字段
 * 由于params 组件是通用的In 字段（对应需要转换的value）,所以还需要将In 字段转换回来
 */
const formatNewParams = (newValues: any[]) => {
    for (let k = 0; k < newValues.length; k++) {
        newValues[k].value = newValues[k].in;
        newValues[k].in = newValues[k].oldIn;
        newValues[k].child = formatNewParams(newValues[k].child || []);
    }
    return newValues;
};
/**
 * 重置in 字段为空 并使用oldIn保留原来的in字段
 */
const formatOldParams = (olvalues: any[]) => {
    for (let k = 0; k < olvalues.length; k++) {
        olvalues[k].oldIn = olvalues[k].in;
        olvalues[k].in = '';
        olvalues[k].child = formatOldParams(olvalues[k].child || []);
    }
    return olvalues;
};
const onlineQuery: React.FC<FormComponentProps> = props => {
    const {getFieldDecorator, setFieldsValue, getFieldValue} = props.form;
    const requestRef: any = React.useRef(null);
    const [state, setState] = React.useState<Istate>({
        merchant_id: '',
    });

    const [queryState, requestQuery] = useDataApiOnlineQuery();
    const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        props.form.validateFieldsAndScroll((error, values) => {
            if (!error) {
                const request_param = requestRef.current.getParams();
                setFieldsValue({
                    request_param: JSON.parse(JSON.stringify(request_param)),
                });
                requestQuery({
                    ...values.merchantInfo,
                    merchant_account: values.merchant_account,
                    method: values.method,
                    request_param: formatNewParams(request_param),
                    router: values.router,
                });
            }
        });
    };
    const handleRetry = () => {
        requestQuery();
    };

    getFieldDecorator('merchantInfo', {initialValue: {}});

    const handleChangrMerchant = (merchant_id: any, options: any) => {
        if (!!merchant_id) {
            const {props} = options;
            const info = props['data-props'];
            setFieldsValue({
                merchantInfo: {
                    app_key: info.merchant.app_key,
                    app_secret: info.merchant.app_secret,
                },
                method: '',
                router: '',
                request_param: [],
                interfaceId: undefined,
            });
        } else {
            setFieldsValue({
                merchantInfo: {
                    app_key: '',
                    app_secret: '',
                },
                method: '',
                router: '',
                request_param: [],
                interfaceId: undefined,
            });
        }
    };

    const handleChangeInterface = (_: any, option: any) => {
        const {props} = option;
        setFieldsValue({
            method: props['data-props'].method,
            router: props['data-props'].router,
            request_param: formatOldParams(addId(props['data-props'].request_param || [], 'request')),
        });
        const merchantInfos = getFieldValue('merchantInfo');
        setFieldsValue({
            merchantInfo: {
                ...merchantInfos,
                is_crypto: props['data-props'].is_crypto,
            },
        });
    };
    getFieldDecorator('method');
    getFieldDecorator('router');
    getFieldDecorator('request_param', {
        initialValue: [],
    });
    const router = getFieldValue('router');
    const merchant_id = getFieldValue('merchanId');
    return (
        <Spin spinning={queryState.loading}>
            <Form {...formItemLayout} onSubmit={handleSubmit}>
                <Row>
                    <Col span={12}>
                        <Form.Item label='商户名称'>
                            {getFieldDecorator('merchanId', {
                                rules: [{required: true, message: '请选择商户!'}],
                            })(<MerchantSelect onChange={handleChangrMerchant} />)}
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label='接口名称'>
                            {getFieldDecorator('interfaceId', {
                                rules: [{required: true, message: '请选择接口'}],
                            })(
                                <BaseApiSelect
                                    only_base_api={false}
                                    showApi={true}
                                    disabled={!merchant_id}
                                    merchant_id={merchant_id}
                                    onChange={handleChangeInterface}
                                />,
                            )}
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={12}>
                        <Form.Item label='请求方式'>
                            {<Paragraph>{getFieldValue('method') || '--'}</Paragraph>}
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label='接口地址'>
                            <Paragraph ellipsis>{router || '--'}</Paragraph>
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={12}>
                        <Form.Item label='是否使用商户账号'>
                            {getFieldDecorator('merchant_account', {
                                initialValue: false,
                                valuePropName: 'checked',
                            })(<Switch checkedChildren='是' unCheckedChildren='否' />)}
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={24}>
                        <Form.Item
                            label='请求参数'
                            wrapperCol={{xs: {span: 24}, sm: {span: 22}}}
                            labelCol={{xs: {span: 24}, sm: {span: 2}}}
                        >
                            <Params
                                ref={requestRef}
                                value={getFieldValue('request_param')}
                                isEditable={false}
                                chooseAll={false}
                                mode='query'
                            />
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={24}>
                        <Result error={queryState.error} onRetry={handleRetry}>
                            <Form.Item
                                label='响应结果'
                                wrapperCol={{xs: {span: 24}, sm: {span: 22}}}
                                labelCol={{xs: {span: 24}, sm: {span: 2}}}
                            >
                                <JsonView src={queryState.data} />
                            </Form.Item>
                        </Result>
                    </Col>
                </Row>
                <Row type='flex' justify='end'>
                    <Button size='large' type='primary' htmlType='submit'>
                        运行
                    </Button>
                </Row>
            </Form>
        </Spin>
    );
};
export default Form.create({name: 'onlinequery'})(onlineQuery);
