import React from 'react';
import message from 'antd/es/message';
import Upload from 'antd/es/upload';
import Button from 'antd/es/button';
import { ConfigConsumer } from '../config-provider';
import { ReactComponent as uploadIcon } from '../icons/upload.svg';
import IconBase from './IconBase';

import './index.less';

export default props => {
  const [fileList, setFileList] = React.useState([]);
  const {
    prefixCls: customizePrefixCls,
    maxLength = 5,
    accept='.csv',
    showRemoveIcon = false,
    ...restProps
  } = props;

  // 处理antd的upload组件的action
  const handleBeforeUpload = () => {
    return false;
  };

  const handleUploadChange = ({ fileList }) => {
    const list = fileList[fileList.length - 1];
    if(list.size / 1024 / 1024 < maxLength){
      setFileList([list]);
      props.onChange(list);
    } else {
      message.error(`文件不能超过 ${maxLength}MB!`);
    }
  };

  return <ConfigConsumer>
    {({ getPrefixCls }) => {
      const prefixCls = getPrefixCls('upload-file', customizePrefixCls);
      return <Upload
        accept={accept}
        prefixCls={prefixCls}
        fileList={fileList}
        showUploadList={{ showRemoveIcon }}
        beforeUpload={handleBeforeUpload}
        onChange={handleUploadChange}
        {...restProps}
      >
        <Button className="upload-file-button" l>
          <IconBase fill="currentColor" icon={uploadIcon} /> 上传文件
        </Button>
      </Upload>;
    }}
  </ConfigConsumer>
};
