import FullScreenDrawer from "@/components/CommonComponents/FullScreenDrawer";
import { useState, useMemo, useCallback, useEffect } from "react";
import RadioGroupOfButtonStyle from "@/components/CommonComponents/RadioGroupOfButtonStyle";
import MyMultipleMenu, { IOption } from "@/components/mui/MyMultipleMenu";
import MySelect from "@/components/mui/MySelect";
import MyInput from "@/components/mui/MyInput";
import MyButton from "@/components/mui/MyButton";
import SearchIcon from "@mui/icons-material/Search";
import MyPagination from "@/components/mui/MyPagination";
import NglView from "@/components/BusinessComponents/NglView";
import KekuleView from "@/components/BusinessComponents/KekuleView";
import Checkbox from "@mui/material/Checkbox";
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 "./save";
import NoData from "@/components/BusinessComponents/NoData";
import Download from "./download";
import style from "./index.module.css";

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

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 [graphicDimension, setGraphicDimension] = useState("2D"); // 分子结构图是2D还是3D
	const [showData, setShowData] = useState<Array<string>>([]); //显示的数据类型
	const [dataTypes, setdataTypes] = useState<Array<IOption>>([]); // 可选的数据类型
	const [sort, setSort] = useState("null"); // 排序方式
	const [keyword, setKeyword] = useState(""); // 关键字
	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 [showAnimation, setShowAnimation] = useState(true); // 弹窗动画变化中

	// 解决图像渲染造成弹窗卡顿的问题
	useEffect(() => {
		setTimeout(() => {
			setShowAnimation(false);
		}, 1000);
	}, []);

	const isCadd = useMemo(() => {
		if (productId === "cadd") {
			return true;
		} else {
			return false;
		}
	}, [productId]);

	const handleSearchDataTypeChange = (e: any) => {
		setSearchDataType(e);
	};
	const handleSortChange = (e: any) => {
		setSort(e);
	};
	const handleKeywordChange = (e: any) => {
		if (e.target.value.length <= 30) {
			setKeyword(e.target.value);
		}
	};

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

	// 空盒子用于布局
	const nullBox = useMemo(() => {
		if (list.length > 4) {
			let nullBoxLength = 8 - list.length;
			return new Array(nullBoxLength).fill("");
		} else {
			return [];
		}
	}, [list]);

	// 获取分子列表
	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: searchDataType ? `meta.${searchDataType}` : "",
				sort: sort === "null" ? "" : sort,
				query: keyword,
			})
				?.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].meta) {
							const meta = res.data.list[0].meta;
							const arr = Object.keys(meta).map((item) => {
								return { label: item, value: item };
							});
							setdataTypes(arr);
							setSearchDataType(arr[0].value);
						}
					}
				})
				?.catch((error) => {
					console.log(error);
					setList([]);
					// Message.error(error?.response?.data?.message || "获取数据集信息失败");
					// Message.error("未搜索到相关数据");
				});
		},
		[
			productId,
			projectId,
			token,
			fileToken,
			path,
			name,
			searchDataType,
			sort,
			keyword,
			// Message,
		]
	);

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

	// 选择/取消分子
	const handleSelectItem = (id: string) => {
		let list: string[] = [...selectItems];
		if (selectItems.filter((e) => e === id).length > 0) {
			list = list.filter((e) => e !== id);
			setSelectItems(list);
		} else {
			list.push(id);
			setSelectItems(list);
		}
	};

	return (
		<FullScreenDrawer handleClose={props.handleClose}>
			<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}>
							{isCadd && (
								<RadioGroupOfButtonStyle
									handleRadio={setGraphicDimension}
									value={graphicDimension}
									radioOptions={[
										{
											value: "2D",
											label: "2D",
										},
										{
											value: "3D",
											label: "3D",
										},
									]}
									RadiosBoxStyle={{ width: "132px" }}
								></RadioGroupOfButtonStyle>
							)}
							<MyMultipleMenu
								value={showData}
								options={dataTypes}
								setValue={setShowData}
								showSelectAll={true}
							>
								<span className={style.selectShowData}>
									选择显示数据({showData.length})
								</span>
							</MyMultipleMenu>
						</div>
						<div className={style.screensRight}>
							<MySelect
								options={dataTypes}
								title="选择属性"
								isTitle={true}
								value={searchDataType}
								onChange={handleSearchDataTypeChange}
								fullWidth={false}
								sx={{
									width: "160px",
									marginRight: "16px",
									height: "32px",
								}}
							></MySelect>
							<MySelect
								options={[
									{
										label: "无",
										value: "null",
									},
									{
										label: "正序",
										value: "ASC",
									},
									{
										label: "倒序",
										value: "DESC",
									},
								]}
								title="排序方式"
								value={sort}
								onChange={handleSortChange}
								isTitle={true}
								fullWidth={false}
								sx={{
									width: "160px",
									marginRight: "16px",
									height: "32px",
								}}
							></MySelect>
							<MyInput
								value={keyword}
								onChange={handleKeywordChange}
								placeholder="请输入关键词搜索"
								fullWidth={false}
								InputProps={{
									endAdornment: <SearchIcon style={{ color: "#8A9099" }} />,
								}}
								sx={{
									width: "340px",
									marginRight: "16px",
									height: "32px",
								}}
							></MyInput>
							<MyButton
								text="确认"
								style={{ width: "68px" }}
								onClick={() => {
									getList();
								}}
							></MyButton>
						</div>
					</div>
				</div>
				{!showAnimation && (
					<div className={style.table}>
						{list.length !== 0 && (
							<>
								<div className={style.list}>
									{list.map((item, index) => {
										return (
											<div
												className={style.datasetLi}
												key={item.id}
												onClick={() => {
													handleSelectItem(item.id);
												}}
											>
												{isCadd && (
													<div className={style.datasetLiTop}>
														{graphicDimension === "2D" && (
															<KekuleView id={`${index}2d`} smi={item.smiles} />
														)}
														{graphicDimension === "3D" && (
															<NglView id={`${index}3d`} content={item.pdb} />
														)}
													</div>
												)}
												<div className={style.datasetLiBottom}>
													<div
														className={style.datasetLiTitle}
														title={item.smiles}
													>
														{item.smiles}
													</div>
													{showData.length !== 0 && (
														<div className={style.datasetLiDataList}>
															{Object.keys(item.meta)
																.filter((key) => showData.indexOf(key) !== -1)
																.map((key, index) => {
																	return (
																		<div
																			className={style.datasetLiDataLi}
																			key={index}
																		>
																			<span
																				className={style.datasetLiDataLiKey}
																			>
																				{key}
																			</span>
																			<span
																				className={style.datasetLiDataLiValue}
																			>
																				{item.meta[key]}
																			</span>
																		</div>
																	);
																})}
														</div>
													)}
													{showData.length === 0 && (
														<div className={style.noDataList}>
															请选择显示数据
														</div>
													)}
												</div>
												{graphicDimension === "2D" && (
													<Checkbox
														size="small"
														sx={{
															padding: "0px",
															position: "absolute",
															top: "16px",
															right: "20px",
															zIndex: 1,
														}}
														checked={selectItems.includes(item.id)}
													/>
												)}
												{graphicDimension === "3D" && (
													<Checkbox
														size="small"
														sx={{
															padding: "0px",
															position: "absolute",
															top: "16px",
															right: "20px",
															zIndex: 1,
															background: "RGBA(30, 38, 51, 1)",
															border: "1px solid #565C66",
															borderRadius: "2px",
														}}
														checked={selectItems.includes(item.id)}
													/>
												)}
											</div>
										);
									})}
									{nullBox.map((item, index) => {
										return (
											<div
												className={classNames({
													[style.datasetLi]: true,
													[style.nullBox]: true,
												})}
												key={index + "null"}
											></div>
										);
									})}
								</div>

								<div className={style.pagination}>
									<MyPagination
										page={page}
										pageChange={pageChange}
										count={count}
									/>
								</div>
							</>
						)}
						{list.length === 0 && <NoData text="未搜索到相关数据"></NoData>}
					</div>
				)}
			</div>
			<div className={style.foot}>
				{isCadd && (
					<MyButton
						variant="outlined"
						text={`下载(${selectItems.length})`}
						style={{ marginRight: "12px" }}
						disabled={selectItems.length === 0}
						onClick={() => setDownloadOpen(true)}
					></MyButton>
				)}
				<MyButton
					disabled={selectItems.length === 0}
					text={`另存为(${selectItems.length})`}
					onClick={() => setSaveOpen(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;
