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

export default (({ imageUrl, getImageUrl }) => {
  const [loading, setLoading] = useState(false);
  const [url, setUrl] = useState(undefined);

  useEffect(() => {
    if (imageUrl) {
      setUrl(imageUrl);
    }
  }, [imageUrl])

  function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  function handleChange(info) {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      let filelist = info.fileList && info.fileList.length>0 && info.fileList[info.fileList.length-1];
      if(filelist && filelist.response && filelist.response.status === -1){
        setLoading(false)
        setUrl(null)
        message.error(filelist.response.message)
      }else{
        getBase64(info.file.originFileObj, imageUrl =>{
          setLoading(false),
          getImageUrl(filelist && filelist.response),
          setUrl(imageUrl)
        });
      }
    }
  };
  function beforeUpload(file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传图片!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小必须小于2MB!');
    }
    return isJpgOrPng && isLt2M;
  }
  const uploadButton = (
    <div>
      {loading ? <Spin size={"small"} /> : <i className="iconfont icon-tianjiadaohang font-20" />}
    </div>
  );
  return (
    <Upload 
      name="file"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      action={getUploadActionUrl()}
      beforeUpload={beforeUpload}
      onChange={handleChange}
    >
      {url ? <img src={url} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
    </Upload>
  )
})