/** @format */

import * as React from 'react';
import md5 from 'md5';
import MerchantForm from './merchantForm';
import message from '../../../../components/message';
import {ReciveMerchantProps, useInsertMerchant} from '../../../../service/merchant';

interface Iprops {
    onOk?: () => void;
}
const InsertMerchant: React.FC<Iprops> = props => {
    const {children, onOk} = props;
    const [state, setState] = React.useState({
        visible: false,
    });
    const [insertState, requestInsert] = useInsertMerchant();
    const handleUpdateModalVisible = () => {
        setState(preState => ({...preState, visible: !preState.visible}));
    };
    const handleSubmit = (values: ReciveMerchantProps) => {
        requestInsert({
            ...values,
            merchant_parssword: values.merchant_parssword ? md5(values.merchant_parssword) : '',
        }).then(error => {
            if (error) return message.error(error);
            handleUpdateModalVisible();
            onOk && onOk();
        });
    };
    return (
        <MerchantForm
            type="insert"
            loading={insertState.loading}
            onSubmit={handleSubmit}
            title="新增"
            visible={state.visible}
            onCancel={handleUpdateModalVisible}
        >
            {React.isValidElement(children) &&
                React.cloneElement(children, {
                    onClick: handleUpdateModalVisible,
                })}
        </MerchantForm>
    );
};
export default InsertMerchant;
