import FullScreenDrawer from "@/components/CommonComponents/FullScreenDrawer";
import { useState, useCallback, useEffect } from "react";
import RadioGroupOfButtonStyle from "@/components/CommonComponents/RadioGroupOfButtonStyle";
import MyMultipleMenu, { IOption } from "@/components/mui/MyMultipleMenu";
import MyButton from "@/components/mui/MyButton";
import MyPagination from "@/components/mui/MyPagination";
import CloudEController from "@/api/fileserver/CloudEController";
import { getToken } from "@/utils/util";
import { observer } from "mobx-react-lite";
import { useStores } from "@/store";
import { toJS } from "mobx";
import classNames from "classnames";
import Save from "./components/Save";
import Download from "./components/Download";
import DatasetCardTable from "./components/DatasetCardTable";
import DatasetTable from "./components/DatasetTable";
import table from "@/assets/project/table.svg";
import tableActive from "@/assets/project/tableActive.svg";
import card from "@/assets/project/card.svg";
import cardActive from "@/assets/project/cardActive.svg";
import filter from "@/assets/project/filter.svg";
import jobDel from "@/assets/project/jobDel.svg";
import style from "./index.module.css";
import _ from "lodash";
import AddIcon from "@mui/icons-material/Add";
import MySelect from "@/components/mui/MySelect";
import { sortState } from "@/components/mui/MyTableNew";
import MyInput from "@/components/mui/MyInput";

type ISeeDatasetProps = {
	handleClose: any;
	path: string;
	fileToken: string;
	projectId: string;
	name: string;
};

type IQuery = {
	index: any;
	compare: ">" | "<" | ">=" | "<=" | "=" | "≈";
	query: any;
};

