import React, { useCallback, useState } from "react";
import { Upload, Row, message } from "antd";
import styled from "styled-components";
import { UploadButton } from "./Button";
import { getUploadActionUrl } from "educoder";

const Info = styled.div`
  font-size: 14px;
  font-family: MicrosoftYaHei;
  color: rgba(231, 114, 52, 1);
  margin-top: 10px;
`;

const verifyFile = (f, fLst) => {
  if (fLst.length === 1 && fLst[0].status === "uploading") {
    message.error("请等待上传完成");
    return false;
  }
  const isProperSize = f.size / (2 ** 20 * 10);
  if (!isProperSize) {
    message.error("简历超过10MB");
    return false;
  }
  return true;
};
export default ({
  attachment_name,
  attachment_url,
  attachment_id,
  onChange,
}) => {
  const [fileLst, setFlieLst] = useState(() => {
    if (attachment_name) {
      return [
        {
          uid: "-1",
          status: "done",
          name: attachment_name,
          url: attachment_url,
        },
      ];
    }
    return [];
  });
  const handleChange = useCallback(async ({ file }) => {
    if (file.status === "removed") {
      setFlieLst([]);
      const id = file.response ? file.response.id : attachment_id;
      //axios.delete(`/attachments/${id}.json`);
      onChange("");
    } else if (file.size > 2 ** 20 * 10) {
      setFlieLst([]);
    } else {
      setFlieLst([file]);
      if (file.status === "done") {
        onChange(file.response.id);
      }
    }
  }, []);
  return (
    <React.Fragment>
      <Row type="flex">
        <Upload
          accept=".pdf,.doc,.docx,.ppt,.pptx,.png,.jpg,.jpeg"
          action={getUploadActionUrl()}
          beforeUpload={verifyFile}
          onChange={handleChange}
          fileList={fileLst}
        >
          <Row type="flex">
            <UploadButton>
              {fileLst.length === 1 ? "重新上传" : "上传"}
            </UploadButton>
            <Info>
              提示：不超过10MB，扩展名为pdf、doc、docx、ppt、pptx、png、jpg、jpeg
            </Info>
          </Row>
        </Upload>
      </Row>
    </React.Fragment>
  );
};
