import React, { useState, useCallback, useEffect, useMemo } from "react";
import style from "./index.module.css";
import classnames from "classnames";
import { IconButton } from "@mui/material";
import SearchIcon from "@mui/icons-material/Search";
import RefreshIcon from "@mui/icons-material/Refresh";
import MyTable from "@/components/mui/MyTable";
import dataSetIcon from "@/assets/project/dataSetIcon.svg";
import fileIcon from "@/assets/project/fileIcon.svg";
import folderIcon from "@/assets/project/folderIcon.svg";
import noFile from "@/assets/project/noFile.svg";
import AddFolder from "./AddFolder";
import MoveFile from "./MoveFile";
import DeleteDialog from "./DeleteDialog";
import UpLoaderFile from "./UpLoaderFile";
import useMyRequest from "@/hooks/useMyRequest";
import { observer } from "mobx-react-lite";
import { useStores } from "@/store";
import CloudEController from "@/api/fileserver/CloudEController";
import { toJS } from "mobx";
import moment from "moment";
import NoProject from "@/components/BusinessComponents/NoProject";
import usePass from "@/hooks/usePass";
import { storageUnitFromB } from "@/utils/util";
import { useLocation } from "react-router-dom";
import RadioGroupOfButtonStyle from "@/components/CommonComponents/RadioGroupOfButtonStyle";
import SeeDataset from "./SeeDataset";
import { getDataFind, getDataFileSearch } from "@/api/project_api";
import MyInput from "@/components/mui/MyInput";
import MyButton from "@/components/mui/MyButton";
import SearchInput from "@/components/BusinessComponents/SearchInput";

