import React, { useState, useCallback, useEffect, useMemo } from "react";
import style from "./index.module.css";
import classnames from "classnames";
import { IconButton } from "@mui/material";
import MyTable from "@/components/mui/MyTableNew";
import dataSetIcon from "@/assets/project/dataSetIcon.svg";
import fileIcon from "@/assets/project/fileIcon.svg";
import folderIcon from "@/assets/project/folderIcon.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 MyButton from "@/components/mui/MyButton";
import SearchInput from "@/components/BusinessComponents/SearchInput";
import ChevronRightIcon from "@mui/icons-material/ChevronRight";

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;
		setActiveTab(locationInfo?.dataType || "file");
		setPath(locationInfo?.pathName || "/");
	}, [location]);

	// 切换文件数据集时情况勾选项
	useEffect(() => {
		setSelectIds([]);
	}, [activeTab]);

	// 列表展示的数据
	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);
				}
			});
			let arr = [...folderList, ...fileList];
			return arr.map((item, index) => {
				return {
					...item,
					id: index,
				};
			});
		} else {
			const folderList = list.filter((item: any) => {
				return item.type === "directory";
			});
			let arr = [...folderList, ...dataSetList];
			return arr.map((item, index) => {
				return {
					...item,
					id: index,
				};
			});
		}
	}, [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();
		}
	};

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

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

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

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

	// table配置
	const versionsHeadCells = [
		{
			id: "name",
			label: "名称",
			width: 200,
			flexGrow: 2,
			cellRenderer: renderName,
		},
		{ id: "size", label: "大小", width: 200, cellRenderer: renderSize },
		{
			id: "mtime",
			label: "创建时间",
			width: 200,
			cellRenderer: renderMtime,
		},
		{ id: "caozuo", label: "操作", width: 200, cellRenderer: renderButtons },
	];

	// 下载文件
	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 : (
								<ChevronRightIcon
									sx={{
										fontSize: "16px",
										color: "rgba(194, 198, 204, 1)",
										margin: "0px 4px",
									}}
								/>
							)}
						</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 : (
								<ChevronRightIcon
									sx={{
										fontSize: "16px",
										color: "rgba(194, 198, 204, 1)",
										margin: "0px 4px",
									}}
								/>
							)}
							{index === 1 && "..."}
							{index === 1 && (
								<ChevronRightIcon
									sx={{
										fontSize: "16px",
										color: "rgba(194, 198, 204, 1)",
										margin: "0px 4px",
									}}
								/>
							)}
						</span>
					);
				});
			}
		}
	}, [path]);

	if (currentProjectStore.currentProjectInfo.name) {
		return (
			<div className={style.projectData}>
				{/* <div className={style.projectDataStickyTop}> */}
				<div
					className={classnames({
						[style.projectDataStickyTop]: true,
						[style.projectDataStickyTopPadding]: selectIds.length === 0,
					})}
				>
					<div className={style.projectDataTitle}>项目数据</div>
					<div className={style.projectDataHeader}>
						<div className={style.projectDataButtonAndSearch}>
							<div className={style.projectDataButtonBox}>
								<MyButton
									text="上传文件"
									variant="contained"
									size="medium"
									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}
								/>
								<IconButton
									aria-label="refreshIcon"
									size="small"
									onClick={handleRefresh}
									disabled={!isPass("PROJECT_DATA_REFRESH", "USER")}
									sx={{
										marginLeft: "12px",
										width: "32px",
										height: "32px",
										":hover": {
											backgroundColor: "rgba(240, 242, 245, 1)",
											borderRadius: "4px",
										},
									}}
								>
									<span
										style={{ fontSize: "16px", color: "rgba(138, 144, 153, 1)" }}
										className="iconfont icon-shuaxin"
									></span>
								</IconButton>
							</div>
						</div>
					</div>
					<div className={style.tableBox}>
						<MyTable
							isVirtuallyTable={true}
							fixedHead={true}
							hasCheckbox={showCheckBox}
							headCells={versionsHeadCells}
							selectItems={selectIds}
							setSelectItems={setSelectIds}
							rows={showList}
						/>
					</div>
				</div>
				{selectIds.length > 0 && (
					<div className={style.projectDataStickyBox}>
						<MyButton
							text={`批量删除 (${selectIds.length})`}
							color="error"
							variant="outlined"
							style={{ marginRight: "12px" }}
							onClick={() => {
								setCurrentOperateFile(null);
								setDeleteDialogOpen(true);
							}}
							disabled={!isPass("PROJECT_DATA_DELETE", "USER")}
						/>
						<MyButton
							text={`批量移动 (${selectIds.length})`}
							variant="contained"
							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;
