/** @format */

import * as React from 'react';
import Form, {FormComponentProps} from 'antd/es/form';
import ModalForm from '../../../../components/modalForm';
import Input from '../../../../components/input';
import {useGroupList} from '../../../../service/accountList';
interface Iprops {
    savingGroup?: (val: {name: string}) => void;
    visible?: boolean;
    onCancel?: () => void;
    loading?: boolean;
}
const AddGroup = React.forwardRef((props: FormComponentProps & Iprops, ref) => {
    const {form, savingGroup, visible, onCancel, loading} = props;
    const {validateFieldsAndScroll, getFieldDecorator} = form;
    const [groupListState, requestGroupList] = useGroupList();
    const handleAddEnsure = () => {
        validateFieldsAndScroll((errors, val) => {
            if (errors) return;
            savingGroup(val);
        });
    };
    const validName = (rule, value, callback) => {
        if (value && groupListState.names.includes(value)) {
            callback('角色名重复，请重设');
        }
        callback();
    };

    return (
        <ModalForm loading={loading} onOk={handleAddEnsure} onCancel={onCancel} title="添加分组" visible={visible}>
            <Form>
                <Form.Item label="请输入角色名">
                    {getFieldDecorator('name', {
                        initialValue: '',
                        rules: [
                            {
                                required: true,
                                message: '请输入角色名',
                            },
                            {
                                validator: validName,
                            },
                        ],
                    })(<Input />)}
                </Form.Item>
            </Form>
        </ModalForm>
    );
});

export default Form.create<FormComponentProps & Iprops>({name: 'AddGroup'})(AddGroup);
