/** @format */

import * as React from 'react';
import {decodeBase64} from '../../../../utils/base64';
import ProviderApiForm, {UpdateAPiProps} from './providerApiForm';
import message from '../../../../components/message';
import {useInsertApi} from '../../../../service/provideApi';

interface Iprops {
    onOk?: () => void;
}
const CreateApi: React.FC<Iprops> = props => {
    const id = Number(new URLSearchParams(decodeBase64(location.search.slice(1))).get('id'));
    const {children, onOk} = props;
    const [insertState, requestInsert] = useInsertApi();
    const [state, setState] = React.useState({
        visible: false,
    });
    const handleUpdateVisilbe = () => {
        setState(preState => ({...preState, visible: !preState.visible}));
    };
    const handleSubmit = (values: UpdateAPiProps) => {
        requestInsert({
            provider_id: id,
            ...values,
        }).then(error => {
            if (error) return message.error(error);
            handleUpdateVisilbe();
            onOk && onOk();
        });
    };
    return (
        <>
            {React.isValidElement(children) && React.cloneElement(children, {onClick: handleUpdateVisilbe})}
            <ProviderApiForm
                type='insert'
                onSubmit={handleSubmit}
                onCancel={handleUpdateVisilbe}
                visible={state.visible}
                title='新增'
                loading={insertState.loading}
            />
        </>
    );
};
export default CreateApi;
