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

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

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

  /**
   *监听
   *
   * @memberof UpLoadIcon
   */
  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 UpLoadIcon
   */
  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 < 100;
    if (!isLt2M) {
      Message.error('图片最大为 100Kb!');
    }
    return isImg && isLt2M;
  };

  render() {
    let { style,defaultImg,enable } = this.props;
    let imageContent = (<img src={require('./../../../../assets/iot/deviceManage/upload.jpg')} alt='' />);
    const uploadButton = (
      <div className='upload-icon-panel'>
        {this.state.loading ? <Icon type={'loading'} /> : defaultImg ? <img src={defaultImg} alt="" style={style} /> : imageContent }
      </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}
        disabled={!enable}
      >
        {imageUrl ?  <img src={imageUrl} alt="" style={style} /> : uploadButton }
      </Upload>
    );
  }
}

UpLoadIcon.propTypes = {
  setImgFile: PropTypes.func,
  style: PropTypes.object,
  defaultImg: PropTypes.string,
  enable: PropTypes.bool
};

UpLoadIcon.defaultProps = {
  style: { 'position': 'relative','top': '-10px' },
  enable: true
  // defaultImg: `${OltSerUrl.fetchDeviceImg}/device_default.png`
};
export default UpLoadIcon;
