/** @format */

import * as React from 'react';
import {Form, Switch, InputNumber, Upload, Icon, Tooltip} from 'antd';
import {FormComponentProps} from 'antd/es/form';

import Modal from '../../../../components/modalForm';
import message from '../../../../components/message';
import MerchantSelect from '../../../../components/select/merchant';
import BaseApiSelect from '../../../../components/select/baseApiSelect';
import {RcFile} from 'antd/es/upload';
import Button from '../../../../components/button';
import Input from '../../../../components/input';
import {useDataApiMultipleQuery} from '../../../../service/baseApi';
const formItemLayout = {
    labelCol: {
        xs: {span: 24},
        sm: {span: 5},
    },
    wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
    },
};
interface Istate {
    fileList: RcFile[];
}
interface Iprops {
    onOk?: () => void;
}
const createTask: React.FC<Iprops & FormComponentProps> = props => {
    const {children, form, onOk} = props;
    const {getFieldValue, getFieldDecorator, setFieldsValue, resetFields} = form;
    const [createState, requestCreate] = useDataApiMultipleQuery();
    const [modalState, setModalState] = React.useState({
        visible: false,
    });
    const handleUpdateModalVisible = () => {
        setState(preState => ({...preState, fileList: []}));
        setModalState(preState => {
            resetFields();
            return {...preState, visible: !preState.visible};
        });
    };

    const [state, setState] = React.useState<Istate>({fileList: []});

    const beforeUpload = (file: RcFile) => {
        setState(preState => {
            return {
                ...preState,
                fileList: [file],
            };
        });
        return false;
    };
    const onRemove = () => {
        setState(preState => {
            return {
                ...preState,
                fileList: [],
            };
        });
    };
    const handleOk = () => {
        props.form.validateFields((err, values) => {
            if (!err) {
                requestCreate(
                    {
                        ...values.merchantInfo,
                        merchant_account: values.merchant_account,
                        method: values.method,
                        router: values.router,
                        multi_number: values.multi_number,
                        task_name: values.task_name,
                    },
                    values.files.file,
                ).then(error => {
                    if (error) return message.error(error);
                    handleUpdateModalVisible();
                    onOk && onOk();
                });
            }
        });
    };
    const handleChangeBaseApi = (_: any, options: any) => {
        if (options && options.props) {
            const {props} = options;
            const info = props['data-props'];
            setFieldsValue({
                method: info.method,
                router: info.router,
            });
            const merchantInfos = getFieldValue('merchantInfo');
            setFieldsValue({
                merchantInfo: {
                    ...merchantInfos,
                    is_crypto: info.is_crypto,
                    api_name: info.name,
                },
            });
        } else {
            setFieldsValue({
                merchantInfo: {},
                method: '',
                router: '',
            });
        }
    };
    const handleChangemerchant = (_: any, options: any) => {
        if (options && options.props) {
            const {props} = options;
            const info = props['data-props'];
            setFieldsValue({
                merchantInfo: {
                    app_key: info.merchant.app_key,
                    app_secret: info.merchant.app_secret,
                },
                method: '',
                router: '',
                interfaceId: undefined,
            });
        } else {
            setFieldsValue({
                merchantInfo: {},
                method: '',
                router: '',
                interfaceId: undefined,
            });
        }
    };
    getFieldDecorator('merchantInfo', {initialValue: {}});
    return (
        <>
            {React.isValidElement(children) ? React.cloneElement(children, {onClick: handleUpdateModalVisible}) : null}
            <Modal
                title='创建任务'
                visible={modalState.visible}
                width={800}
                onOk={handleOk}
                onCancel={handleUpdateModalVisible}
            >
                <Form {...formItemLayout}>
                    <Form.Item label='任务名称'>
                        {getFieldDecorator('task_name')(<Input placeholder='请输入任务名称' />)}
                    </Form.Item>
                    <Form.Item label='商户名称'>
                        {getFieldDecorator('merchantId', {
                            initialValue: undefined,
                            rules: [
                                {
                                    required: true,
                                    message: '请选择商户!',
                                },
                            ],
                        })(<MerchantSelect api_ids={getFieldValue('interfaceId')} onChange={handleChangemerchant} />)}
                    </Form.Item>
                    <Form.Item label='接口选择'>
                        {getFieldDecorator('interfaceId', {
                            rules: [
                                {
                                    required: true,
                                    message: '请选择接口!',
                                },
                            ],
                        })(
                            <BaseApiSelect
                                placeholder='请选择接口'
                                disabled={!getFieldValue('merchantId')}
                                merchant_id={getFieldValue('merchantId')}
                                onChange={handleChangeBaseApi}
                            />,
                        )}
                    </Form.Item>
                    <Form.Item label='请求方式'>
                        {getFieldDecorator('method')(<span>{getFieldValue('method') || '--'}</span>)}
                    </Form.Item>
                    <Form.Item label='接口地址'>
                        {getFieldDecorator('router')(
                            <Tooltip title={getFieldValue('router')} placement='topLeft'>
                                <span>{getFieldValue('router') || '--'}</span>
                            </Tooltip>,
                        )}
                    </Form.Item>
                    <Form.Item label='使用商户账号'>
                        {getFieldDecorator('merchant_account', {
                            valuePropName: 'checked',
                            initialValue: false,
                        })(<Switch checkedChildren='是' unCheckedChildren='否' />)}
                    </Form.Item>
                    <Form.Item label='并发数'>
                        {getFieldDecorator('multi_number', {
                            initialValue: 1,
                            rules: [
                                {
                                    required: true,
                                    message: '请设置并发数!',
                                },
                            ],
                        })(<InputNumber min={1} step={5} />)}
                    </Form.Item>
                    <Form.Item label='任务文件'>
                        {getFieldDecorator('files', {
                            rules: [
                                {
                                    required: true,
                                    message: '请选择任务文件!',
                                },
                            ],
                        })(
                            <Upload
                                onRemove={onRemove}
                                accept='.xlsx'
                                fileList={state.fileList}
                                beforeUpload={beforeUpload}
                            >
                                <Button>
                                    <Icon type='upload' /> 上传
                                </Button>
                            </Upload>,
                        )}
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};
export default Form.create<Iprops & FormComponentProps>({name: 'createTask'})(createTask);
