import React, { useState } from 'react';
import { LoadingOutlined, UploadOutlined } from '@ant-design/icons';
import { Button, message, Upload } from 'antd';
import { saveImportPerson } from '@/services/invoicePerson'

function beforeUpload(file) {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  if (!isExcel) {
    message.error('请上传excle表格（务必通过模板下载修改）');
  }
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error('文件大小必须小于 10MB!');
  }

  return isExcel && isLt10M;
}


export default (props) => {
  const { onChange, id, refrash } = props;

  const [loading, setLoading] = useState(false);

  const handleChange = info => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'error') {
      setLoading(false);
      refrash()
      return;
    }

    if (info.file.status === 'done') {
      setLoading(false);
      onChange(info.file.response);
    }
  };
  function uploadFile({ file, onSuccess, onError }) {
    const formData = new FormData();
    formData.append('file', file);
    saveImportPerson(formData, id).then((url) => {
      onSuccess(url, file)
    }).catch((e) => {
      onError(e)
    });

    return {
      abort: () => { },
    };
  }
  return (
    <Upload
      customRequest={uploadFile}
      showUploadList={false}
      beforeUpload={beforeUpload}
      onChange={handleChange}
    >
      <Button type="primary" disabled={loading} icon={loading ?
        <LoadingOutlined /> : <UploadOutlined />}>上传</Button>
    </Upload>
  );
}
