import React, { useEffect, useState } from 'react';
import { Upload , Icon , message } from "antd";
import { getUploadActionUrl } from 'educoder';

function UploadImage({ getImage , url }){
  const [ imageUrl , setImageUrl ] = useState(undefined);
  useEffect(()=>{
    if(url){
      setImageUrl(url);
    }
  },[url])

  function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
    reader.onload = function(e) {
      getImage && getImage(e.target.result);  // 上传的图片的编码
    }
  }
  // 上传前
  function beforeUpload(file){
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('上传的图片只能是JPG或者PNG格式!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('上传的图片不能超过2MB!');
    }
    return isJpgOrPng && isLt2M;
  }
  // 上传完成后
  function handleChange(info){
    if(info && info.file && info.file.status === "done"){
      getBase64(info.file.originFileObj, imageUrl =>
        setImageUrl(imageUrl)
      );
    }
  }
  return(
    <Upload
      name="file"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      action={getUploadActionUrl()}
      beforeUpload={beforeUpload}
      onChange={handleChange}
    >
      {
        imageUrl ? 
        <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
        :
        <div>
          <Icon type={'plus'} />
          <div className="ant-upload-text">点击上传</div>
        </div>
      }
    </Upload>
  )
}
export default UploadImage;