/** @format */

import { useState } from "react";
import { Avatar, Card, Flex, Input, message, Select, Upload } from "antd";
import { CloudUploadOutlined } from "@ant-design/icons";
import { ProCard } from "@ant-design/pro-components";
import StorageIcon from "@/constant/stroage-icon.ts";
import { getStorageBuckets, uploadFiles } from "@/api/oss";
import useStore from "@/utils/store/useStore.tsx";

const { Dragger } = Upload;

const FileUpload = (props: any) => {
	const [buckets, setBuckets] = useState<any[]>([]);
	const store = useStore("file");
	const [defaultFileList, setDefaultFileList] = useState([]);
	const userStore = useStore("user");
	const userId: any = userStore.getUserId();
	async function getBuckets(type: any) {
		getStorageBuckets(userId, type).then((res: any) => {
			if (res && res.success) {
				setBuckets(res.data);
			}
		});
	}
	const handleOnChange = ({ fileList }: { fileList: any }) => {
		setDefaultFileList(fileList);
	};

	const uploadFile = async (options: any) => {
		const { onSuccess, onError, file }: { onSuccess: any; onError: any; file: any } = options;
		if (store.getUploadFileBucket() === null || store.getUploadFileStorage() === null) {
			message.open({
				content: "请选择存储桶和存储路径",
				type: "error",
			});
			return;
		}
		const fileData = new FormData();
		fileData.append("file", file);
		const formData: any = {
			userId: userId,
			bucketName: store.getUploadFileBucket(),
			path: store.getUploadFilePath(),
		};
		console.log(formData);
		uploadFiles(store.getUploadFileStorage(), fileData, formData).then((res: any) => {
			if (res && res.success) {
				message.open({
					content: "上传成功",
					type: "success",
				});
				onSuccess(res.success);
			} else {
				message.open({
					content: "上传失败",
					type: "error",
				});
				setDefaultFileList([]);
				onError(res.success);
			}
		});
	};
	return (
		<>
			<Flex vertical={false} align={"center"}>
				<ProCard bordered={false} boxShadow={false}>
					<Flex vertical={false}>
						<Select
							size="large"
							status="warning"
							style={{
								width: "30%",
								display: "flex",
								flexDirection: "row",
								alignItems: "center",
							}}
							showSearch={true}
							allowClear={true}
							onSelect={(value: any) => {
								store.setUploadFileStorage(value);
								getBuckets(value).then();
							}}
							onClear={() => {
								store.setUploadFileStorage("");
								setBuckets([]);
							}}
							onChange={(value: any) => {
								store.setUploadFileStorage(value);
							}}
							fieldNames={{
								label: "name",
								value: "ossType",
							}}
							labelRender={(label: any) => {
								return (
									<>
										<Card
											bordered={false}
											style={{
												height: 35,
												display: "flex",
												alignItems: "center",
												flexDirection: "row",
											}}
											size={"small"}>
											<Avatar src={StorageIcon[label.value]} size={"small"} />
											<span
												style={{
													marginLeft: "10px",
													fontWeight: "bolder",
												}}>
												{label.label}
											</span>
										</Card>
									</>
								);
							}}
							options={props.userStorage}
							notFoundContent={"未找到，请先配置存储商"}
							optionRender={(item: any) => {
								return (
									<>
										<Card
											bordered={false}
											style={{
												height: 35,
												display: "flex",
												alignItems: "center",
												flexDirection: "row",
											}}
											size={"small"}>
											<Avatar src={StorageIcon[item.value]} size={"small"} />
											<span
												style={{
													marginLeft: "10px",
													fontWeight: "bolder",
												}}>
												{item.label}
											</span>
										</Card>
									</>
								);
							}}
							placeholder={"请选择存储商"}></Select>

						<Select
							size="large"
							status="warning"
							style={{
								width: "30%",
								display: "flex",
								flexDirection: "row",
								alignItems: "center",
								marginLeft: "10px",
							}}
							onSelect={(value: any) => {
								store.setUploadFileBucket(value);
							}}
							onClear={() => {
								store.setUploadFileBucket("");
								setBuckets([]);
							}}
							onChange={(value: any) => {
								store.setUploadFileBucket(value);
							}}
							showSearch={true}
							allowClear={true}
							notFoundContent={"未找到，请先配置存储商"}
							fieldNames={{
								label: "name",
								value: "name",
							}}
							labelRender={(label: any) => {
								return (
									<>
										<Card
											bordered={false}
											style={{
												height: 35,
												display: "flex",
												alignItems: "center",
												flexDirection: "row",
											}}
											size={"small"}>
											<Avatar
												src={StorageIcon["bucket"]}
												shape={"square"}
												size={"small"}
											/>
											<span
												style={{
													marginLeft: "10px",
													fontWeight: "bolder",
												}}>
												{label.label}
											</span>
										</Card>
									</>
								);
							}}
							options={buckets}
							optionRender={(item: any) => {
								return (
									<>
										<Card
											bordered={false}
											style={{
												height: 35,
												display: "flex",
												alignItems: "center",
												flexDirection: "row",
											}}
											size={"small"}>
											<Avatar
												src={StorageIcon["bucket"]}
												size={"small"}
												shape={"square"}
											/>{" "}
											<span
												style={{
													marginLeft: "10px",
													fontWeight: "bolder",
												}}>
												{item.label}
											</span>
										</Card>
									</>
								);
							}}
							placeholder={"请选择存储桶"}></Select>
						<Input
							placeholder={"请输入路径/默认当前打开的路径"}
							onChange={(e: any) => {
								store.setUploadFilePath(e.target.value);
							}}
							style={{ marginLeft: 10, width: "40%" }}></Input>
					</Flex>
				</ProCard>
			</Flex>
			<ProCard>
				<Dragger
					name={"file"}
					multiple={false}
					directory={false}
					maxCount={1}
					defaultFileList={defaultFileList}
					headers={{
						ContentType: "multipart/form-data",
					}}
					onChange={handleOnChange}
					customRequest={uploadFile}
					onDrop={() => uploadFile}>
					<p className="ant-upload-drag-icon">
						<CloudUploadOutlined />
					</p>

					<p className="ant-upload-text">单击或拖动文件到此区域进行上传</p>
					<p className="ant-upload-hint">只支持单次上传。</p>
				</Dragger>
			</ProCard>
		</>
	);
};
export default FileUpload;
