import { Form, Input, message, Modal, ModalProps } from 'antd';
import { FC, useEffect } from 'react';
import { InterDataType, InterReqType } from '~/api/interface';
import { listBrandInfoType, rentMakeAddType } from '~/api/interface/rentManageType';
import { RentManageAPI } from '~/api';

//品牌列表返回类型
type makeListType = InterDataType<listBrandInfoType>['list'];
interface selfProps {
  onCancel: () => void;
  onOk: () => void;
  currentRentMakeItem: makeListType[0] | undefined;
}
//新增品牌参数类型
type addRentMakeParameterType = Exclude<InterReqType<rentMakeAddType>, undefined>;

const AddOrEditRentMakeModal: FC<ModalProps & selfProps> = ({
  open,
  onCancel,
  onOk,
  currentRentMakeItem,
}) => {
  const [form] = Form.useForm<addRentMakeParameterType>();

  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  const handleOk = () => {
    form.validateFields().then((values) => {
      RentManageAPI[currentRentMakeItem ? 'editBrandInfo' : 'addBrandInfo']({
        ...values,
        id: currentRentMakeItem ? currentRentMakeItem.id : undefined,
      }).then(({ code }) => {
        if (code === '200') {
          message.success(currentRentMakeItem ? '编辑成功' : '新增成功');
          form.resetFields();
          onOk();
        }
      });
    });
  };

  useEffect(() => {
    if (currentRentMakeItem) {
      form.setFieldValue('brandName', currentRentMakeItem.brandName);
    }
  }, [currentRentMakeItem]);

  return (
    <Modal open={open} onOk={handleOk} onCancel={handleCancel} title='新增品牌'>
      <Form form={form}>
        <Form.Item
          label='品牌名称'
          name='brandName'
          rules={[{ required: true, message: '请输入品牌名称' }]}
        >
          <Input placeholder='请输入品牌名称' maxLength={30} />
        </Form.Item>
      </Form>
    </Modal>
  );
};
export default AddOrEditRentMakeModal;