const ProjectData = observer(() => {
	const isPass = usePass();
	const { currentProjectStore } = useStores();
	const fileToken = toJS(currentProjectStore.currentProjectInfo.filetoken);
	const projectId = toJS(currentProjectStore.currentProjectInfo.id);
	/** 路由信息 */
	const location = useLocation();
	// 当前文件路径
	const [path, setPath] = useState<string>("/");
	// 防止用户连续点击文件夹造成路径显示错误
	const [debounce, setDebounce] = useState(false);
	// 点击操作列中的按钮 会设置当前点击的文件
	const [currentOperateFile, setCurrentOperateFile] = useState<any>(null);
	// 文件file   数据集dataset
	const [activeTab, setActiveTab] = useState("file");
	// 复选框选中的文件名称数组
	const [selectIds, setSelectIds] = useState<Array<string>>([]);
	const [keyWord, setKeyWord] = useState("");
	// 文件夹、文件列表
	const [list, setList] = useState<any>([]);
	// 数据集列表  不带文件
	const [dataSetList, setDataSetList] = useState<any>([]);
	let tableRef: any = React.createRef();
	// 是否显示复选框     用户搜索文件后不显示  其他情况显示
	const [showCheckBox, setShowCheckBox] = useState<boolean>(true);
	// 文件服务器指向
	const fileServerEndPoint = localStorage.getItem("fileServerEndPoint");
	// 文件移动弹窗控制
	const [moveDialogOpen, setMoveDialogOpen] = useState(false);
	// 文件删除弹窗控制
	const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
	// 上传文件弹窗控制
	const [uploaderDialogOpen, setUploaderDialogOpen] = useState(false);
	// 查看数据集（数据集详情）显示控制
	const [showSeeDataset, setShowSeeDataset] = useState(false);
	// 查看的数据集的数据集名称
	const [seeDatasetName, setSeeDatasetName] = useState("");

	useEffect(() => {
		const locationInfo: any = location?.state;
		setPath(locationInfo?.pathName || "/");
	}, [location]);

	// 列表展示的数据
	const showList = useMemo(() => {
		if (activeTab === "file") {
			// 做排序  文件夹在前
			let folderList: any = [];
			let fileList: any = [];
			list.forEach((item: any) => {
				if (item.type === "directory") {
					folderList.push(item);
				} else {
					fileList.push(item);
				}
			});
			return [...folderList, ...fileList];
		} else {
			const folderList = list.filter((item: any) => {
				return item.type === "directory";
			});
			return [...folderList, ...dataSetList];
		}
	}, [list, dataSetList, activeTab]);

	// 是否全是文件夹
	const isAllDirectory = useMemo(() => {
		return showList.every((li: any) => {
			return li.type === "directory";
		});
	}, [showList]);

	// 全（文件、文件夹、数据集）列表
	const allList = useMemo(() => {
		return [...list, ...dataSetList];
	}, [list, dataSetList]);

	// 全局搜索数据集
	const { run: getDataFileSearchRun } = useMyRequest(getDataFileSearch, {
		onSuccess: (res: any) => {
			const dataSetList = res.data.map((item: any) => {
				return {
					...item,
					type: "dataSet",
				};
			});
			setDataSetList(dataSetList);
			setSelectIds([]);
			setDebounce(false);
			tableRef?.current?.initSelectedFunc([]);
			setShowCheckBox(false);
		},
	});

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

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

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

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

	const getList = useCallback(() => {
		if (keyWord) {
			return;
		} else if (fileToken && projectId) {
			if (fileServerEndPoint) {
				return CloudEController.JobOutFileList(
					path,
					fileToken,
					projectId,
					false
				)?.then((res) => {
					if (Array.isArray(res.data)) {
						setList(res.data);
					} else {
						setList([]);
					}
					setSelectIds([]);
					setDebounce(false);
					setShowCheckBox(true);
				});
			}
		}
	}, [fileToken, path, projectId, keyWord, fileServerEndPoint]);

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

	// 全局搜索文件列表
	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([]);
					}
					setSelectIds([]);
					setDebounce(false);
					setShowCheckBox(false);
				});
			}
		}
	}, [fileToken, projectId, keyWord, getList]);

	// 刷新
	const handleRefresh = () => {
		if (isPass("PROJECT_DATA_REFRESH", "USER")) {
			tableRef?.current?.initSelectedFunc([]);
			setSelectIds([]);
			if (keyWord) {
				searchFileList();
				getDataSetListSearch();
			} else {
				getList();
				getDataSetList();
			}
		}
	};

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

	// 按回车搜索
	const handleKeyWordChangeKeyUp = (e: any) => {
		if (e.keyCode === 13) {
			searchFileList();
			getDataSetListSearch();
		}
	};

	// table配置
	const versionsHeadCells = useMemo(() => {
		if (showCheckBox) {
			return [
				{ id: "checkbox" },
				{ id: "name", numeric: false, label: "名称", width: "25%" },
				{ id: "size", numeric: false, label: "大小", width: "25%", sort: true },
				{
					id: "mtime",
					numeric: false,
					label: "创建时间",
					width: "25%",
					sort: true,
				},
				{ id: "caozuo", numeric: false, label: "操作", width: "25%" },
			];
		} else {
			return [
				{ id: "name", numeric: false, label: "名称", width: "25%" },
				{ id: "size", numeric: false, label: "大小", width: "25%", sort: true },
				{
					id: "mtime",
					numeric: false,
					label: "创建时间",
					width: "25%",
					sort: true,
				},
				{ id: "caozuo", numeric: false, label: "操作", width: "25%" },
			];
		}
	}, [showCheckBox]);

	// 点击复选框
	const hanldeCheckbox = (e: any) => {
		const selectarr = e.map((item: any) => {
			let andIndex = item.indexOf("&index=");
			return item.slice(5, andIndex);
		});
		setSelectIds(selectarr);
	};

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

	// 查看数据集
	const handleSeeDataset = (item: any) => {
		console.log(item);
		setSeeDatasetName(item.name);
		setShowSeeDataset(true);
	};

	// table配置
	const renderName = (item: any) => {
		if (item.type === "directory") {
			return (
				<span
					className={classnames({
						[style.folderIconBox]: true,
						[style.pointer]: true,
					})}
					onClick={() => handleViewFolders(item)}
				>
					<img className={style.folderIcon} src={folderIcon} alt="" />
					{item.name}
				</span>
			);
		} else if (item.type === "dataSet") {
			return (
				<span
					className={classnames({
						[style.folderIconBox]: true,
						[style.pointer]: true,
					})}
					onClick={() => handleSeeDataset(item)}
				>
					<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>
			);
		}
	};
	const renderSize = (item: any) => {
		if (item.type === "dataSet") {
			return `${item.size}条`;
		}
		return `${item.size ? storageUnitFromB(Number(item.size)) : "-"}`;
	};
	const renderMtime = (item: any) => {
		return String(moment(item.mtime).format("YYYY-MM-DD HH:mm:ss"));
	};
	const renderButtons = (item: any) => {
		return (
			<span style={{ whiteSpace: "nowrap" }}>
				{!isAllDirectory && (
					<MyButton
						text="下载"
						style={{
							position: "relative",
							left: "-10px",
							minWidth: "10px",
							padding: "0 10px",
							visibility:
								item.type !== "dataSet" && item.type !== "directory"
									? "visible"
									: "hidden",
						}}
						variant="text"
						size="medium"
						disabled={selectIds.length > 0 || !isPass("PROJECT_DATA_DOWNLOAD")}
						onClick={() => hanleDownloadFile(item)}
					/>
				)}
				<MyButton
					text="移动至"
					style={{
						position: "relative",
						left: "-10px",
						minWidth: "10px",
						padding: "0 10px",
					}}
					variant="text"
					size="medium"
					onClick={() => {
						setCurrentOperateFile(item);
						setMoveDialogOpen(true);
					}}
					disabled={
						selectIds.length > 0 || !isPass("PROJECT_DATA_MOVE", "USER")
					}
				/>

				<MyButton
					text="删除"
					style={{
						position: "relative",
						left: "-10px",
						minWidth: "10px",
						padding: "0 10px",
					}}
					variant="text"
					size="medium"
					color="error"
					onClick={() => {
						setCurrentOperateFile(item);
						setDeleteDialogOpen(true);
					}}
					disabled={
						selectIds.length > 0 || !isPass("PROJECT_DATA_DELETE", "USER")
					}
				/>
			</span>
		);
	};

	// 下载文件
	const hanleDownloadFile = (item: any) => {
		const downloadPath =
			path === "/" ? `/${item.name}` : `${path}/${item.name}`;
		CloudEController.JobFileDownload(
			downloadPath,
			fileToken as string,
			projectId as string
		);
	};

	// 前端展示的文件路径
	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]);

	if (currentProjectStore.currentProjectInfo.name) {
		return (
			<div className={style.projectData}>
				<div className={style.projectDataStickyTop}>
					<div className={style.projectDataTitle}>项目数据</div>
					<div className={style.projectDataHeader}>
						<div className={style.projectDataButtonAndSearch}>
							<div className={style.projectDataButtonBox}>
								<MyButton
									text="上传文件"
									variant="contained"
									size="small"
									style={{ marginRight: "12px" }}
									onClick={() => setUploaderDialogOpen(true)}
									disabled={
										selectIds.length !== 0 ||
										!isPass("PROJECT_DATA_UPLOAD", "USER")
									}
								/>

								<AddFolder
									selectIds={selectIds}
									list={allList}
									path={path}
									refresh={handleRefresh}
									fileToken={fileToken as string}
									projectId={projectId as string}
								></AddFolder>
							</div>
							<SearchInput
								value={keyWord}
								onChange={handleKeyWordChange}
								onKeyUp={handleKeyWordChangeKeyUp}
								sx={{ width: 340 }}
							/>
						</div>
						<div className={style.projectDataPathAndTabs}>
							<div className={style.projectDataPath}>{showPath}</div>
							<div className={style.projectDataTabsAndBtton}>
								<RadioGroupOfButtonStyle
									value={activeTab}
									radioOptions={[
										{ value: "file", label: "文件" },
										{ value: "dataset", label: "数据集" },
									]}
									handleRadio={setActiveTab}
								></RadioGroupOfButtonStyle>
								<IconButton
									aria-label="refreshIcon"
									size="small"
									onClick={handleRefresh}
									disabled={!isPass("PROJECT_DATA_REFRESH", "USER")}
									sx={{ marginLeft: "17px" }}
								>
									<RefreshIcon sx={{ fontSize: "18px" }} />
								</IconButton>
							</div>
						</div>
					</div>
					<MyTable
						footer={false}
						rowHover={true}
						onRef={tableRef}
						stickyHeader={true}
						initSelected={selectIds}
						headCells={versionsHeadCells}
						rowsPerPage={"99"}
						checkboxData={(e: any) => {
							hanldeCheckbox(e);
						}}
						rows={showList.map((item: any, index: number) => ({
							...item,
							id: `name=${item.name}&index=${index}`,
							name: renderName(item),
							size: renderSize(item),
							mtime: renderMtime(item),
							caozuo: renderButtons(item),
						}))}
					/>
					{showList.length === 0 && (
						<div className={style.noDataBox}>
							<img className={style.noDataImg} src={noFile} alt="" />
							<span className={style.noDataText}>暂无数据</span>
						</div>
					)}
				</div>
				{selectIds.length > 0 && (
					<div className={style.projectDataStickyBox}>
						<MyButton
							text={`批量删除（${selectIds.length}）`}
							color="error"
							variant="outlined"
							size="small"
							style={{ marginRight: "12px" }}
							onClick={() => {
								setCurrentOperateFile(null);
								setDeleteDialogOpen(true);
							}}
							disabled={!isPass("PROJECT_DATA_DELETE", "USER")}
						/>
						<MyButton
							text={`批量移动（${selectIds.length}）`}
							// color="neutral"
							variant="contained"
							size="small"
							style={{ marginRight: "24px" }}
							onClick={() => {
								setCurrentOperateFile(null);
								setMoveDialogOpen(true);
							}}
							disabled={!isPass("PROJECT_DATA_MOVE", "USER")}
						/>
					</div>
				)}
				{deleteDialogOpen && (
					<DeleteDialog
						deleteDialogOpen={deleteDialogOpen}
						setDeleteDialogOpen={setDeleteDialogOpen}
						path={path}
						projectId={projectId as string}
						currentOperateFile={currentOperateFile}
						selectIds={selectIds}
						refresh={handleRefresh}
						showList={showList}
					></DeleteDialog>
				)}
				{uploaderDialogOpen && (
					<UpLoaderFile
						uploaderDialogOpen={uploaderDialogOpen}
						setUploaderDialogOpen={setUploaderDialogOpen}
						path={path}
						list={allList}
					></UpLoaderFile>
				)}
				{moveDialogOpen && (
					<MoveFile
						moveDialogOpen={moveDialogOpen}
						setMoveDialogOpen={setMoveDialogOpen}
						path={path}
						fileToken={fileToken as string}
						projectId={projectId as string}
						currentOperateFile={currentOperateFile}
						selectIds={selectIds}
						refresh={handleRefresh}
						showList={showList}
					></MoveFile>
				)}
				{showSeeDataset && (
					<SeeDataset
						handleClose={() => setShowSeeDataset(false)}
						name={seeDatasetName}
						path={path}
						fileToken={fileToken as string}
						projectId={projectId as string}
					></SeeDataset>
				)}
			</div>
		);
	} else {
		return <NoProject />;
	}
});

export default ProjectData;
