import React, { Component } from "react";
import { Icon, message } from "antd";
import {getBase64} from '@/util'
import "./index.scss";

export default class ButtonAdd extends Component {
    state = {
        loading: false
    };

    checkFile(file) {
        if (!file) return false;

        const isJPG = file.type === "image/jpeg";
        if (!isJPG) {
            message.error("你只能上传JPG格式的图片哦");
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error("上传图片大小必须小于2M");
        }
        return isJPG && isLt2M;
    }

    handleChange(files) {
        let curFile = files[0];

        if (!this.checkFile(curFile)) return;
        getBase64(curFile, async imageUrl => {
            this.props.changeFile(this.props.imageKey,imageUrl)
        });
    }

    render() {
        const uploadButton = (
            <div>
                <Icon type={this.state.loading ? "loading" : "plus"} />
                <div className="ant-upload-text">Upload</div>
            </div>
        );
        const imageUrl = this.props.imageUrl;

        return (
            <div className="upload-wrap">
                <div className="upload-select">
                    <input
                        type="file"
                        onChange={e => {
                            this.handleChange(e.target.files);
                        }}
                    />
                    {imageUrl ? (
                        <img src={imageUrl} alt="avatar" />
                    ) : (
                        uploadButton
                    )}
                </div>
            </div>
        );
    }
}
