import React, { useState, useCallback, useMemo, useEffect } from "react";

import style from "./index.module.css";
import MyDialog from "@/components/mui/MyDialog";
import folderIcon from "@/assets/project/folderIcon.svg";
import bigFolderIcon from "@/assets/project/bigFolderIcon.svg";
import { useMessage } from "@/components/MySnackbar";
import MyTreeView from "@/components/mui/MyTreeView";
import CloudEController from "@/api/fileserver/CloudEController";
import { getDataFileMovePackage } from "@/api/project_api";
import useMyRequest from "@/hooks/useMyRequest";
import classNames from "classnames";
import _ from "lodash";

type IMoveFileProps = {
	moveDialogOpen: any;
	setMoveDialogOpen: any;
	path: string;
	projectId: string;
	fileToken: string;
	refresh: any;
	selectIds: Array<any>;
	currentOperateFile: any;
	showList: Array<any>;
};

const MoveFile = (props: IMoveFileProps) => {
	const {
		moveDialogOpen,
		setMoveDialogOpen,
		path,
		projectId,
		fileToken,
		currentOperateFile,
		selectIds,
		refresh,
		showList,
	} = props;
	const Message = useMessage();
	const [newPath, setNewPath] = useState("/");
	const [rootActive, setRootActive] = useState(true);
	const [treeData, setTreeData] = useState<any>([]);
	const [renderTreeData, setRenderTreeData] = useState<any>([]);
	// 要移动的文件夹  之后用来隐藏文件夹树中同路径的文件夹
	const [moveFolderPathArr, setMoveFolderPathArr] = useState<Array<string>>([]);

	const getTree = useCallback(() => {
		if (fileToken && projectId) {
			return CloudEController.JobOutFileDirtree(
				"/",
				fileToken,
				projectId,
				false
			)?.then((res) => {
				if (Array.isArray(res.data)) {
					let arr = res.data;
					setTreeData(arr);
				} else {
					setTreeData([]);
				}
			});
		}
	}, [fileToken, projectId]);

	useEffect(() => {
		getTree();
	}, [getTree]);

	const getDisabledRepeatFolder = useCallback(
		(folderTree: any, samePathFolederArr: Array<string>) => {
			const arr = _.cloneDeep(folderTree);
			const disabledRepeatFolder = (tree: any, repeatPath: Array<string>) => {
				tree.forEach((item: any, index: number) => {
					if (repeatPath.indexOf(`${item.dir.substr(1)}${item.name}`) !== -1) {
						item.disabled = true;
					} else {
						item.disabled = false;
						if (item.subdirs.length > 0) {
							disabledRepeatFolder(item.subdirs, repeatPath);
						}
					}
				});
			};
			disabledRepeatFolder(arr, samePathFolederArr);
			return arr;
		},
		[]
	);

	useEffect(() => {
		const tree = getDisabledRepeatFolder(treeData, moveFolderPathArr);
		setRenderTreeData(tree);
	}, [moveFolderPathArr, getDisabledRepeatFolder, treeData]);

	useEffect(() => {
		let moveFolderArr: any = [];
		let pathArr = [];
		if (currentOperateFile) {
			if (currentOperateFile.type === "directory") {
				moveFolderArr = [currentOperateFile];
			} else {
				moveFolderArr = [];
			}
		} else {
			moveFolderArr = selectIds
				.map((item) => {
					return showList[item];
				})
				.filter((item) => item.type === "directory");
		}
		pathArr = moveFolderArr.map((item: any) => {
			return path === "/" ? `/${item.name}` : `${path}/${item.name}`;
		});
		setMoveFolderPathArr(pathArr);
	}, [selectIds, showList, currentOperateFile, path]);

	const { run: getDataFileMovePackageRun } = useMyRequest(
		getDataFileMovePackage,
		{
			onSuccess: () => {
				Message.success("移动成功！");
				setMoveDialogOpen(false);
				refresh();
			},
			onError(error: any) {
				if (error?.message) {
					Message.error(error?.message);
				} else if (error?.response?.status === 405) {
					Message.error("因目标路径存在同名文件，数据移动失败。");
				} else {
					Message.error("文件服务发生错误，数据移动失败。");
				}
			},
		}
	);

	// 移动的目标路径
	const dpath = useMemo(() => {
		return newPath === "/" ? "/" : `${newPath}/`;
	}, [newPath]);

	// 移动的原路径
	const spath = useMemo(() => {
		return path === "/" ? "/" : `${path}/`;
	}, [path]);

	// 要移动的文件数组
	const moveList = useMemo(() => {
		if (currentOperateFile) {
			return [currentOperateFile];
		} else {
			return selectIds.map((item) => {
				return showList[item];
			});
		}
	}, [currentOperateFile, selectIds, showList]);

	const packageNames = useMemo(() => {
		return moveList
			.filter((item: any) => {
				return item.type !== "dataSet";
			})
			.map((item: any) => item.name)
			.join(",");
	}, [moveList]);

	const dataSetNames = useMemo(() => {
		return moveList
			.filter((item: any) => {
				return item.type === "dataSet";
			})
			.map((item: any) => item.name)
			.join(",");
	}, [moveList]);

	const moveFileFun = useCallback(() => {
		getDataFileMovePackageRun({
			projectId,
			packageNames,
			dataSetNames,
			spath,
			dpath,
		});
	}, [
		getDataFileMovePackageRun,
		projectId,
		packageNames,
		dataSetNames,
		spath,
		dpath,
	]);

	// 移动
	const handleMoveFileSubmit = () => {
		if (!newPath) {
			Message.error("请选择移动到哪个目录");
		} else if (newPath === path) {
			Message.error("指定的目标路径为数据原路径，无需移动。");
		} else {
			moveFileFun();
		}
	};

	const renderLabel = (node: any) => {
		return (
			<span className={style.treeLabel}>
				<img className={style.labelFolderIcon} src={folderIcon} alt="" />
				<span className={style.treeLabelText}>{node.name}</span>
			</span>
		);
	};

	const onNodeSelect = (a: any, b: any) => {
		setNewPath(b);
		setRootActive(false);
	};

	// 给路径去掉第一个'/'然后结尾加上文件名 方便后面直接使用
	const idFunc = (item: any) => {
		return `${item.dir.substr(1)}${item.name}`;
	};

	const handleRoot = () => {
		setNewPath("/");
		setRootActive(true);
	};

	return (
		<MyDialog
			open={moveDialogOpen}
			title="移动至"
			onClose={() => setMoveDialogOpen(false)}
			onConfirm={handleMoveFileSubmit}
		>
			<div
				className={classNames({
					[style.rootTitle]: true,
					[style.rootTitleActive]: rootActive,
				})}
				onClick={handleRoot}
			>
				<img className={style.bigFolderIcon} src={bigFolderIcon} alt="" />
				ProjectData
			</div>
			<MyTreeView
				treeData={renderTreeData}
				renderLabel={renderLabel}
				onNodeSelect={onNodeSelect}
				idFunc={idFunc}
				treeViewSx={{
					width: 400,
					overflow: "hidden",
				}}
			></MyTreeView>
		</MyDialog>
	);
};

export default MoveFile;
