import React, { Component } from 'react';
import { Upload } from '@easyv/antd';
import message from 'components/message';

import defaultImg from '../../../../images/default.png';
import styles from './UploadThumb.less';

interface IProps {
  imgUrl?: string;
  maxSize?: number;
  handleImgChange: (File) => void;
}

interface IState {
  imgUrl?: string;
}

export default class UploadThumb extends Component<IProps, IState> {
  constructor(props) {
    super(props);
    this.state = {
      imgUrl: this.props.imgUrl
    };
  }

  handleBeforeUpload = (file) => {
    const { maxSize = 1024 * 200 } = this.props;
    const isLarger = file.size > maxSize;
    if (isLarger) {
      message.error(`文件大小超出${getSize(maxSize)}`);
    } else {
      this.setState({
        imgUrl: window.URL.createObjectURL(file)
      });
      this.props.handleImgChange(file);
    }
    return false;
  };

  handleImageError = () => {
    this.setState({
      imgUrl: defaultImg
    });
  };

  render() {
    const { imgUrl } = this.state;

    return (
      <Upload
        listType="picture-card"
        showUploadList={false}
        accept="image/*"
        beforeUpload={this.handleBeforeUpload}
        className={styles.thumb}>
        {!imgUrl ? (
          <div style={{ color: '#999' }}>
            <i className="icon iconfont icon-btn_addgroup" />
            <div>点击上传</div>
          </div>
        ) : (
          <img style={{ width: 102, height: 66 }} src={imgUrl} onError={this.handleImageError} />
        )}
      </Upload>
    );
  }
}

function getSize(size) {
  return size / 1024 < 1024 ? `${Math.floor(size / 1024)}KB` : `${Math.floor(size / 1024 / 1024)}M`;
}
