import React, { useEffect, useState } from "react";
import { Upload, Button } from 'antd';
import { appendFileSizeToUploadFileAll } from 'educoder';
import { httpUrl } from '../task/fetch';

function Uploads({ className, size, actionUrl, fileList, showNotification, load }) {
  const [files, setFiles] = useState(undefined);

  useEffect(() => {
    if (fileList) {
      init();
    }
  }, [fileList]);

  function init() {
    let f = appendFileSizeToUploadFileAll(fileList);
    setFiles(f);
  }
  function onAttachmentRemove(file) {
    if (!file.percent || file.percent === 100) {
      deleteAttachment(file);
      return false;
    }
  }
  function deleteAttachment(file) {
    let id = (file.response && file.response.data && file.response.data.id) || file.id;

    // 暂时不直接删除上传的文件，只在最后保存的时候进行修改
    let nf = files.filter(item => {
      let itemId = (item.response && item.response.data && item.response.data.id) || item.id;
      return itemId !== id;
    });
    setFiles(nf);
    backFiles(nf);
  }

  function backFiles(fileList) {
    let filesId = [];
    for (const item of fileList) {
      if (item) {
        let itemId = (item.response && item.response.data && item.response.data.id) || item.id;
        itemId && filesId.push(itemId);
      }
    }
    load && load(fileList, filesId.join());
  }


  function handleChange(info) {
    if (info.file.status === 'uploading' || info.file.status === 'done' || info.file.status === 'removed') {
      let fileList = info.fileList;
      setFiles(appendFileSizeToUploadFileAll(fileList));
      if (info.file.response) {
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].response && !fileList[i].response.data) {
            fileList.splice(i, 1);
          }
        }
        backFiles(fileList);
        if (!info.file.response.data) {
          info.file.response && showNotification(info.file.response.message)
        }
      }
    }
  }

  function beforeUpload(file) {
    const isLt100M = file.size / 1024 / 1024 < size;
    if (!isLt100M) {
      showNotification(`文件大小必须小于${size}MB!`);
    }
    return isLt100M;
  }

  const upload = {
    name: 'file',
    fileList: files,
    action: (httpUrl || actionUrl) + `/busiAttachments/upload`,
    onChange: handleChange,
    onRemove: onAttachmentRemove,
    beforeUpload: beforeUpload,
  };
  return (
    <Upload {...upload} className={className}>
      <Button type="primary">点击上传</Button>
      <span className="ml10 color-grey-9">(你可以上传小于<span className="color-red">{size}MB</span>的文件)</span>
    </Upload>
  )
}
export default Uploads;