import { InputBase, IconButton } from "@mui/material";
import SearchIcon from "@mui/icons-material/Search";
import styles from "./index.module.css";
import cloneDeep from "lodash/cloneDeep";
import { getScrollLoader } from "@/utils/util";
import { useState, useCallback, useEffect } from "react";
import { getOperatorList } from "@/api/project_api";
import CircularProgress from "@mui/material/CircularProgress";
import useMyRequest from "@/hooks/useMyRequest";
import { useStores } from "@/store";
import { toJS } from "mobx";
import { ITask } from "@/views/Project/ProjectSubmitWork/interface";

let count = 1;

type IProps = {
	operatorList: any;
	setOperatorList: any;
};

const OperatorList = (props: IProps) => {
	const { operatorList, setOperatorList } = props; // 流程图中流算子列表
	const { currentProjectStore } = useStores();
	const [list, setList] = useState<ITask[]>([]); // 算子列表
	const productId = toJS(currentProjectStore.currentProductInfo.id);
	const [keyword, setKeyword] = useState(""); // 搜索算子列表时的关键词
	const [dragItem, setDragItem] = useState<any>({}); // 拖拽的算子
	const [page, setPage] = useState(0); //
	const [isLastPage, setIsLastPage] = useState(false);
	// todo 加载中   没有更多了样式
	const { run: getOperatorListRun, loading } = useMyRequest(getOperatorList, {
		onSuccess: (res) => {
			let arr = res?.data?.content;
			setIsLastPage(res?.data?.last);
			arr.forEach((item: any, index: number) => {
				item.edges = [];
				item.parameters.push({
					choices: [],
					classType: "STRING",
					classTypeName: "String",
					defaultValue: null,
					description: "",
					domType: "dataset",
					hidden: false,
					isnull: false,
					level: null,
					linked: false,
					many: false,
					name: `in${index + 1}`,
					order: 0,
					parameterGroup: "in",
					promoted: false,
					promotedName: null,
					required: false,
					title: null,
					validators: [],
				});
			});
			arr.forEach((item: any, index: number) => {
				item.parameters.push({
					choices: [],
					classType: "STRING",
					classTypeName: "String",
					defaultValue: null,
					description: "",
					domType: "dataset",
					hidden: false,
					isnull: false,
					level: null,
					linked: false,
					many: false,
					name: `out${index + 1}`,
					order: 0,
					parameterGroup: "out",
					promoted: false,
					promotedName: null,
					required: false,
					title: null,
					validators: [],
				});
			});
			setList([...list, ...arr]);
			// setList(res?.data?.content || []);
		},
	});

	const getOperatorListFun = useCallback(
		(keyword: string = "", page = 0) => {
			getOperatorListRun({
				productId: productId as string,
				keyword,
				page,
				size: 5,
			});
			// size: 20   todo
		},
		[productId, getOperatorListRun]
	);

	useEffect(() => {
		getOperatorListFun();
	}, [getOperatorListFun]);

	const keywordChange = (e: any) => {
		if (e.target.value.length <= 30) {
			setKeyword(e.target.value);
		}
	};

	const handleKeywordKeyUp = (e: any) => {
		if (e.keyCode === 13) {
			setList([]);
			setKeyword(e.target.value);
			setPage(0);
			getOperatorListFun(e.target.value, 0);
		}
	};
	// const list = [
	// 	{
	// 		title: "这是中文",
	// 		version: "1.0.0",
	// 	},
	// 	{
	// 		allVersions: ["1.0.0", "2.0.0"],
	// 		creator: "root",
	// 		description: "这是一段Hitlist算子的描述",
	// 		edges: [
	// 			{
	// 				id: "fdd26229-3a1f-46e7-a14a-dd55bcce55e4",
	// 				label: null,
	// 				source: "62c7965c9bf7ba39f2dcefcc",
	// 				sourceHandle: null,
	// 				target: "62c7965c9bf7ba39f2dcefce",
	// 				targetHandle: null,
	// 			},
	// 		],
	// 		id: "62c7965c9bf7ba39f2dcefcc",
	// 		parameters: [
	// 			{
	// 				name: "cpus",
	// 				classType: "INT",
	// 				classTypeName: "Int",
	// 				required: false,
	// 				defaultValue: "1",
	// 			},
	// 		],
	// 		// parentNode: "62c7965c9bf7ba39f2dcefc8",
	// 		position: { x: 40, y: 200 },
	// 		productId: "cadd",
	// 		status: null,
	// 		title: "Hitlist",
	// 		type: "FLOW",
	// 		version: "2.0.0",
	// 	},
	// 	{
	// 		title: "asdf",
	// 		version: "1.0.0",
	// 	},
	// 	{
	// 		title: "asdf",
	// 		version: "1.0.0",
	// 	},
	// 	{
	// 		title: "asdf",
	// 		version: "1.0.0",
	// 	},
	// ];

	const handleScroll = (e: any) => {
		if (getScrollLoader(e)) {
			console.log("加载1");
			if (loading || isLastPage) {
				return;
			} else {
				console.log("加载2");
				getOperatorListFun(keyword, page + 1);
				setPage(page + 1);
			}
		}
	};

	const randerIcon = () => {
		return (
			<div className={styles.icon}>
				<div className={styles.iconLi}>
					<div className={styles.iconItem}></div>
					<div className={styles.iconItem}></div>
				</div>
				<div className={styles.iconLi}>
					<div className={styles.iconItem}></div>
					<div className={styles.iconItem}></div>
				</div>
				<div className={styles.iconLi}>
					<div className={styles.iconItem}></div>
					<div className={styles.iconItem}></div>
				</div>
			</div>
		);
	};

	/** 拖拽开始 */
	const onDragStart = (item: any) => {
		setDragItem(item);
		console.log("onDragStart");
		// setIsDragStyle(true);
		count++;
	};

	/** 生成批流副本 */
	const getNewOperatorItem = useCallback(
		(task: ITask, x: number, y: number) => {
			const newEdges =
				task?.edges &&
				task?.edges.map((every) => {
					return {
						...every,
						source: `${every.source}_${count}`,
						target: `${every.target}_${count}`,
					};
				});
			return {
				...task,
				id: `${task.id}_${count}`,
				position: {
					x: x,
					y: y,
				},
				edges: newEdges.length ? newEdges : task?.edges,
			};
			// const newVal = arr.map((item) => {
			// 	const newEdges =
			// 		item?.edges &&
			// 		item?.edges.map((every) => {
			// 			return {
			// 				...every,
			// 				source: `${every.source}_${count}`,
			// 				target: `${every.target}_${count}`,
			// 			};
			// 		});
			// 	return {
			// 		...item,
			// 		id: `${item.id}_${count}`,
			// 		parentNode: item.parentNode ? `${item.parentNode}_${count}` : "",
			// 		position: {
			// 			x: item.position?.x,
			// 			y: item.position?.y,
			// 		},
			// 		edges: newEdges.length ? newEdges : item?.edges,
			// 	};
			// });
			// return newVal;
		},
		[]
	);

	/** 拖拽结束 */
	const onDragEnd = useCallback(
		(e: React.DragEvent<HTMLDivElement>) => {
			const dom = document.getElementById("customOperatorFlow");
			console.log(e);
			console.log(dom);
			const clientX = e.clientX;
			const clientY = e.clientY;
			const upperLeftPointX = Number(dom?.offsetLeft);
			const upperLeftPointY = Number(dom?.offsetTop);
			const lowerRightX = Number(upperLeftPointX) + Number(dom?.offsetWidth);
			const lowerRightY = Number(upperLeftPointY) + Number(dom?.offsetHeight);
			if (
				clientX > upperLeftPointX &&
				clientY > upperLeftPointY &&
				clientX < lowerRightX &&
				clientY < lowerRightY
			) {
				// const batchFlowArr = getBatchFlowArr(info.id);
				const newDragItem = cloneDeep(dragItem);
				const newOperatorItem = getNewOperatorItem(
					newDragItem,
					clientX - upperLeftPointX,
					clientY - upperLeftPointY - 42
				);
				// const newOperatorItem = {
				// 	...newDragItem,
				// 	id: `${newDragItem.id}_${count}`,
				// 	source: `${newDragItem.source}_${count}`,
				// 	target: `${newDragItem.target}_${count}`,
				// 	position: {
				// 		x: clientX - upperLeftPointX,
				// 		y: clientY - upperLeftPointY,
				// 	},
				// };
				const newVal = cloneDeep(operatorList);
				newVal.push(newOperatorItem);
				console.log(newVal);
				setOperatorList(newVal);
				// setTemplateConfigInfo(newVal);
			}
			// setIsDragStyle(false);
		},
		[dragItem, operatorList, setOperatorList, getNewOperatorItem]
	);

	return (
		<div className={styles.operatorList}>
			<div className={styles.searchBox}>
				<IconButton
					type="submit"
					className={styles.searchButton}
					aria-label="search"
				>
					<SearchIcon
						className={styles.searchIcon}
						style={{ color: "rgba(153, 153, 153, 1)" }}
					/>
				</IconButton>
				<InputBase
					className={styles.searchInput}
					placeholder="请输入算子名称"
					value={keyword}
					onChange={keywordChange}
					onKeyUp={handleKeywordKeyUp}
				/>
			</div>
			<div className={styles.list} onScroll={(e) => handleScroll(e)}>
				{list.map((item, index) => {
					return (
						<div
							key={index}
							className={styles.li}
							draggable={true}
							onDragStart={() => onDragStart(item)}
							onDragEnd={onDragEnd}
						>
							{randerIcon()}
							<div className={styles.nameVersion}>
								<span className={styles.name}>{item.title}</span>
								<span className={styles.version}>v{item.version}</span>
							</div>
							{/* <span className={styles.name}>{item.title}</span>
							<span className={styles.version}>{item.version}</span> */}
						</div>
					);
				})}
				{!loading && (
					<div className={styles.loading}>
						<CircularProgress
							size={12}
							sx={{
								color: "rgba(19, 112, 255, 1)",
								marginRight: "8px",
							}}
						/>
						加载中...
					</div>
				)}
				{!isLastPage && <div className={styles.loading}>已经到底了</div>}
			</div>
		</div>
	);
};

export default OperatorList;
