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

class ImageListUpload extends React.Component {
  state = {
    previewVisible: false,
    previewImage: '',
    loadding: false,
  };

  getFileList = () => {
    return (this.props.value || []).map((img, inx) => ({ uid: inx, url: img, status: 'done' }))
  }

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async file => {
    this.setState({
      previewImage: file.url ,
      previewVisible: true,
    });
  };

  handleChange = (e) => {
    if (e.file.status === "uploading") {
      this.setState({ loading: true });
      return;
    }

    if (e.file.state === 'removed') {
      const fileList = (this.props.value || []).filter(x => x != e.file.url);
      this.props.onChange(fileList);
    }

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

    //   if (e.file.response && e.file.response.url) {
    //     if (typeof this.props.onChange === 'function') {
    //       const fileList = this.getFileList()
    //       this.props.onChange([...fileList || [], e.file.response.url]);
    //     }
    //   }
    // }
  };

  handleUploadSucess = (url) => {
    this.setState({ loading: false });
    if (typeof this.props.onChange === 'function') {
      const fileList = this.props.value || [];
      this.props.onChange([...fileList, url]);
    }
  }

  render() {
    const { previewVisible, previewImage } = this.state;
    const fileList = this.getFileList();

    const uploadButton = (
      <div>
        <Icon style={{ fontSize: '2em', color: '#aaa' }} type={this.state.loading ? "loading" : "plus"}  />
      </div>
    );
    return (
      <div className="clearfix">
        <Upload
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
          { ...uploaderProps }
          onSuccess={this.handleUploadSucess}
        >
          {(fileList || images).length >= 8 ? null : uploadButton}
        </Upload>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    );
  }
}

export default ImageListUpload;
