import React from 'react';
import { Upload, Icon, message } from 'antd';
import './style.less';
import { uploaderProps } from '../../utils/upload';



class ImageUpload extends React.Component {
  state = {
    loading: false,
    imageUrl: undefined,
  };

  handleChange = info => {
    if (info.file.status === "uploading") {
      this.setState({ loading: true });
      return;
    }
    
    if (info.file.status === 'removed') {
      this.props.onChange();
    }

    // if (info.file.status === "done") {
    //   this.setState({
    //     loading: false,
    //   })

    //   if (info.file.response && info.file.response.url) {
    //     this.setState({
    //       imageUrl: info.file.response.thumbUrl,
    //     });

    //     if (typeof this.props.onChange === 'function') {
    //       this.props.onChange(info.file.response.url);
    //     }
    //   }
    // }
  };

  handleUploadSucess = (url) => {
    this.setState({ loading: false });
    if (typeof this.props.onChange === 'function') {
      this.props.onChange(url);
    }
  }

  render() {
    const uploadButton = (
      <div>
        <Icon style={{ fontSize: '2em', color: '#aaa' }} type={this.state.loading ? "loading" : "plus"} />
      </div>
    );

    const value = this.props.value;
    return (
      <Upload
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        beforeUpload={this.props.beforeUpload}
        onChange={this.handleChange}
        {...uploaderProps}
        disabled={this.props.disabled}
        onSuccess={this.handleUploadSucess}
      >
        {(this.state.imageUrl || value) ? (
          <img src={this.state.imageUrl || value} alt="avatar" style={{ width: "100%" }} />
        ) : (
            uploadButton
          )}
      </Upload>
    );
  }
}

export default ImageUpload;
