import React, { Component } from "react";
import { Upload, Icon } from "antd";
const { Dragger } = Upload;
class Read extends Component {
  constructor(props) {
    super(props);
    this.state = {
      fileList: undefined,
      fileContent: undefined,
      fileName: undefined,
    };
  }

  onAttachmentRemove = (file) => {
    this.setState({
      fileList: undefined,
      fileContent: undefined,
      fileName: undefined,
    });
  };

  beforeUpload = (file) => {
    const { fileList } = this.state;
    const { size } = this.props;
    const isLt100M = file.size / 1024 / 1024 < size;
    if (fileList && fileList.length > 0) {
      this.props.showNotification("文件已存在, 请删除后再上传");
      return false;
    } else if (!isLt100M) {
      this.props.showNotification(`文件大小必须小于${size}MB!`);
      return false;
    } else {
      this.setState({
        fileList: [file],
        fileName: file.name,
      })
    }
  };

  // 上传 文件转base64
  customRequest = (option) =>{
    const formData = new FormData();
    formData.append('files[]', option.file);
    const reader = new FileReader();
    reader.readAsDataURL(option.file);
    const {load} = this.props;
    reader.onloadend = function(e){
      if(e.target.result){
        option.onSuccess();
        const base64 = e.target.result.substring(e.target.result.indexOf('base64')+7, e.target.result.length);
        load({
          fileName: option.file.name,
          fileContent: base64
        });
      }
    }
  }

  render() {
    //判断是否已经提交，如已提交评论则上一条评论数据清除
    const { icon, size } = this.props;
    const { fileList, fileName } = this.state;
    const upload = {
      name: "file",
      fileList: fileList,
      customRequest: this.customRequest,
      onRemove: this.onAttachmentRemove,
      beforeUpload: this.beforeUpload,
    };

    return (
      <Dragger {...upload} className={this.props.className}>
        {fileName ? (
          <p className="ant-upload-text">{fileName}</p>
        ) : (
          <div>
            {icon || <Icon type="inbox" />}
            <p className="ant-upload-text">
              拖动文件或<span className="color-blue">点击此处上传</span>
            </p>
            {/* <p className="mt10">
              暂仅支持文本格式，不支持图片,excel等不可以txt读取的文件
            </p> */}
            <p className="mt10">
              文件名请使用英文且不得超过{size}MB
            </p>
          </div>
        )}
      </Dragger>
    );
  }
}
export default Read;
