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

function beforeUpload(file) {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel';
  if (!isExcel) {
    message.error('请上传 excel表格!');
  }
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error('文件大小必须小于 10MB!');
  }

  return isExcel && isLt10M;
}

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

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

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

    if (info.file.status === 'done') {
      setLoading(false);
      onChange(info.file.response);
    }
  };

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