import ossClie from "@/util/oss";
import Modal from "antd/lib/modal";
import { PlusOutlined } from "@ant-design/icons";
import Upload, { RcFile, UploadFile, UploadProps } from "antd/lib/upload";
import { useEffect, useState } from "react";
import baseHttp from "@/service/base";
import SystemConfig from "@/service/apiConfig/systemConfig";

interface UploadFileProps {
  imgList: Array<UploadFileEx>;
  onChnage: Function;
}

interface UploadFileEx extends UploadFile {
  systemImageId?: number;
  bannerName?: string;
  redictUrl?: string;
  id?: number;
}
const getBase64 = (file: RcFile): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

const AliUpload = (props:UploadFileProps) => {
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState("");
  const [previewTitle, setPreviewTitle] = useState("");
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const handleCancel = () => setPreviewOpen(false);
  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as RcFile);
    }
    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
    setPreviewTitle(
      file.name || file.url!.substring(file.url!.lastIndexOf("/") + 1)
    );
  };

  useEffect(() => {
    setFileList(props.imgList);
  }, [props.imgList]);

  const handleChange: UploadProps["onChange"] = ({ fileList: newFileList }) => {
    let isChange: Boolean = false;
    newFileList.forEach(async (item) => {
      if (item.originFileObj) {
        isChange = true;
        await ossClie(newFileList[newFileList.length - 1].originFileObj).then(
          (resUploadFileEx: UploadFileEx) => {
            resUploadFileEx.uid = resUploadFileEx.name;
            resUploadFileEx.bannerName = resUploadFileEx.name;
            baseHttp.post( SystemConfig.AddImages, { url: resUploadFileEx.url }).then((resp)=>{
              resUploadFileEx.systemImageId = resp.data.id;
              resUploadFileEx.id = resp.data.id;
              resUploadFileEx.redictUrl = "";
              fileList.push(resUploadFileEx);
              props.onChnage(fileList);
              setFileList(fileList);
            })
          }
        );
      }
    });
    if (!isChange) {
      props.onChnage(newFileList);
      setFileList(newFileList);
    }
  };
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  return (
    <div style={{ margin: 10 }}>
      <Upload
        listType="picture-card"
        fileList={fileList}
        onPreview={handlePreview}
        onChange={handleChange}
      >
        {fileList.length >= 4 ? null : uploadButton}
      </Upload>
      <Modal
        open={previewOpen}
        title={previewTitle}
        footer={null}
        onCancel={handleCancel}
      >
        <img alt="example" style={{ width: "100%" }} src={previewImage} />
      </Modal>
    </div>
  );
};

export default AliUpload;