const SeeDataset = observer((props: ISeeDatasetProps) => {
	const { path, name, fileToken, projectId } = props;
	const { currentProjectStore } = useStores();
	const productId = toJS(currentProjectStore.currentProductInfo.id); // 产品id  如：cadd
	const token = getToken();
	const [tableType, setTableType] = useState<"table" | "card">("table");
	const [graphicDimension, setGraphicDimension] = useState("2D"); // 分子结构图是2D还是3D
	const [showData, setShowData] = useState<Array<string>>([]); //显示的数据类型
	const [showSearchBox, setShowSearchBox] = useState<boolean>(true); // 高级筛选显示隐藏控制
	const [hasSmiles, setHasSmiles] = useState(false);
	const [dataTypes, setdataTypes] = useState<Array<IOption>>([]); // 可选的数据类型
	const [sort, setSort] = useState("null"); // 排序方式
	const [sortState, setSortState] = useState<sortState>({
		field: null,
		order: null,
	});
	console.log(sortState);
	const [querylist, setQuerylist] = useState<Array<IQuery>>([]);
	const [queryInit, setQueryInit] = useState<IQuery>({
		index: "",
		compare: ">",
		query: "",
	});
	// const [searchDataType, setSearchDataType] = useState<any>(null); // 搜索的数据属性
	const [page, setPage] = useState(0); // 当前页码   // 请求接口的页码是从0开始的
	const size = 8; // 每页数量
	const [count, setCount] = useState(0); // 总页数
	const [list, setList] = useState<Array<any>>([]); // 分子列表
	const [selectItems, setSelectItems] = useState<Array<any>>([]);
	const [saveOpen, setSaveOpen] = useState(false); // 另存为弹窗显示控制
	const [downloadOpen, setDownloadOpen] = useState(false); // 下载弹窗显示控制
	const [firstGetList, setFirstGetList] = useState(true); // 第一次请求列表

	// const handleSortChange = (e: any) => {
	// 	setSort(e);
	// };

	const pageChange = (value: number) => {
		setPage(value - 1);
	};

	// 获取分子列表
	const getList = useCallback(
		(paramsPage = 0) => {
			setPage(paramsPage);
			CloudEController.GetDatasetItemsList({
				type: productId as string,
				projectId: projectId as string,
				token: token,
				filetoken: fileToken as string,
				path: path,
				name: name,
				page: paramsPage,
				size,
				index: "",
				sort: sort === "null" ? "" : sort,
			})
				?.then((res) => {
					setList(res.data.list);
					setCount(res.data.totalPage - 1);
					if (res.data.list && res.data.list.length > 0) {
						if (res.data.list[0]) {
							let arr: any = [];
							let _hasSmiles = false;
							Object.keys(res.data.list[0]).forEach((item) => {
								if (
									![
										"meta",
										"id",
										// "canonical_smiles",
										// "mol",
										// "mol2",
										// "pdb",
										// "sdf",
										// "sdf2d",
										// "sdf3d",
										// "smiles",
									].includes(item)
								) {
									arr.push({ label: item, value: item });
								}
								if (item === "smiles") {
									_hasSmiles = true;
								}
							});
							if (firstGetList) {
								setdataTypes(arr);
								setShowData(arr.slice(0, 5).map((item: any) => item.value));
								setHasSmiles(_hasSmiles);
								setQuerylist([
									{
										index: arr[0]?.value || "",
										compare: ">",
										query: "",
									},
								]);
								setQueryInit({
									index: arr[0]?.value || "",
									compare: ">",
									query: "",
								});
							}
							setFirstGetList(false);
						}
					}
				})
				?.catch((error) => {
					console.log(error);
					setList([]);
				});
		},
		[productId, projectId, token, fileToken, path, name, sort, firstGetList]
	);

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

	const handleIndexChange = (e: any, subscriptIndex: number) => {
		let arr = _.cloneDeep(querylist);
		console.log(e);
		arr[subscriptIndex].index = e;
		setQuerylist(arr);
	};

	const handleCompareChange = (e: any, subscriptIndex: number) => {
		let arr = _.cloneDeep(querylist);
		console.log(e);
		arr[subscriptIndex].compare = e;
		setQuerylist(arr);
	};

	const handleQueryChange = (e: any, subscriptIndex: number) => {
		let arr = _.cloneDeep(querylist);
		console.log(e);
		arr[subscriptIndex].query = e.target.value;
		setQuerylist(arr);
	};

	const handleDeleteQuery = (index: number) => {
		let arr = _.cloneDeep(querylist);
		arr.splice(index, 1);
		setQuerylist(arr);
	};

	const handleInitQuerylist = () => {
		setQuerylist([{ ...queryInit }]);
	};

	// 点击其他地方隐藏高级筛选
	useEffect(() => {
		document.addEventListener("click", (e) => {
			setShowSearchBox(false);
		});
	}, []);

	// 高级筛选box取消冒泡
	const handlestopBubble = (e: any) => {
		e.nativeEvent.stopImmediatePropagation();
	};

	const handleShowSearchBox = (e: any) => {
		e.nativeEvent.stopImmediatePropagation();
		setShowSearchBox(!showSearchBox);
	};

	return (
		<FullScreenDrawer handleClose={props.handleClose} zIndex={1100}>
			<div
				className={classNames({
					[style.datasetBox]: true,
					[style.datasetBoxShowFoot]: true,
				})}
			>
				<div className={style.top}>
					<div className={style.title}>{name}</div>
					<div className={style.screens}>
						<div className={style.screensLeft}>
							{hasSmiles && (
								<>
									<RadioGroupOfButtonStyle
										handleRadio={setTableType}
										value={tableType}
										radioBoxStyle={{ minWidth: "40px" }}
										radioStyle={{ padding: "0" }}
										radioOptions={[
											{
												value: "table",
												label: (
													<img
														src={tableType === "table" ? tableActive : table}
														alt=""
													></img>
												),
											},
											{
												value: "card",
												label: (
													<img
														src={tableType === "card" ? cardActive : card}
														alt=""
													></img>
												),
											},
										]}
									/>
									<div className={style.separator}></div>
								</>
							)}
							{tableType === "card" && hasSmiles && (
								<>
									<div
										className={classNames({
											[style.graphicDimension]: true,
											[style.graphicDimensionActive]: graphicDimension === "2D",
										})}
										onClick={() => setGraphicDimension("2D")}
									>
										2D
									</div>
									<div
										className={classNames({
											[style.graphicDimension]: true,
											[style.graphicDimensionActive]: graphicDimension === "3D",
											[style.marginRight20]: true,
										})}
										onClick={() => setGraphicDimension("3D")}
									>
										3D
									</div>
								</>
							)}
							<MyMultipleMenu
								value={showData}
								options={dataTypes}
								setValue={setShowData}
								showSelectAll={true}
								iconColor="rgba(138, 144, 153, 1)"
							>
								<span className={style.selectShowData}>
									选择显示数据({showData.length})
								</span>
							</MyMultipleMenu>
						</div>
						<div className={style.screensRight}>
							<MyButton
								text="高级筛选"
								onClick={(e: any) => {
									handleShowSearchBox(e);
								}}
								variant="outlined"
								color="secondary"
								img={
									<img
										src={filter}
										alt=""
										style={{ marginRight: "10px" }}
									></img>
								}
							></MyButton>
							{showSearchBox && (
								<div
									className={style.searchBox}
									onClick={(e) => handlestopBubble(e)}
								>
									<div className={style.searchTop}>
										<span
											className={classNames({
												[style.searchTopText]: true,
												[style.width250]: true,
											})}
										>
											选择属性
										</span>
										<span
											className={classNames({
												[style.searchTopText]: true,
												[style.width120]: true,
											})}
										>
											比较符
										</span>
										<span
											className={classNames({
												[style.searchTopText]: true,
												[style.width180]: true,
											})}
										>
											比较值
										</span>
									</div>
									<div className={style.searchList}>
										{querylist.map((item, index) => {
											return (
												<div className={style.searchLi}>
													<MySelect
														options={dataTypes}
														placeholder="请选择属性"
														value={item.index}
														sx={{ marginRight: "16px", width: "250px" }}
														onChange={(e) => handleIndexChange(e, index)}
													></MySelect>
													<MySelect
														value={item.compare}
														onChange={(e) => handleCompareChange(e, index)}
														options={[
															{
																label: ">",
																value: ">",
															},
															{
																label: "<",
																value: "<",
															},
															{
																label: ">=",
																value: ">=",
															},
															{
																label: "<=",
																value: "<=",
															},
															{
																label: "=",
																value: "=",
															},
															{
																label: "≈",
																value: "≈",
															},
														]}
														sx={{ marginRight: "16px", width: "120px" }}
													></MySelect>
													<MyInput
														value={item.query}
														onChange={(e) => handleQueryChange(e, index)}
														sx={{ marginRight: "16px", width: "180px" }}
													></MyInput>
													<img
														onClick={() => handleDeleteQuery(index)}
														src={jobDel}
														alt=""
													/>
												</div>
											);
										})}
									</div>
									<div className={style.searchFooter}>
										<div
											className={style.searchFooterLeft}
											onClick={() =>
												setQuerylist([...querylist, { ...queryInit }])
											}
										>
											<AddIcon sx={{ fontSize: "20px", marginRight: "6px" }} />
											<span>添加条件</span>
										</div>
										<div className={style.searchFooterRight}>
											<MyButton
												variant="outlined"
												text="重置"
												style={{ marginRight: "12px" }}
												onClick={() => handleInitQuerylist()}
												color="secondary"
											></MyButton>
											<MyButton
												text="筛选"
												onClick={() => setSaveOpen(true)}
											></MyButton>
										</div>
									</div>
								</div>
							)}
						</div>
					</div>
				</div>
				<div className={style.table}>
					{tableType === "table" && (
						<DatasetTable
							list={list}
							showData={showData}
							selectItems={selectItems}
							setSelectItems={setSelectItems}
							sortState={sortState}
							setSortState={setSortState}
						></DatasetTable>
					)}
					{tableType === "card" && (
						<DatasetCardTable
							list={list}
							graphicDimension={graphicDimension}
							showData={showData}
							selectItems={selectItems}
							setSelectItems={setSelectItems}
						></DatasetCardTable>
					)}
				</div>
			</div>
			<div
				className={classNames({
					[style.foot]: true,
					[style.borderTop]: tableType === "table",
				})}
			>
				{selectItems.length === 0 && (
					<MyPagination page={page} pageChange={pageChange} count={count} />
				)}
				{selectItems.length !== 0 && (
					<>
						<MyButton
							text={`另存为(${selectItems.length})`}
							style={{ marginRight: "12px" }}
							onClick={() => setSaveOpen(true)}
						></MyButton>
						<MyButton
							variant="outlined"
							text={`下载(${selectItems.length})`}
							onClick={() => setDownloadOpen(true)}
						></MyButton>
					</>
				)}
			</div>
			{saveOpen && (
				<Save
					type={productId as string}
					projectId={projectId}
					token={token}
					fileToken={fileToken}
					path={path}
					name={name}
					selectIds={selectItems}
					open={saveOpen}
					setOpen={setSaveOpen}
				></Save>
			)}
			{downloadOpen && (
				<Download
					type={productId as string}
					projectId={projectId}
					token={token}
					fileToken={fileToken}
					path={path}
					name={name}
					selectIds={selectItems}
					open={downloadOpen}
					setOpen={setDownloadOpen}
				></Download>
			)}
		</FullScreenDrawer>
	);
});

export default SeeDataset;
