import { FC, useEffect, useState } from 'react';
import { Form, Input, message, Modal, ModalProps } from 'antd';
import { Uploader } from '~/components/uploader';
import { UploadOutlined } from '@ant-design/icons';
import { RentManageAPI } from '~/api';
import { InterDataType, InterReqType } from '~/api/interface';
import { addType, getTypeListType } from '~/api/interface/rentManageType';

//类型类别返回类型
type rentTypeListType = InterDataType<getTypeListType>['list'];
//新增租赁类型参数类型
type addRentTypeParameters = InterReqType<addType>;

interface selfProps {
  onCancel: () => void;
  onOk: () => void;
  currentRentTypeItem: rentTypeListType[0] | undefined;
}
const AddOrEditTypeModal: FC<ModalProps & selfProps> = ({
  open,
  onCancel,
  onOk,
  currentRentTypeItem,
}) => {
  const [form] = Form.useForm<addRentTypeParameters>();
  const [fileList, setFileList] = useState<any>([]);

  const handleCancel = () => {
    form.resetFields();
    setFileList([]);
    onCancel();
  };
  const handelOk = () => {
    form.validateFields().then((values: any) => {
      RentManageAPI[currentRentTypeItem ? 'editTypeReq' : 'addTypeReq']({
        ...values,
        id: currentRentTypeItem ? currentRentTypeItem.id : undefined,
      }).then(({ code }) => {
        if (code === '200') {
          message.success(currentRentTypeItem ? '编辑成功' : '新增成功');
          form.resetFields();
          setFileList([]);
          onOk();
        }
      });
    });
  };
  //上传成功
  const uploadSuccess = (fileList: any) => {
    form.setFieldValue('url', fileList[0].url);
    setFileList(fileList);
  };

  useEffect(() => {
    if (currentRentTypeItem) {
      form.setFieldsValue({
        name: currentRentTypeItem.name,
        url: currentRentTypeItem.url,
      });
      setFileList([
        { id: Math.random(), uid: Math.random(), url: currentRentTypeItem.url, name: '类型图片' },
      ]);
    }
  }, [currentRentTypeItem]);

  return (
    <Modal open={open} title='新增类型' onCancel={handleCancel} onOk={handelOk}>
      <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
        <Form.Item
          label='类型名称'
          name='name'
          rules={[{ required: true, message: '请输入类型名称' }]}
        >
          <Input placeholder='请输入类型名称' maxLength={30} />
        </Form.Item>
        <Form.Item label='图片' name='url' rules={[{ required: true, message: '请上传图片' }]}>
          <Uploader
            fileUpload
            listType='picture-card'
            onChange={uploadSuccess}
            defaultFileList={fileList}
          >
            <UploadOutlined />
          </Uploader>
        </Form.Item>
      </Form>
    </Modal>
  );
};
export default AddOrEditTypeModal;
