/** @format */

import * as React from 'react';
import {Form, Upload, Icon, notification, Tooltip, Typography} from 'antd';
import {FormComponentProps} from 'antd/es/form';
import ProviderApiSelect from '../../../../components/select/providerApi';
import Button from '../../../../components/button';
import {useCreateTasks} from '../../../../service/tasks';
import ModalForm from '../../../../components/modalForm';
const {Text, Paragraph} = Typography;

const formItemLayout = {
    labelCol: {
        xs: {span: 24},
        sm: {span: 4},
    },
    wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
    },
};
interface IcreateTasks extends FormComponentProps {
    onOk?: () => void;
}
interface Istate {
    visible: boolean;
    provideOptions: {
        api_name: string;
        provider_api_id: number;
        thirdpart_host: string;
        thirdpart_api_router: string;
        platform_code: string;
    };
}
const sourceCreateTaskForm: React.FC<IcreateTasks> = props => {
    const {form, onOk, children} = props;
    const {getFieldDecorator, getFieldValue, setFieldsValue, validateFieldsAndScroll, resetFields} = form;
    const [modalState, setModalState] = React.useState({
        visible: false,
    });
    const [state, setState] = React.useState<Istate>({
        visible: false,
        provideOptions: {
            api_name: '',
            provider_api_id: 0,
            thirdpart_host: '',
            thirdpart_api_router: '',
            platform_code: '',
        },
    });
    const [createState, requestCreate] = useCreateTasks();

    const handleChangeInterface = (_: any, options: any) => {
        const provideOptions = options.props['data-props'];
        setState(preState => ({
            ...preState,
            provideOptions: {
                api_name: provideOptions.api_name,
                provider_api_id: provideOptions.provider_api_id,
                thirdpart_host: provideOptions.thirdpart_host,
                thirdpart_api_router: provideOptions.thirdpart_api_router,
                platform_code: provideOptions.provider_api_code,
            },
        }));
        setFieldsValue({
            router: provideOptions.thirdpart_host + '/' + provideOptions.thirdpart_api_router,
        });
    };
    //提交数据
    const handleSubmit = () => {
        validateFieldsAndScroll((error, values) => {
            if (error) return;
            const {tasks} = values;
            const fileFormData = new FormData();
            fileFormData.append('file', tasks[0].originFileObj);
            requestCreate(state.provideOptions, fileFormData).then(error => {
                if (error) {
                    return notification.error({
                        message: '创建批量任务失败!',
                        description: error,
                    });
                }
                handleUpdateModalVisible();
                onOk && onOk();
            });
        });
    };

    const HandleRemoveFile = () => {
        setFieldsValue({
            tasks: [],
        });
    };

    const handleUpdateModalVisible = () => {
        setModalState(preState => ({...preState, visible: !preState.visible}));
    };
    const normFile = (e: any) => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList.slice(e.fileList.length - 1);
    };
    React.useEffect(() => {
        if (!modalState.visible) {
            resetFields();
        }
    }, [modalState.visible]);
    return (
        <>
            {React.isValidElement(children) &&
                React.cloneElement(children, {
                    onClick: handleUpdateModalVisible,
                })}
            <ModalForm
                loading={createState.loading}
                onCancel={handleUpdateModalVisible}
                visible={modalState.visible}
                error={null}
                title="批量创建任务"
                onOk={handleSubmit}
            >
                <Form {...formItemLayout}>
                    <Form.Item label="接口">
                        {getFieldDecorator('interface', {
                            rules: [
                                {
                                    required: true,
                                    message: '请选择接口!',
                                },
                            ],
                        })(<ProviderApiSelect provider_id="" onChange={handleChangeInterface} />)}
                    </Form.Item>
                    <Form.Item label="接口路径">
                        {getFieldDecorator('router', {
                            initialValue: '',
                        })(
                            <Tooltip placement="topLeft" title={getFieldValue('router')}>
                                <Paragraph ellipsis copyable={!!getFieldValue('router')}>
                                    {getFieldValue('router') || '--'}
                                </Paragraph>
                            </Tooltip>,
                        )}
                    </Form.Item>
                    <Form.Item label="任务文件">
                        {getFieldDecorator('tasks', {
                            valuePropName: 'fileList',
                            getValueFromEvent: normFile,
                        })(
                            <Upload
                                onRemove={HandleRemoveFile}
                                accept=".xlsx"
                                beforeUpload={() => {
                                    return false;
                                }}
                            >
                                <Button>
                                    <Icon type="upload" />
                                    点击上传
                                </Button>
                            </Upload>,
                        )}
                    </Form.Item>
                </Form>
            </ModalForm>
        </>
    );
};
export default Form.create<IcreateTasks>({name: 'sourceCreateTaskForm'})(sourceCreateTaskForm);
