import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Upload, Icon, Message } from 'amos-antd' ;
import { OltSerUrl } from '../../../consts/urlConsts';
import './common.scss';

const HEXSIZE = 1024;
/**
 * 图片上传，实现图片的显示以及图片路径的返回功能，图片提交由调用者自己实现
 *
 * @class UpLoadImg
 * @extends {Component}
 */
class UpLoadImg extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      file: undefined,
      imageUrl: ''
    };
  }

  /**
   *
   *图片加载到浏览器
   * @memberof UpLoadImg
   */
  getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };

  /**
   *监听
   *
   * @memberof UpLoadImg
   */
  handleChange = (info) => {
    this.setState({ file: info.file });
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, imageUrl => this.setState({
        imageUrl,
        loading: false
      }));
      this.props.setImgFile(info.file.originFileObj);
    }
  }

  /**
   *
   *图片校验
   * @memberof UpLoadImg
   */
  beforeUpload = (file) => {
    var pattern = /image\/(gif|jpeg|png|jpg|bmp)$/;
    const isImg = pattern.test(file.type);
    if (!isImg) {
      Message.error('请选择符合格式的图片！（gif|jpeg|png|jpg|bmp）');
    }
    const isLt2M = file.size / HEXSIZE / HEXSIZE < 2;
    if (!isLt2M) {
      Message.error('图片最大为2MB');
    }
    return isImg && isLt2M;
  };

  render() {
    let { style,defaultImg } = this.props;
    const uploadButton = (
      <div>
        {this.state.loading ? <Icon type={'loading'} /> : <img src={defaultImg} alt="" style={style} />  }
        <div style={{ 'padding-top': '10px' }}>上传图片（小于2MB）</div>
      </div>
    );
    const imageUrl = this.state.imageUrl;
    const url = OltSerUrl.addDevice;
    return (
      <Upload
        name="avatar"
        listType="picture-card"
        showUploadList={false}
        action={url}
        beforeUpload={this.beforeUpload}
        onChange={this.handleChange}
      >
        {imageUrl ? <img src={imageUrl} alt="" style={style} /> : uploadButton}
      </Upload>
    );
  }
}

UpLoadImg.propTypes = {
  setImgFile: PropTypes.func,
  style: PropTypes.object,
  defaultImg: PropTypes.string
};

UpLoadImg.defaultProps = {
  style: { 'max-width': '300px', 'max-height': '158px' },
  defaultImg: `${OltSerUrl.fetchDeviceImg}/default.png`
};
export default UpLoadImg;
