import React, { useState, useRef, useCallback } from "react";
import { getUploadLogoActionUrl, getUrl } from "educoder";
import { Upload, Icon, message } from "antd";
import axios from 'axios';

export default ({ logo_url, onChange }) => {
  const base64Ref = useRef(null);
  const getBase64 = useCallback((file) => {
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.addEventListener("load", () => {
        base64Ref.current = reader.result;
        resolve(reader.result);
      });
      reader.readAsDataURL(file);
    });
  }, []);
  const [isLoading, setLoading] = useState(() => {
    if (logo_url) {
      return true;
    }
    return false;
  });
  const [imageUrl, setUrl] = useState(() => {
    if (logo_url) {
      return getUrl("/"+logo_url);
    }
    return undefined;
  });
  const handleChange = useCallback(({ file }) => {
    if (file.status === "uploading") {
      setLoading(true);
      return;
    }else if (file.status === "done") {
      onChange("t");
      setLoading(false);
      setUrl(base64Ref.current);
    }else if (file.size > 2 ** 20 * 2) {
      setLoading(false);
      setUrl("");
    }
  }, []);
  const verifyFile = useCallback((f) => {
    if(imageUrl){
      axios.post('/resumes/destroy_logo.json');
    }
    const isProperSize = f.size / 1024 / 1024 < 2; //2MB
    if (!isProperSize) {
      message.error("照片超过2MB");
    }
    return isProperSize;
  },[imageUrl]);
  return (
    <React.Fragment>
      <Upload
        accept=".jpg,.jpeg"
        listType="picture-card"
        showUploadList={false}
        name="image"
        action={getUploadLogoActionUrl()}
        beforeUpload={verifyFile}
        transformFile={getBase64}
        onChange={handleChange}
      >
        {imageUrl ? (
          <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
        ) : (
          <Icon type={isLoading ? "loading" : "plus"} />
        )}
      </Upload>
    </React.Fragment>
  );
};
