import React, { useState, useCallback, useEffect, useMemo } from "react";
import style from "./index.module.css";
import MyDialog from "../../mui/Dialog";
import { useStores } from "@/store";
import { observer } from "mobx-react-lite";
import { toJS } from "mobx";
import CloudEController from "@/api/fileserver/CloudEController";
import { getDataFind, getDataFileSearch } from "@/api/project_api";
import Table from "@/components/Material.Ui/Table";
import noFile from "@/assets/project/noFile.svg";
import folderIcon from "@/assets/project/folderIcon.svg";
import SearchIcon from "@mui/icons-material/Search";
import dataSetIcon from "@/assets/project/dataSetIcon.svg";
import fileIcon from "@/assets/project/fileIcon.svg";
import OutlinedInput from "@mui/material/OutlinedInput";
import useMyRequest from "@/hooks/useMyRequest";
import { storageUnitFromB } from "@/utils/util";
import classnames from "classnames";
import { useMessage } from "@/components/MySnackbar";
import moment from "moment";

export type FileSelectType = "file" | "dataset" | "path"; // file 文件选择 dataset数据集选择  path文件夹选择

type FileSelectProps = {
	open: boolean;
	onConfirm: any;
	onClose: any;
	type?: FileSelectType; // file 文件选择 dataset数据集选择  path文件夹选择
};

