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



class ImageUpload extends React.Component {

  state = {
    loading: false,
    previewVisible: false,
    previewImage: '',
    fileList: this.getPropsFileList(),
  };

  componentDidUpdate(prevProps) {
    // 直接 setState 会死循环
    if (prevProps.value !== this.props.value) {
      this.setState({ fileList: this.getPropsFileList() })
    }
  }

  getPropsFileList() {
    return !this.props.value ? [] : [{
      uid: '-1',
      name: 'image.png',
      status: 'done',
      url: this.props.value,
    }]
  }


  handleChange = ({ file, fileList }) => {
    const { status, response } = file
    this.setState({ fileList, loading: status === "uploading" })

    if (typeof this.props.onChange === 'function' && status != "uploading") {
      const image = status === 'done' ? response : undefined
      this.props.onChange(image);
    }
  };

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

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

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

    return (
      <>
      <Upload
        {...uploaderProps}
        listType="picture-card"
        className="avatar-uploader"
        onChange={this.handleChange}
        fileList={this.state.fileList}
        onPreview={this.handlePreview}
      >
        {this.state.fileList.length >= 1 ? null : uploadButton}  
      </Upload>
      <Modal visible={this.state.previewVisible} footer={null} onCancel={this.handleCancel}>
      <img alt="example" style={{ width: '100%' }} src={this.state.previewImage} />
      </Modal>
      </>
    );
  }
}

export default ImageUpload;
