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 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 { IQuery } from "@/api/fileserver/CloudEController";
import MyInput from "@/components/mui/MyInput";
import MyPopover from "@/components/mui/MyPopover";

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 [loading, setLoading] = useState(false);
	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>(false); // 高级筛选显示隐藏控制
	const [hasSmiles, setHasSmiles] = useState(false); // 是否是分子结构型数据集
	const [dataTypes, setdataTypes] = useState<Array<IOption>>([]); // 可选的数据类型
	const [sortState, setSortState] = useState<sortState>({
		// 排序状态
		field: null,
		order: null,
	});
	const [querylist, setQuerylist] = useState<Array<IQuery>>([]); // 高级筛选
	const [queryInit, setQueryInit] = useState<IQuery>({
		// 高级筛选初始化数据
		index: "",
		compare: ">",
		query: "",
	});
	const [page, setPage] = useState(0); // 当前页码   // 请求接口的页码是从0开始的
	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 [isTop, setIsTop] = useState(true);

	// 滚动滚轮时监听是否到顶
	const onscroll = (e: any) => {
		if (e.target.scrollTop <= 0) {
			console.log(1);
			setIsTop(true);
		} else {
			console.log(2);
			setIsTop(false);
		}
	};

	// 页码改变
	const pageChange = (value: number) => {
		getList(value - 1);
	};

	// 获取分子列表
	const getList = useCallback(
		(paramsPage = 0) => {
			setPage(paramsPage);
			setSelectItems([]);
			let requestQuerylist = querylist.filter((query) => {
				return query.index !== "" && query.query !== "";
			});
			setLoading(true);
			CloudEController.GetDatasetItemsListNew(
				{
					type: productId as string,
					projectId: projectId as string,
					token: token,
					filetoken: fileToken as string,
					path: path,
					name: name,
					page: paramsPage,
					size: tableType === "table" ? 15 : 8,
					index: sortState.field ? sortState.field : "",
					sort: sortState.order ? sortState.order : "",
				},
				requestQuerylist
			)
				?.then((res) => {
					setLoading(false);
					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"].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);
							setShowSearchBox(false);
						}
					}
				})
				?.catch((error) => {
					setLoading(false);
					console.log(error);
					setList([]);
				});
		},
		[
			productId,
			projectId,
			token,
			fileToken,
			path,
			name,
			sortState,
			firstGetList,
			querylist,
			tableType,
		]
	);

	// 当排序状态、展示方式改变的时候获取第一页数据
	useEffect(() => {
		getList(0);
	}, [sortState, tableType]);

	// 高级筛选值变化
	const handleIndexChange = (e: any, subscriptIndex: number) => {
		let arr = _.cloneDeep(querylist);
		arr[subscriptIndex].index = e;
		setQuerylist(arr);
	};

	// 高级筛选值变化
	const handleCompareChange = (e: any, subscriptIndex: number) => {
		let arr = _.cloneDeep(querylist);
		arr[subscriptIndex].compare = e;
		setQuerylist(arr);
	};

	// 高级筛选值变化
	const handleQueryChange = (e: any, subscriptIndex: number) => {
		let arr = _.cloneDeep(querylist);
		arr[subscriptIndex].query = e.target.value;
		setQuerylist(arr);
	};

	// 高级筛选值变化
	const handleDeleteQuery = (index: number) => {
		if (querylist.length === 1) {
			return;
		}
		let arr = _.cloneDeep(querylist);
		arr.splice(index, 1);
		setQuerylist(arr);
	};

	// 高级筛选值初始化
	const handleInitQuerylist = () => {
		setQuerylist([{ ...queryInit }]);
	};

	// 显示数据变化
	const handleSetShowData = (e: any) => {
		if (e.length === 0) {
			setShowData([dataTypes[0].value]);
			return;
		}
		setShowData(e);
	};

	// 高级筛选渲染
	const searchBox = () => {
		return (
			<div className={style.searchBox}>
				<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} key={index}>
								<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>
								<span
									className={classNames({
										[style.deleteIcon]: true,
										[style.deleteIconDisabled]: querylist.length === 1,
										iconfont: true,
										"icon-shanchu": true,
									})}
									onClick={() => handleDeleteQuery(index)}
								></span>
								{/* <div
									onClick={() => handleDeleteQuery(index)}
									className={classNames({
										[style.deleteIcon]: true,
										[style.deleteIconDisabled]: querylist.length === 1,
									})}
								></div> */}
							</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={() => {
								getList(0);
							}}
						></MyButton>
					</div>
				</div>
			</div>
		);
	};

	return (
		<FullScreenDrawer handleClose={props.handleClose} zIndex={1100}>
			<div
				className={classNames({
					[style.datasetBox]: true,
					[style.datasetBoxShowFoot]: true,
				})}
			>
				<div
					className={classNames({
						[style.top]: true,
						[style.topBoxShadow]: !isTop,
					})}
				>
					<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: (
													<span
														style={{
															fontSize: "16px",
															color:
																tableType === "table"
																	? "#1370ff"
																	: "rgba(151, 151, 151, 1)",
														}}
														className="iconfont icon-liebiaopaixu"
													></span>
												),
											},
											{
												value: "card",
												label: (
													<span
														style={{
															fontSize: "16px",
															color:
																tableType === "card"
																	? "#1370ff"
																	: "rgba(151, 151, 151, 1)",
														}}
														className="iconfont icon-tubiaopaixu"
													></span>
												),
											},
										]}
									/>
									<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={(e: any) => handleSetShowData(e)}
								showSelectAll={true}
								iconColor="rgba(138, 144, 153, 1)"
								topContent={
									<div className={style.topContent}>至少勾选一项</div>
								}
							>
								<span className={style.selectShowData}>
									选择显示数据({showData.length})
								</span>
							</MyMultipleMenu>
						</div>
						<div className={style.screensRight}>
							<MyPopover
								open={showSearchBox}
								changeOpen={(e) => setShowSearchBox(e)}
								content={searchBox()}
								transformOrigin={{
									vertical: "top",
									horizontal: "right",
								}}
								anchorOrigin={{
									vertical: "bottom",
									horizontal: "right",
								}}
							>
								<MyButton
									text="高级筛选"
									variant="outlined"
									color="secondary"
									img={
										<span
											style={{
												fontSize: "16px",
												color: "rgba(30, 38, 51, 1)",
												marginRight: "8px",
											}}
											className="iconfont icon-shaixuan"
										></span>
									}
									style={{ margin: "4px 0" }}
								></MyButton>
							</MyPopover>
						</div>
					</div>
				</div>
				<div className={style.table} onScroll={onscroll}>
					{tableType === "table" && (
						<DatasetTable
							list={list}
							showData={showData}
							selectItems={selectItems}
							setSelectItems={setSelectItems}
							sortState={sortState}
							setSortState={setSortState}
							loading={loading}
						></DatasetTable>
					)}
					{tableType === "card" && (
						<DatasetCardTable
							list={list}
							graphicDimension={graphicDimension}
							showData={showData}
							selectItems={selectItems}
							setSelectItems={setSelectItems}
							loading={loading}
						></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;
