import { App, Form, Input, Modal } from 'antd';
import React from 'react';
import { useAjax } from '@/Hook/useAjax';
import { addProjectGroupsApi, editProjectGroupsApi } from '../../API/groupManage';

interface GroupModalProps {
    initialValues?: any
    visible?: boolean
    onChange?: () => void
    onClose?: () => void
}


const GroupModal: React.FC<GroupModalProps> = ({ initialValues, visible, onChange, onClose }) => {

    /****************************************/
    const { message } = App.useApp()
    const [form] = Form.useForm();
    const addProjectGroups = useAjax((params) => addProjectGroupsApi(params))
    const editProjectGroups = useAjax((params) => editProjectGroupsApi(params))
    /****************************************/

    const handleOk = () => {
        form.validateFields().then((values) => {
            if (initialValues?.id) {
                editProjectGroups.run({ ...values, groupId: initialValues.id }).then((res) => {
                    if (res?.data) {
                        message.success('修改成功')
                        onChange?.()
                    }
                })
            } else {
                addProjectGroups.run(values).then((res) => {
                    if (res?.data) {
                        message.success('添加成功')
                        onChange?.()
                    }
                })
            }

        }).catch((err) => {
            console.log('err', err)
            form.submit()
        });
    }

    return <Modal
        title={<strong>{initialValues?.id ? '修改' : '新增'}新增项目组</strong>}
        open={visible}
        onCancel={onClose}
        width={500}
        onOk={handleOk}
        confirmLoading={addProjectGroups.loading}
    >
        <Form
            form={form}
            name="newGRoup"
            labelAlign='left'
            labelCol={{ span: 5 }}
            colon={false}
            scrollToFirstError={{
                behavior: 'smooth',
                block: 'center'
            }}
            onFinishFailed={({ errorFields }) => {
                message.error(errorFields?.[0]?.errors?.[0])
            }}
            preserve={true}
            initialValues={initialValues}
        >
            <Form.Item label={<strong>项目组名称</strong>} name="name" rules={[{ required: true, message: '请输入项目组名称!' }]}>
                <Input placeholder='请输入项目组名称' allowClear />
            </Form.Item>
            <Form.Item label={<strong>描述</strong>} name="description">
                <Input.TextArea placeholder='请输入项目组描述' allowClear />
            </Form.Item>
        </Form>
    </Modal>
};

export default React.memo(GroupModal);