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

import style from "./index.module.css";
import classnames from "classnames";
import { Button, InputBase, IconButton } from "@mui/material";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import SearchIcon from "@mui/icons-material/Search";
import RefreshIcon from "@mui/icons-material/Refresh";
import Table from "@/components/Material.Ui/Table";
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 { getDataFind, getDataFileSearch } from "@/api/project_api";

const theme = createTheme({
	palette: {
		neutral: {
			main: "#1370FF",
			contrastText: "#fff",
		},
	},
});
declare module "@mui/material/styles" {
	interface Palette {
		neutral: Palette["primary"];
	}

	interface PaletteOptions {
		neutral?: PaletteOptions["primary"];
	}
}

declare module "@mui/material/Button" {
	interface ButtonPropsColorOverrides {
		neutral: true;
	}
}

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 [tableLoadding, setTableLoadding] = useState(false);
	// 防止用户连续点击文件夹造成路径显示错误
	const [debounce, setDebounce] = useState(false);
	// 点击操作列中的按钮 会设置当前点击的文件
	const [currentOperateFile, setCurrentOperateFile] = useState<any>(null);
	// 文件file   数据集dataset
	// const [activeTab, setActiveTab] = useState(1);
	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");

	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) {
				setTableLoadding(true);
				return CloudEController.JobOutFileList(
					path,
					fileToken,
					projectId,
					false
				)?.then((res) => {
					setTableLoadding(false);
					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) {
				setTableLoadding(true);
				setPath("/");
				return CloudEController.JobSearchFileList(
					keyWord,
					"/",
					fileToken,
					projectId,
					false
				)?.then((res) => {
					setTableLoadding(false);
					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();
		}
	};

	// todo name sort
	// 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}`);
			}
		}
	};

	// table配置
	const renderName = (item: any) => {
		if (item.type === "directory") {
			return (
				<span
					className={classnames({
						[style.folderIconBox]: true,
						[style.folderPointer]: true,
					})}
					onClick={() => 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 renderButtons = (item: any) => {
		return (
			<span style={{ whiteSpace: "nowrap" }}>
				{!isAllDirectory && (
					<Button
						sx={{
							position: "relative",
							left: "-4px",
							minWidth: "10px",
							marginRight: "10px",
							visibility:
								item.type !== "dataSet" && item.type !== "directory"
									? "visible"
									: "hidden",
						}}
						variant="text"
						size="small"
						disabled={selectIds.length > 0 || !isPass("PROJECT_DATA_DOWNLOAD")}
						onClick={() => hanleDownloadFile(item)}
					>
						下载
					</Button>
				)}
				<Button
					sx={{
						position: "relative",
						left: "-4px",
						minWidth: "10px",
						marginRight: "10px",
					}}
					variant="text"
					size="small"
					onClick={() => hanleShowMoveFileDialog(item)}
					disabled={
						selectIds.length > 0 || !isPass("PROJECT_DATA_MOVE", "USER")
					}
				>
					移动至
				</Button>
				<Button
					sx={{
						position: "relative",
						left: "-4px",
						minWidth: "10px",
						marginRight: "10px",
					}}
					variant="text"
					size="small"
					color="error"
					onClick={() => hanleShowDeleteDialogRef(item)}
					disabled={
						selectIds.length > 0 || !isPass("PROJECT_DATA_DELETE", "USER")
					}
				>
					删除
				</Button>
			</span>
		);
	};

	// 文件上传
	let UpLoaderFileRef: any = React.createRef();
	const hanleShowUpLoaderFileDialog = () => {
		UpLoaderFileRef.current.showDialog();
	};

	// 新增文件
	let addFolderRef: any = React.createRef();

	const hanleShowAddFolderDialog = () => {
		addFolderRef.current.showDialog();
	};

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

	// 文件移动
	let moveFileRef: any = React.createRef();

	const hanleShowMoveFileDialog = (item: any) => {
		setCurrentOperateFile(item);
		moveFileRef.current.showDialog();
	};

	// 删除弹窗
	let deleteDialogRef: any = React.createRef();
	const hanleShowDeleteDialogRef = (item: any) => {
		setCurrentOperateFile(item);
		deleteDialogRef.current.showDialog();
	};

	// 批量移动
	const handleBatchMove = () => {
		setCurrentOperateFile(null);
		moveFileRef.current.showDialog();
	};

	// 批量删除
	const handleBatchDelete = () => {
		setCurrentOperateFile(null);
		deleteDialogRef.current.showDialog();
	};

	// 前端展示的文件路径
	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 - 4 */}
							{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 (
			<ThemeProvider theme={theme}>
				<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}>
									<Button
										color="neutral"
										variant="contained"
										size="small"
										style={{ marginRight: "12px" }}
										onClick={hanleShowUpLoaderFileDialog}
										disabled={
											selectIds.length !== 0 ||
											!isPass("PROJECT_DATA_UPLOAD", "USER")
										}
									>
										上传文件
									</Button>
									<Button
										color="neutral"
										variant="outlined"
										size="small"
										onClick={hanleShowAddFolderDialog}
										disabled={
											selectIds.length !== 0 ||
											!isPass("PROJECT_DATA_ADDDIR", "USER")
										}
									>
										新建文件夹
									</Button>
								</div>
								<div className={style.projectDataSearch}>
									<InputBase
										className={style.searchInput}
										placeholder="输入关键词搜索"
										inputProps={{ "aria-label": "输入关键词搜索" }}
										value={keyWord}
										onChange={handleKeyWordChange}
										style={{ width: "280px", fontSize: "14px" }}
										onKeyUp={handleKeyWordChangeKeyUp}
									/>
									<IconButton
										type="submit"
										className={style.searchButton}
										aria-label="search"
										size="small"
										style={{ padding: "4px" }}
										onClick={handleRefresh}
									>
										<SearchIcon
											className={style.searchIcon}
											style={{ color: "#999" }}
										/>
									</IconButton>
								</div>
							</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")}
									>
										<RefreshIcon />
									</IconButton>
								</div>
							</div>
						</div>
						<Table
							footer={false}
							rowHover={true}
							onRef={tableRef}
							nopadding={true}
							stickyheader={true}
							load={tableLoadding}
							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),
							}))}
						></Table>
						{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}>
							<Button
								color="error"
								variant="outlined"
								size="small"
								style={{ marginRight: "12px" }}
								onClick={handleBatchDelete}
								disabled={!isPass("PROJECT_DATA_DELETE", "USER")}
							>
								批量删除（{selectIds.length}）
							</Button>
							<Button
								color="neutral"
								variant="contained"
								size="small"
								style={{ marginRight: "24px" }}
								onClick={handleBatchMove}
								disabled={!isPass("PROJECT_DATA_MOVE", "USER")}
							>
								批量移动（{selectIds.length}）
							</Button>
						</div>
					)}
					<DeleteDialog
						onRef={deleteDialogRef}
						path={path}
						projectId={projectId}
						currentOperateFile={currentOperateFile}
						selectIds={selectIds}
						refresh={handleRefresh}
						showList={showList}
					></DeleteDialog>
					<UpLoaderFile
						onRef={UpLoaderFileRef}
						path={path}
						list={allList}
					></UpLoaderFile>
					<AddFolder
						onRef={addFolderRef}
						list={allList}
						path={path}
						refresh={handleRefresh}
						fileToken={fileToken}
						projectId={projectId}
					></AddFolder>
					<MoveFile
						onRef={moveFileRef}
						path={path}
						fileToken={fileToken}
						projectId={projectId}
						currentOperateFile={currentOperateFile}
						selectIds={selectIds}
						refresh={handleRefresh}
						showList={showList}
					></MoveFile>
				</div>
			</ThemeProvider>
		);
	} else {
		return <NoProject />;
	}
});

export default ProjectData;
