import * as React from 'react';
import { FastUpload, FastButton, FastIcon, fastMessage } from "components/ui";
import { uploadFile } from "utils/upload";
import { FormTypes } from "../../types";

function UploadFile(props: FormTypes.FormItem.FormAtomicUploadProps) {
  const { config, values, validateTrigger } = props;
  const { key, type, isRaw, accept } = config;

  const handleChange = (value: any) => {
    // eslint-disable-next-line react/destructuring-assignment
    props[validateTrigger](value);
  };

  const handleBeforeUpload = (file: File) => {
    if (
      accept &&
      !accept.some((acceptItem: string) => file.name.includes(acceptItem))
    ) {
      fastMessage.warning(`${file.name}文件格式错误`);
      return FastUpload.LIST_IGNORE;
    }
    if (isRaw) {
      handleChange(file);
    } else {
      uploadFile(file).then((url: any) => {
        handleChange(url);
      });
    }

    return false;
  };

  if (isRaw) {
    return (
      <FastUpload
        name="file"
        beforeUpload={handleBeforeUpload}
        onRemove={() => handleChange("")}
        maxCount={1}
      >
        <FastButton icon={<FastIcon.UploadOutlined />}>上传</FastButton>
      </FastUpload>
    );
  }

  if (type === "multuploadfile") {
    return (
      <FastUpload
        beforeUpload={handleBeforeUpload}
        fileList={values[key].map((url: string) => ({
          url,
          name: url,
          uid: url,
        }))}
      >
        <FastButton icon={<FastIcon.UploadOutlined />}>上传</FastButton>
      </FastUpload>
    );
  }

  return (
    <FastUpload
      name="file"
      beforeUpload={handleBeforeUpload}
      fileList={
        values[key]
          ? [{ url: values[key], name: values[key], uid: values[key] }]
          : []
      }
      onRemove={() => handleChange("")}
      maxCount={1}
      accept="docx"
    >
      <FastButton icon={<FastIcon.UploadOutlined />}>上传</FastButton>
    </FastUpload>
  );
}

export default UploadFile;
