import React, { useState, useEffect } from "react";
import { Upload as Uploads, Modal } from "antd";
import type { UploadFile, UploadProps } from "antd/es/upload/interface";
import { PlusOutlined } from "@ant-design/icons";
import "../styles/home-manage.scss";
type UploadType = {
value?: any;
onChange?: (value: any) => void;
disabled: boolean;
isMulti: boolean;
};
function Upload(props: UploadType) {
const { value, onChange, disabled, isMulti } = props;
const [previewVisible, setPreviewVisible] = useState(false);
const [previewImage, setPreviewImage] = useState(value);
const [previewTitle, setPreviewTitle] = useState("图片预览");
const [fileList, setFileList] = useState<UploadFile[]>([]);
const uploadButton = (
<div>
<PlusOutlined />
<div style={{ marginTop: 8 }}>Upload</div>
</div>
);
useEffect(() => {
if (Array.isArray(value)) {
let fileListCopy: any[] = [];
value.forEach((v) => {
if (v) {
setPreviewImage(v);
const item = {
uid: Math.round(Math.random() * 100000),
name: "图片",
url: v,
};
fileListCopy.push(item);
} else {
setPreviewImage(v);
setFileList(fileListCopy);
}
});
setFileList(fileListCopy);
}
}, [value]);
const handleChange: UploadProps["onChange"] = ({
file,
fileList: newFileList,
}) => {
const { status, response } = file;
if (status === "done") {
let { url = "" } = response;
if (!url.includes("https")) {
url = `https:${url}`;
}
onChange?.([...value, url]);
}
setFileList(newFileList);
};
const handlePreview = async (file: UploadFile) => {
let { url = "", response, name } = file;
if (response) {
url = response.url || "";
if (!url.includes("https")) {
url = `https:${url}`;
}
}
setPreviewImage(url);
setPreviewTitle(name || "");
setPreviewVisible(true);
};
const handleCancel = () => setPreviewVisible(false);
const handleRemove = (file: UploadFile<any>) => {
let url = file.url || file?.response.url;
if (!url.includes("https")) {
url = `https:${url}`;
}
const fileListCopy = fileList.filter((v) => {
let urlV = v.url || v?.response.url;
if (!urlV.includes("https")) {
urlV = `https:${urlV}`;
}
return urlV == url;
});
const valueCopy = value.filter((v: any) => v != url);
setFileList(fileListCopy);
onChange?.(valueCopy);
};
const handleDownload = (file: any) => {
console.log(file);
};
return (
<>
<Uploads
name="file"
accept="image/*"
listType="picture-card"
className="avatar-uploader"
action="/config/upload/img.node"
fileList={fileList}
onChange={handleChange}
onPreview={handlePreview}
onRemove={handleRemove}
onDownload={handleDownload}
data={{ innerPublic: "public" }}
disabled={disabled}
maxCount={isMulti ? 5 : 1}
>
{(isMulti && fileList.length >= 5) || (!isMulti && fileList.length >= 1)
? null
: uploadButton}
</Uploads>
<Modal
visible={previewVisible}
title={previewTitle}
footer={null}
onCancel={handleCancel}
>
<img alt="example" style={{ width: "100%" }} src={previewImage} />
</Modal>
</>
);
}
export default Upload;