/** @format */
import { FunctionComponent, useEffect, useState } from "react";
import { CheckCard, ProCard } from "@ant-design/pro-components";
import styles from "./index.module.less";
import {
	Avatar,
	Button,
	Card,
	Divider,
	Dropdown,
	Empty,
	Flex,
	FloatButton,
	Input,
	message,
	Modal,
	Popover,
	QRCode,
	Select,
	Skeleton,
	Tooltip,
} from "antd";
import bucket from "@/assets/icons/bucket.svg";
import {
	CheckOutlined,
	CloudUploadOutlined,
	CopyOutlined,
	DeleteOutlined,
	DownloadOutlined,
	EditOutlined,
	EllipsisOutlined,
	EyeOutlined,
	LeftOutlined,
	QrcodeOutlined,
	RedoOutlined,
	ReloadOutlined,
	SnippetsOutlined,
} from "@ant-design/icons";
import standard_dir from "@/assets/icons/standard_directory.svg";
import useStore from "@/utils/store/useStore.tsx";
import { observer } from "mobx-react";
import FileIcon from "@/constant/file-icon.ts";
import file_icon from "@/assets/icons/files/file.svg";
import FileUpload from "@/components/Main/File/components/FileUpload.tsx";
import logo from "@/assets/images/logo.png";
import {
	copyFile,
	deleteFile,
	downloadFiles,
	getAllStorage,
	getBucketFiles,
	getStorageBuckets,
	previewFile,
	renameFile,
} from "@/api/oss";
import StorageIcon from "@/constant/stroage-icon.ts";
import { useNavigate } from "react-router-dom";
import Base64 from "base-64";
const File: FunctionComponent = () => {
	const store = useStore("file");
	const navigate = useNavigate();
	const [files, setFiles] = useState<any>([]);
	const [loading, setLoading] = useState<boolean>(true);
	const [loadingFile, setLoadingFile] = useState<boolean>(true);
	const [open, setOpen] = useState<boolean>(false);
	const [openRename, setOpenRename] = useState<boolean>(false);
	const [userStorage, setUserStorage] = useState<any>([] as any);
	const [buckets, setBuckets] = useState<any[]>([]);
	const [newFileName, setNewFileName] = useState<any>(null);
	const [disable, setDisable] = useState<boolean>(true);
	const [previewUrl, setPreviewUrl] = useState<any>(null);
	const userStore = useStore("user");
	const userId: any = userStore.getUserId();
	function setLoadingTimeOut() {
		setTimeout(() => {
			setLoadingFile(false);
		}, 500);
	}
	async function getUserStorage() {
		getAllStorage(userId).then((res: any) => {
			if (res && res.success) {
				setUserStorage(res.data);
				setLoading(false);
			}
		});
	}
	async function getFiles(bucket: any, dirName: any, type: any) {
		return getBucketFiles(userId, bucket, dirName, type).then((res: any) => {
			if (res && res.success) {
				setFiles(res.data);
				setLoadingTimeOut();
			}
		});
	}
	function getFileExtension(filename: any): string {
		const dotIndex = filename.lastIndexOf(".");
		return dotIndex !== -1 ? filename.slice(dotIndex + 1) : "";
	}
	async function getBuckets(type: any) {
		getStorageBuckets(userId, type).then((res: any) => {
			if (res && res.success) {
				setBuckets(res.data);
			}
		});
	}

	useEffect(() => {
		getUserStorage().then();
	}, []);
	return (
		<>
			<div className={styles.file_main}>
				<div className={styles.file_content_left}>
					<ProCard bordered boxShadow style={{ minHeight: "83vh" }}>
						<Flex vertical={false} align={"center"}>
							<Select
								size="large"
								status="warning"
								style={{
									width: "100%",
									display: "flex",
									flexDirection: "row",
									alignItems: "center",
								}}
								showSearch={true}
								allowClear={true}
								onSelect={(value: any) => {
									store.setCurrentStorage(value);
									getBuckets(value).then();
								}}
								onClear={() => {
									store.setCurrentStorage("");
									setBuckets([]);
								}}
								onChange={(value: any) => {
									store.setCurrentStorage(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={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>
							<Button
								type="default"
								shape={"circle"}
								style={{ marginLeft: 10 }}
								onClick={() => {
									if (store.getCurrentStorage() != null) {
										getBuckets(store.getCurrentStorage()).then();
									}
								}}
								icon={<ReloadOutlined />}></Button>
						</Flex>
						<Divider></Divider>
						<div>
							<CheckCard.Group
								size={"small"}
								onChange={(value: any) => {
									setFiles([]);
									store.clearAllFilePath();
									store.setFilePath(`/${value}`);
									store.setCurrentBucket(value);
									if (value !== undefined) {
										setLoadingFile(true);
										getFiles(value, "", store.getCurrentStorage()).then();
									}
								}}
								style={{ width: "100%" }}>
								{buckets.length === 0 ? (
									<>
										<Empty description={"请选择存储商"} />
									</>
								) : (
									<>
										{buckets &&
											Array.from(buckets).map((item: any, index: number) => {
												return (
													<div key={index}>
														<CheckCard
															style={{ width: "100%" }}
															title={item.name}
															avatar={bucket as any}
															description={item.size}
															value={item.name}
															extra={
																<Dropdown
																	placement="top"
																	menu={{
																		onClick: (value: any) => {
																			if (
																				value.key === "view"
																			) {
																				navigate(
																					"/main/bucket",
																				);
																			}
																		},
																		items: [
																			{
																				label: "查看",
																				key: "view",
																			},
																		],
																	}}>
																	<EllipsisOutlined
																		style={{
																			fontSize: 22,
																			color: "rgba(0,0,0,0.5)",
																		}}
																		onClick={(e) =>
																			e.stopPropagation()
																		}
																	/>
																</Dropdown>
															}
														/>
													</div>
												);
											})}
									</>
								)}
							</CheckCard.Group>
						</div>
					</ProCard>
				</div>
				<div className={styles.file_content_right}>
					<ProCard bordered boxShadow style={{ minHeight: "83vh" }}>
						<div className={styles.file_right_header}>
							<Flex vertical={false} align={"center"} justify={"flex-start"}>
								<Flex vertical={false} align={"center"}>
									<Button
										shape="circle"
										icon={<LeftOutlined />}
										onClick={() => {
											if (
												store.getCurrentBucket() === null ||
												store.getCurrentStorage() === null
											) {
												message.open({
													content: "请选择存储商和桶",
													type: "warning",
												});
												return;
											}
											if (store.getFilePath().length === 1) {
												if (files.length !== 0) {
													return;
												}
												setLoadingFile(true);
												getFiles(
													store.getCurrentBucket(),
													"",
													store.getCurrentStorage(),
												).then();
											} else {
												setLoadingFile(true);
												getFiles(
													store.getCurrentBucket(),
													store.getMiddlePath(),
													store.getCurrentStorage(),
												).then(() => {
													store.clearFilePath();
												});
											}
										}}
									/>
									<Button
										style={{ marginLeft: 20 }}
										shape="circle"
										onClick={() => {
											if (
												store.getCurrentBucket() === null ||
												store.getCurrentStorage() === null
											) {
												message.open({
													content: "请选择存储商和桶",
													type: "warning",
												});
												return;
											}
											setLoadingFile(true);
											getFiles(
												store.getCurrentBucket(),
												store.getFilePathExceptFirst(),
												store.getCurrentStorage(),
											).then();
										}}
										icon={<RedoOutlined />}
									/>
								</Flex>
								<Input
									value={store.getFilePath().join("/")}
									style={{ marginLeft: 15 }}
								/>
							</Flex>
							<Flex
								vertical={false}
								align={"center"}
								justify={"flex-start"}
								style={{ marginTop: 10 }}>
								{/*<Tooltip title="删除" placement={"bottom"}>*/}
								{/*	<Button shape="circle" icon={<DeleteOutlined />} />*/}
								{/*</Tooltip>*/}
								<Tooltip title="下载" placement={"bottom"}>
									<Button
										style={{ marginLeft: 0 }}
										shape="circle"
										onClick={() => {
											if (
												store.getCurrentBucket() === null ||
												store.getCurrentStorage() === null
											) {
												message.open({
													content: "请选择存储商和桶",
													type: "warning",
												});
												return;
											}
											if (store.getCurrentFile() === null) {
												message
													.open({
														content: "请先选择文件！",
														type: "warning",
													})
													.then();
												return;
											}
											downloadFiles(
												userId,
												store.getCurrentBucket(),
												store.getCurrentStorage(),
												store.getCurrentFile(),
											).then((res: any) => {
												const content = res.data;
												const blob = new Blob([content]);
												const url = window.URL.createObjectURL(blob);
												const link = document.createElement("a");
												link.style.display = "none";
												link.href = url;

												// 取后端给前端返的请求头中的文件名称
												const temp = res.headers["content-disposition"]
													.split(";")[1]
													.split("filename=")[1];
												const fileName = decodeURIComponent(temp);
												console.log("fileName:" + fileName);

												link.download = fileName;
												document.body.appendChild(link);
												link.click();
												document.body.removeChild(link); //下载完成移除元素
												window.URL.revokeObjectURL(url); //释放掉blob对象
											});
										}}
										icon={<DownloadOutlined />}
									/>
								</Tooltip>
								<Tooltip title="预览" placement={"bottom"}>
									<Button
										style={{ marginLeft: 20 }}
										shape="circle"
										onClick={() => {
											if (
												store.getCurrentBucket() === null ||
												store.getCurrentStorage() === null
											) {
												message.open({
													content: "请选择存储商和桶",
													type: "warning",
												});
												return;
											}
											if (store.getCurrentFile() !== null) {
												previewFile(
													userId,
													store.getCurrentBucket(),
													store.getCurrentStorage(),
													store.getCurrentFile(),
												).then((res: any) => {
													if (res && res.success && res.data) {
														window.open(
															"http://1.95.0.111:8012/onlinePreview?url=" +
																encodeURIComponent(
																	Base64.encode(res.data) as any,
																),
														);
													}
												});
											} else {
												message
													.open({
														content: "请先选择文件！",
														type: "warning",
													})
													.then();
											}
										}}
										icon={<EyeOutlined />}
									/>
								</Tooltip>
								<Tooltip title="扫码查看" placement={"bottom"}>
									<Popover
										placement="bottom"
										title={"扫码查看"}
										trigger="click"
										content={
											<>
												<QRCode
													errorLevel="H"
													size={300}
													iconSize={300 / 5}
													value={previewUrl}
													icon={logo as any}
												/>
											</>
										}>
										<Button
											style={{ marginLeft: 20 }}
											shape="circle"
											onClick={() => {
												if (
													store.getCurrentBucket() === null ||
													store.getCurrentStorage() === null
												) {
													message.open({
														content: "请选择存储商和桶",
														type: "warning",
													});
													return;
												}
												if (store.getCurrentFile() === null) {
													message
														.open({
															content: "请先选择文件！",
															type: "warning",
														})
														.then();
													return;
												}
												previewFile(
													userId,
													store.getCurrentBucket(),
													store.getCurrentStorage(),
													store.getCurrentFile(),
												).then((res: any) => {
													if (res && res.success && res.data) {
														setPreviewUrl(
															"http://1.95.0.111:8012/onlinePreview?url=" +
																encodeURIComponent(
																	Base64.encode(res.data) as any,
																),
														);
													}
												});
											}}
											icon={<QrcodeOutlined />}
										/>
									</Popover>
								</Tooltip>
								<Tooltip title="粘贴" placement={"bottom"}>
									<Button
										style={{ marginLeft: 20 }}
										disabled={disable}
										shape="circle"
										onClick={() => {
											if (
												store.getCurrentBucket() === null ||
												store.getCurrentStorage() === null
											) {
												message.open({
													content: "请选择存储商和桶",
													type: "warning",
												});
												return;
											}
											if (store.getCopyFile() === null) {
												message.open({
													content: "请先复制文件",
													type: "warning",
												});
												return;
											}
											copyFile(
												userId,
												store.getCurrentBucket(),
												store.getCurrentStorage(),
												store.getCopyFile(),
												store.getFilePathExceptFirst() +
													"/" +
													store.getCopyFileName(),
											).then((res: any) => {
												if (res && res.success) {
													message
														.open({
															content: "粘贴成功 ",
															type: "success",
														})
														.then();
													setDisable(true);
												} else {
													message
														.open({
															content: "粘贴失败 ",
															type: "error",
														})
														.then();
												}
											});
										}}
										icon={<SnippetsOutlined />}
									/>
								</Tooltip>
								{/*<Tooltip title="剪切" placement={"bottom"}>*/}
								{/*	<Button*/}
								{/*		style={{ marginLeft: 20 }}*/}
								{/*		shape="circle"*/}
								{/*		icon={<ScissorOutlined />}*/}
								{/*	/>*/}
								{/*</Tooltip>*/}
								<Tooltip title="复制" placement={"bottom"}>
									<Button
										style={{ marginLeft: 20 }}
										shape="circle"
										onClick={() => {
											if (
												store.getCurrentBucket() === null ||
												store.getCurrentStorage() === null
											) {
												message.open({
													content: "请选择存储商和桶",
													type: "warning",
												});
												return;
											}
											if (store.getCurrentFile() === null) {
												message.open({
													content: "请先选择文件！",
													type: "warning",
												});
												return;
											}
											if (
												store.getCurrentFile() !== "" &&
												store.getCurrentFile() !== null
											) {
												store.setCopyFile(store.getCurrentFile() as string);
												message
													.open({
														content: "复制成功 ",
														type: "success",
													})
													.then();
												setDisable(false);
											} else {
												message
													.open({
														content: "请先选择文件！",
														type: "warning",
													})
													.then();
											}
										}}
										icon={<CopyOutlined />}
									/>
								</Tooltip>
								{/*<Tooltip title="搜索" placement={"bottom"}>*/}
								{/*	<Button*/}
								{/*		style={{ marginLeft: 20 }}*/}
								{/*		shape="circle"*/}
								{/*		icon={<SearchOutlined />}*/}
								{/*	/>*/}
								{/*</Tooltip>*/}
								<Tooltip title="重命名" placement={"bottom"}>
									<Popover
										onOpenChange={(value: any) => {
											setOpenRename(value);
										}}
										open={openRename}
										content={
											<Flex vertical={false} align={"center"}>
												<Input
													onChange={(e: any) => {
														setNewFileName(e.target.value);
													}}></Input>
												<Button
													shape={"circle"}
													onClick={() => {
														if (
															store.getCurrentBucket() === null ||
															store.getCurrentStorage() === null
														) {
															message.open({
																content: "请选择存储商和桶",
																type: "warning",
															});
															return;
														}
														if (newFileName !== null) {
															renameFile(
																userId,
																store.getCurrentBucket(),
																store.getCurrentStorage(),
																store.getCurrentFile(),
																store.getFilePathExceptFirst() +
																	"/" +
																	newFileName,
															).then((res: any) => {
																if (res && res.success) {
																	message
																		.open({
																			content: "重命名成功！",
																			type: "success",
																		})
																		.then();
																	setNewFileName(null);
																	setOpenRename(false);
																} else {
																	message
																		.open({
																			content: "重命名失败！",
																			type: "error",
																		})
																		.then();
																}
															});
														} else {
															message
																.open({
																	content: "请输入新文件名！",
																	type: "warning",
																})
																.then();
														}
													}}
													icon={<CheckOutlined />}></Button>
											</Flex>
										}
										title={"重命名：" + store.getCurrentFile()}
										trigger="click">
										<Button
											style={{ marginLeft: 20 }}
											shape="circle"
											icon={<EditOutlined />}
											onClick={() => {
												if (
													store.getCurrentBucket() === null ||
													store.getCurrentStorage() === null
												) {
													message.open({
														content: "请选择存储商和桶",
														type: "warning",
													});
													return;
												}
												if (
													store.getCurrentFile() === null ||
													store.getCurrentFile() === ""
												) {
													message
														.open({
															content: "请先选择文件！",
															type: "warning",
														})
														.then();
													return;
												} else {
													setOpenRename(true);
												}
											}}
										/>
									</Popover>
								</Tooltip>
							</Flex>
						</div>

						<div className={styles.file_right_content}>
							<Skeleton active loading={loadingFile} paragraph={{ rows: 13 }}>
								<CheckCard.Group
									multiple={false}
									bordered={false}
									className={styles.file_right_content}>
									{files.map((file: any, index: any) => {
										if (file.isDir) {
											return (
												<Dropdown
													key={index}
													menu={{
														items: [
															// {
															// 	label: "删除",
															// 	key: "delete",
															// },
														],
													}}
													trigger={["contextMenu"]}>
													<div
														style={{ marginLeft: 10 }}
														onDoubleClick={() => {
															if (
																store.getCurrentBucket() === null ||
																store.getCurrentStorage() === null
															) {
																message.open({
																	content: "请选择存储商和桶",
																	type: "warning",
																});
																return;
															}
															setLoadingTimeOut();
															getFiles(
																store.getCurrentBucket(),
																`${store.getFilePathExceptFirst()}/${file.name}`,
																store.getCurrentStorage(),
															).then(() => {
																store.setFilePath(file.name);
															});
														}}>
														<CheckCard
															size={"small"}
															value={file.name}
															avatar={
																<div
																	style={{
																		display: "flex",
																		flexDirection: "column",
																		justifyContent: "center",
																		alignItems: "center",
																	}}>
																	<Avatar
																		src={standard_dir as any}
																		shape={"square"}
																		size={"large"}
																	/>
																	<Tooltip
																		title={file.name}
																		placement={"bottom"}
																		color={"lime"}>
																		<span
																			className={
																				styles.file_name
																			}>
																			{file.name}
																		</span>
																	</Tooltip>
																</div>
															}
															className={styles.file_card}
															style={{
																width: 100,
																height: 100,
																display: "flex",
																alignItems: "center",
																justifyContent: "center",
															}}
														/>
													</div>
												</Dropdown>
											);
										} else {
											return (
												<Dropdown
													key={index}
													menu={{
														onClick: ({ key }) => {
															if (key === "delete") {
																deleteFile(
																	userId,
																	store.getCurrentBucket(),
																	store.getCurrentStorage(),
																	store.getFilePathExceptFirst() +
																		"/" +
																		file.name,
																).then((res: any) => {
																	if (res && res.success) {
																		message.open({
																			content: "删除成功！",
																			type: "success",
																		});
																	} else {
																		message.open({
																			content: "删除失败！",
																			type: "error",
																		});
																	}
																});
															} else if (key === "view") {
																previewFile(
																	userId,
																	store.getCurrentBucket(),
																	store.getCurrentStorage(),
																	store.getFilePathExceptFirst() +
																		"/" +
																		file.name,
																).then((res: any) => {
																	if (
																		res &&
																		res.success &&
																		res.data
																	) {
																		window.open(
																			"http://1.95.0.111:8012/onlinePreview?url=" +
																				encodeURIComponent(
																					Base64.encode(
																						res.data,
																					) as any,
																				),
																		);
																	}
																});
															} else if (key === "copy") {
																if (
																	store.getCurrentFile() !== "" &&
																	store.getCurrentFile() !== null
																) {
																	message
																		.open({
																			content: "复制成功 ",
																			type: "success",
																		})
																		.then();
																	store.setCopyFile(
																		store.getCurrentFile() as string,
																	);
																	setDisable(false);
																} else {
																	message
																		.open({
																			content:
																				"请先选择文件！",
																			type: "warning",
																		})
																		.then();
																}
															} else if (key === "paste") {
																if (disable) {
																	message
																		.open({
																			content: "请先复制文件",
																			type: "warning",
																		})
																		.then();
																} else {
																	copyFile(
																		userId,
																		store.getCurrentBucket(),
																		store.getCurrentStorage(),
																		store.getCopyFile(),
																		store.getFilePathExceptFirst() +
																			"/" +
																			store.getCopyFileName(),
																	).then((res: any) => {
																		if (res && res.success) {
																			message
																				.open({
																					content:
																						"粘贴成功 ",
																					type: "success",
																				})
																				.then();
																			setDisable(true);
																		} else {
																			message
																				.open({
																					content:
																						"粘贴失败 ",
																					type: "error",
																				})
																				.then();
																		}
																	});
																}
															}
														},
														items: [
															{
																label: "复制",
																key: "copy",
																icon: <CopyOutlined />,
															},
															{
																label: "粘贴",
																key: "paste",
																icon: <SnippetsOutlined />,
															},
															{
																label: "删除",
																key: "delete",
																icon: <DeleteOutlined />,
															},
															{
																label: "预览",
																key: "view",
																icon: <EyeOutlined />,
															},
														],
													}}
													trigger={["contextMenu"]}>
													<div style={{ marginLeft: 10 }}>
														<CheckCard
															size={"small"}
															value={file.name}
															onChange={(value: any) => {
																if (value) {
																	const pathExceptFirst =
																		store.getFilePathExceptFirst();
																	const fileValue =
																		pathExceptFirst +
																		"/" +
																		file.name;
																	store.setCurrentFile(fileValue);
																	store.setCopyFileName(
																		file.name,
																	);
																}
																if (value === false) {
																	store.setCopyFileName("");
																	store.setCurrentFile("");
																}
															}}
															bodyStyle={{ overflow: "hidden" }}
															avatar={
																<div
																	style={{
																		display: "flex",
																		flexDirection: "column",
																		justifyContent: "center",
																		alignItems: "center",
																		overflow: "hidden",
																	}}>
																	<Avatar
																		src={
																			FileIcon[
																				getFileExtension(
																					file.name,
																				)
																			] || file_icon
																		}
																		shape={"square"}
																		size={"large"}
																	/>
																	<Tooltip
																		title={file.name}
																		color={"lime"}
																		autoAdjustOverflow={true}
																		placement={"bottom"}>
																		<span
																			className={
																				styles.file_name
																			}>
																			{file.name}
																		</span>
																	</Tooltip>
																</div>
															}
															className={styles.file_card}
															style={{
																width: 100,
																height: 100,
																display: "flex",
																alignItems: "center",
																justifyContent: "center",
															}}
														/>
													</div>
												</Dropdown>
											);
										}
									})}
								</CheckCard.Group>
							</Skeleton>
						</div>
					</ProCard>
				</div>
			</div>

			<FloatButton
				type="primary"
				style={{ right: "5%" }}
				icon={<CloudUploadOutlined />}
				onClick={() => setOpen(true)}
			/>
			<Modal
				title={<p>文件上传</p>}
				loading={loading}
				footer={false}
				open={open}
				width={"50%"}
				onCancel={() => setOpen(false)}>
				<FileUpload userStorage={userStorage}></FileUpload>
			</Modal>
		</>
	);
};
export default observer(File);
