import { MovableModalForm } from '@/components';
import SysRoleGroupController from '@/services/apis/SysRoleGroupController';
import { FormInstance, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { App } from 'antd';
import { useRef, useState } from 'react';

const RoleGroupEditModal: React.FC<{
    data: Partial<API.SysRoleGroupOutput>;
    onFinish: (data?: Partial<API.SysRoleGroupOutput>) => void;
    onClose?: () => void;
}> = ({ data, onFinish, onClose }) => {
    const formRef = useRef<FormInstance>();
    const [visible, setVisible] = useState<boolean>(true);

    const { message } = App.useApp();

    const handleClose = () => {
        setVisible(false);
        setTimeout(() => onClose?.(), 300);
    };

    return (
        <>
            <MovableModalForm
                title={`${data?.id !== 0 ? '修改' : '添加'}角色组`}
                width={480}
                open={visible}
                formRef={formRef}
                initialValues={data}
                modalProps={{
                    centered: true,
                    maskClosable: false,
                    onCancel: () => {
                        formRef?.current?.resetFields();
                        handleClose();
                    },
                }}
                onFinish={async (values: any) => {
                    try {
                        const p: API.AddSysRoleGroupInput = { ...values };
                        if (data.id === 0) {
                            await SysRoleGroupController.add(p);
                        } else {
                            let updateParams = { ...p, id: data.id } as API.UpdateSysRoleGroupInput;
                            await SysRoleGroupController.update(updateParams);
                        }
                        message.success('操作成功！');
                        formRef?.current?.resetFields();
                        onFinish(data.id !== 0 ? p : undefined);
                        handleClose();
                        return true;
                    } catch {
                        message.error('操作失败！');
                        return false;
                    }
                }}
            >
                <ProFormText
                    label="角色组名称"
                    name="name"
                    fieldProps={{ maxLength: 80 }}
                    rules={[{ required: true }]}
                />
                <ProFormTextArea
                    label="备注说明"
                    name="remark"
                    fieldProps={{ maxLength: 200 }}
                />
            </MovableModalForm >
        </>
    );
};

export default RoleGroupEditModal;