const FileSelect = observer((props: FileSelectProps) => {
	const { onConfirm, type = "path" } = props;
	const { currentProjectStore } = useStores();
	const Message = useMessage();
	const projectId = toJS(currentProjectStore.currentProjectInfo.id);
	const fileToken = toJS(currentProjectStore.currentProjectInfo.filetoken);
	const [path, setPath] = useState<String>("/");
	const [selectFileName, setSelectFileName] = useState("");
	const [selectItem, setSelectItem] = useState<any>({});
	// 防止用户连续点击文件夹造成路径显示错误
	const [debounce, setDebounce] = useState(false);
	// 文件夹、文件列表
	const [list, setList] = useState<any>([]);
	// 数据集列表  不带文件
	const [dataSetList, setDataSetList] = useState<any>([]);
	const [keyWord, setKeyWord] = useState("");

	// 点击确认时返回的路径
	const resultPath = useMemo(() => {
		if (keyWord) {
			if (selectFileName) {
				console.log("selectFileName", selectFileName);
				console.log("selectItem", selectItem.dir);
				// dataset     path: "/test/"   path: "/"
				// 其他  dir: "//call_logs/stdout/slurm/536f1e38-9357-470b-a0e9-fa5a9fbafe35/call-task_B/execution/"
				//
				if (type === "dataset") {
					return `${selectItem.path}${selectFileName}`;
				} else if (type === "file") {
					return `${selectItem.dir.slice(1)}${selectFileName}`;
				}
			}
		} else {
			if (selectFileName) {
				return `${path === "/" ? "" : path}/${selectFileName}`;
			} else {
				return path;
			}
		}
	}, [path, selectFileName, keyWord, selectItem, type]);
	console.log("resultPath", resultPath);

	const fileSelectOnConfirm = () => {
		if (type === "file") {
			if (!selectFileName) {
				Message.error("请选择一个文件");
				return;
			} else if (selectItem.type === "directory") {
				Message.error("现在选择的是文件夹，请重新选择");
				return;
			}
		} else if (type === "dataset") {
			if (!selectFileName) {
				Message.error("请选择数据集");
				return;
			} else if (selectItem.type === "directory") {
				Message.error("现在选择的是文件夹，请重新选择");
				return;
			}
		}
		onConfirm(resultPath);
	};

	// 搜索值改变
	const handleKeyWordChange = (e: any) => {
		if (e.target.value.length > 30) {
			return;
		}
		setKeyWord(e.target.value);
	};

	// 文件夹下钻
	const handleViewFolders = (item: any) => {
		if (debounce) {
			return;
		} else {
			setDebounce(true);
			if (path === "/") {
				setPath(`/${item.name}`);
			} else {
				setPath(`${path}/${item.name}`);
			}
		}
	};

	// 获取某路径下的数据集fun
	const { run: getDataFindRun } = useMyRequest(getDataFind, {
		onSuccess: (res: any) => {
			const dataSetList = res.data.map((item: any) => {
				return {
					...item,
					type: "dataSet",
				};
			});
			setDataSetList(dataSetList);
			setDebounce(false);
		},
	});

	// 获取某路径下的数据集
	const getDataSetList = useCallback(() => {
		if (keyWord) {
			return;
		} else if (projectId) {
			return getDataFindRun({
				projectId: projectId as string,
				path: path === "/" ? "/" : `${path}/`,
			});
		}
	}, [keyWord, path, projectId, getDataFindRun]);

	// 全局搜索数据集fun
	const { run: getDataFileSearchRun } = useMyRequest(getDataFileSearch, {
		onSuccess: (res: any) => {
			const dataSetList = res.data.map((item: any) => {
				return {
					...item,
					type: "dataSet",
				};
			});
			setDataSetList(dataSetList);
		},
	});

	// 全局搜索数据集
	const getDataSetListSearch = useCallback(() => {
		if (keyWord && projectId) {
			return getDataFileSearchRun({
				projectId: projectId as string,
				name: keyWord,
			});
		} else {
			return getDataSetList();
		}
	}, [keyWord, projectId, getDataFileSearchRun, getDataSetList]);

	// 获取某路径下的文件目录
	const getList = useCallback(() => {
		if (keyWord) {
			return;
		} else if (fileToken && projectId) {
			return CloudEController.JobOutFileList(
				path,
				fileToken,
				projectId,
				false
			)?.then((res) => {
				if (Array.isArray(res.data)) {
					setList(res.data);
				} else {
					setList([]);
				}
				setDebounce(false);
			});
		}
	}, [fileToken, path, projectId, keyWord]);

	// 全局搜索文件列表
	const searchFileList = useCallback(() => {
		if (!keyWord) {
			getList();
		} else {
			if (fileToken && projectId) {
				setPath("/");
				return CloudEController.JobSearchFileList(
					keyWord,
					"/",
					fileToken,
					projectId,
					false
				)?.then((res) => {
					if (Array.isArray(res.data)) {
						setList(res.data);
					} else {
						setList([]);
					}
					setDebounce(false);
				});
			}
		}
	}, [fileToken, projectId, keyWord, getList]);

	// table配置
	const renderName = (item: any) => {
		if (item.type === "directory") {
			return (
				<span
					className={classnames({
						[style.folderIconBox]: true,
						[style.folderPointer]: true,
					})}
					onClick={() => !keyWord && handleViewFolders(item)}
				>
					<img className={style.folderIcon} src={folderIcon} alt="" />
					{item.name}
				</span>
			);
		} else if (item.type === "dataSet") {
			return (
				<span className={style.folderIconBox}>
					<img className={style.folderIcon} src={dataSetIcon} alt="" />
					{item.name}
				</span>
			);
		} else {
			return (
				<span className={style.folderIconBox}>
					<img className={style.folderIcon} src={fileIcon} alt="" />
					{item.name}
				</span>
			);
		}
	};

	// table配置
	const renderSize = (item: any) => {
		if (item.type === "dataSet") {
			return `${item.size}条`;
		}
		return `${item.size ? storageUnitFromB(Number(item.size)) : "-"}`;
	};

	// table配置
	const renderMtime = (item: any) => {
		return String(moment(item.mtime).format("YYYY-MM-DD HH:mm:ss"));
	};

	// table配置
	const versionsHeadCells = [
		{ id: "name", numeric: false, label: "名称", width: "50%" },
		{ id: "size", numeric: false, label: "大小", width: "15%", sort: true },
		{
			id: "mtime",
			numeric: false,
			label: "创建时间",
			width: "20%",
			sort: true,
		},
	];

	// 列表展示的数据
	const showList = useMemo(() => {
		let folderList: any = [];
		let fileList: any = [];
		list.forEach((item: any) => {
			if (item.type === "directory") {
				folderList.push(item);
			} else {
				fileList.push(item);
			}
		});
		if (keyWord) {
			if (type === "file") {
				return fileList;
			} else if (type === "dataset") {
				return dataSetList;
			} else {
				return folderList;
			}
		} else {
			if (type === "file") {
				return [...folderList, ...fileList];
			} else if (type === "dataset") {
				return [...folderList, ...dataSetList];
			} else {
				return [...folderList];
			}
		}
	}, [list, dataSetList, type, keyWord]);

	// 前端展示的文件路径
	const showPath = useMemo(() => {
		if (path === "/") {
			return <span className={style.showPathSpan}>ProjectData</span>;
		} else {
			const pathArr = path.split("/");
			if (pathArr.length <= 4) {
				return pathArr.map((item, index) => {
					return (
						<span
							key={index}
							onClick={() =>
								setPath(
									pathArr.slice(0, index + 1).join("/") === ""
										? "/"
										: pathArr.slice(0, index + 1).join("/")
								)
							}
							className={classnames({
								[style.showPathSpan]: true,
								[style.showPathSpanActive]: index === pathArr.length - 1,
							})}
						>
							{index === 0 ? "ProjectData" : item}{" "}
							{index === pathArr.length - 1 ? null : (
								<i className={style.showPathI}>{">"}</i>
							)}
						</span>
					);
				});
			} else {
				return pathArr.map((item, index) => {
					return (
						<span
							key={index}
							onClick={() => {
								if (index === 1) {
									return;
								}
								setPath(
									pathArr.slice(0, index + 1).join("/") === ""
										? "/"
										: pathArr.slice(0, index + 1).join("/")
								);
							}}
							className={classnames({
								[style.showPathSpan]: true,
								[style.showPathSpanActive]: index === pathArr.length - 1,
							})}
						>
							{index === 0
								? "ProjectData"
								: index > pathArr.length - 4
								? item
								: ""}
							{index === pathArr.length - 1 ||
							(index <= pathArr.length - 4 && index > 0) ? null : (
								<i className={style.showPathI}>{">"}</i>
							)}
							{index === 1 && "..."}
							{index === 1 && <i className={style.showPathI}>{">"}</i>}
						</span>
					);
				});
			}
		}
	}, [path]);

	const getAllData = useCallback(() => {
		setDataSetList([]);
		setList([]);
		setSelectFileName("");
		setSelectItem({});
		if (type === "file" || type === "path") {
			// 不需要获取数据集
			if (keyWord) {
				// 搜索的话是全局搜
				searchFileList();
			} else {
				getList();
			}
		} else {
			// 需要获取数据集
			if (keyWord) {
				// 搜索的话是全局搜
				searchFileList();
				getDataSetListSearch();
			} else {
				getList();
				getDataSetList();
			}
		}
	}, [
		type,
		keyWord,
		searchFileList,
		getList,
		getDataSetListSearch,
		getDataSetList,
	]);

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

	const radioClick = (rowItem: any) => {
		console.log(rowItem);
		setSelectItem(rowItem);
		let name = rowItem.id;
		setSelectFileName(name.slice(5, name.indexOf("&index=")));
	};

	return (
		<MyDialog
			open={props.open}
			onClose={props.onClose}
			onConfirm={fileSelectOnConfirm}
			title="文件选择器"
		>
			<div className={style.FSBox}>
				<div className={style.FSTop}>
					<div className={style.FSPath}>{showPath}</div>
					{type !== "path" && (
						<div className={style.FSKeyWord}>
							<OutlinedInput
								value={keyWord}
								onChange={handleKeyWordChange}
								placeholder="输入关键词搜索"
								size="small"
								sx={{ width: 240, height: 32 }}
								endAdornment={<SearchIcon style={{ color: "#8A9099" }} />}
								// onKeyUp={handleKeyWordChangeKeyUp}
							/>
						</div>
					)}
				</div>
				<Table
					footer={false}
					rowHover={true}
					nopadding={true}
					stickyheader={true}
					headCells={versionsHeadCells}
					rowsPerPage={"99"}
					rows={showList.map((item: any, index: number) => ({
						...item,
						id: `name=${item.name}&index=${index}`,
						name: renderName(item),
						size: renderSize(item),
						mtime: renderMtime(item),
					}))}
					radioClick={radioClick}
					cursor="name"
				></Table>
				{showList.length === 0 && (
					<div className={style.noDataBox}>
						<img className={style.noDataImg} src={noFile} alt="" />
						<span className={style.noDataText}>暂无数据</span>
					</div>
				)}
			</div>
		</MyDialog>
	);
});

export default FileSelect;
