import * as React from 'react';
import { fastMessage, FastUpload } from "components/ui";
import { verifyImage, uploadImg } from "utils/image";
import { isArray } from "utils/isType";
import { FormTypes } from "../../types";

function UploadImg(props: FormTypes.FormItem.FormAtomicUploadProps) {
  const { config, values, validateTrigger } = props;
  const { key, type, notModify } = config;
  const handleBeforeUpload = (file: any) => {
    const result = verifyImage(file);
    if (result) {
      fastMessage.error(result);
      return false;
    }
    uploadImg(file).then((data: any) => {
      // eslint-disable-next-line react/destructuring-assignment
      props[validateTrigger](
        type === "multuploadimage"
          ? [
              ...values[key],
              {
                url: data.url,
              },
            ]
          : data.url
      );
    });
    return false;
  };

  if (type === "multuploadimage") {
    return (
      <FastUpload
        listType="picture-card"
        className="avatar-uploader"
        beforeUpload={handleBeforeUpload}
        fileList={isArray(values[key]) ? values[key] : [{ url: values[key] }]}
      >
        <div style={{ marginTop: 8 }}>上传</div>
      </FastUpload>
    );
  }

  if (notModify) {
    return (
      <img
        src={values[key]}
        style={{ width: "100%", maxHeight: "100%", objectFit: "contain" }}
        alt="图片"
      />
    );
  }
  return (
    <FastUpload
      name="avatar"
      listType="picture-card"
      className="avatar-uploader"
      beforeUpload={handleBeforeUpload}
      showUploadList={false}
    >
      {values[key] ? (
        <img
          src={values[key]}
          style={{ width: "100%", maxHeight: "100%", objectFit: "contain" }}
          alt="图片"
        />
      ) : (
        <div style={{ marginTop: 8 }}>上传</div>
      )}
    </FastUpload>
  );
}

export default UploadImg;
