import { FC, useEffect } from 'react';
import { Form, Input, Modal, message, ModalProps } from 'antd';
import { MakeManageAPI } from '~/api';

interface selfProps {
  makeItem: any;
  onOk: () => void;
  handleCancel: () => void;
}

const AddOrEditModal: FC<ModalProps & selfProps> = ({
  open,
  handleCancel,
  onOk,
  title,
  makeItem,
}) => {
  const [form] = Form.useForm<{ brandName: string }>();
  const submit = () => {
    form.validateFields().then((value) => {
      MakeManageAPI[makeItem ? 'editBrandInfo' : 'addBrandInfo']({
        ...value,
        id: makeItem?.id,
      }).then(({ code, message: msg }) => {
        if (code === '200') {
          message.success(makeItem ? '编辑成功' : '新增成功');
          onOk();
          form.resetFields();
        } else {
          message.error(msg);
        }
      });
    });
  };
  const onCancel = () => {
    form.resetFields();
    handleCancel();
  };

  useEffect(() => {
    if (makeItem) {
      form.setFieldsValue({
        brandName: makeItem.brandName,
      });
    }
  }, [makeItem]);
  return (
    <Modal open={open} onOk={submit} onCancel={onCancel} title={title}>
      <Form form={form}>
        <Form.Item
          label='品牌名称'
          name='brandName'
          rules={[{ required: true, message: '请输入品牌名称!' }]}
        >
          <Input placeholder='请输入品牌名称' maxLength={10} />
        </Form.Item>
      </Form>
    </Modal>
  );
};
export default AddOrEditModal;
