import React, { useCallback, useEffect, useState } from "react";
import { observer } from "mobx-react-lite";
import FullScreenDrawer from "@/components/CommonComponents/FullScreenDrawer";
import MyButton from "@/components/mui/MyButton";
import OperatorList from "./components/OperatorList";
// import Flow from "../Project/components/Flow";
import { useMessage } from "@/components/MySnackbar";
import BatchOperatorFlow from "../Project/components/Flow/components/BatchOperatorFlow";
import SaveOperator from "./components/SaveOperator";
import { ITask } from "../Project/ProjectSubmitWork/interface";
import _ from "lodash";
import styles from "./index.module.css";

type IProps = {
	setShowCustomOperator: any;
	initOperatorList: ITask[];
};

const CustomOperator = observer((props: IProps) => {
	const { setShowCustomOperator, initOperatorList } = props;
	const Message = useMessage();
	const [operatorList, setOperatorList] = useState<ITask[]>(initOperatorList);
	const [saveFormDialog, setSaveFormDialog] = useState(false);
	// const [showCustomOperator, setShowCustomOperator] = useState(false);

	/** 设置选中唯一标识符 */
	const handleNodeClick = useCallback((val: string) => {
		// setSelectTaskId(val);
		// console.log(val);
	}, []);

	// 判断   每个流算子必须至少有一条连接线。
	const checkHasOneLine = (sourceArr: string[], targetArr: string[]) => {
		console.log("checkHasOneLine");
		const all = _.uniq([...sourceArr, ...targetArr]);
		if (all.length === operatorList.length) {
			console.log("checkHasOneLine1");
			return true;
		} else {
			console.log("checkHasOneLine2");
			return false;
		}
		// _.uniq([2, 1, 2]);
	};

	// 判断   每个起始算子（可以有多个起始点）的输入必须为文件的路径输入或数据集的路径输入。
	const checkIn = (targetArr: string[]) => {
		console.log("checkIn");
		const uniqTargetArr = _.uniq(targetArr);
		if (uniqTargetArr.length === operatorList.length) {
			// 流节点连成一个圈了
			return false;
		}
		let check = true;
		operatorList.forEach((flowNode) => {
			if (uniqTargetArr.indexOf(flowNode.id) === -1) {
				// 该节点的输入没有连线  也就是说这个节点是起点
				const inArr = flowNode.parameters.filter(
					(parameter) => parameter.parameterGroup === "in"
				);
				if (inArr.length > 0) {
					if (
						!inArr.some((inItem) => {
							return (
								(inItem.domType || "").toLowerCase() === "dataset" ||
								(inItem.domType || "").toLowerCase() === "path" ||
								(inItem.domType || "").toLowerCase() === "file"
							);
						})
					) {
						check = false;
					}
				} else {
					// 起点没有输入
					check = false;
				}
			}
		});
		return check;
	};

	// 判断  起码有一个结尾算子（可以有多个结尾点）的输出必须为文件保存或数据集保存。
	const checkOut = (sourceArr: string[]) => {
		console.log("checkOut");
		const uniqSourceArr = _.uniq(sourceArr);
		if (uniqSourceArr.length === operatorList.length) {
			// 流节点连成一个圈了
			return false;
		}
		let check = true;
		operatorList.forEach((flowNode) => {
			if (uniqSourceArr.indexOf(flowNode.id) === -1) {
				// 该节点的输入没有连线  也就是说这个节点是起点
				const outArr = flowNode.parameters.filter(
					(parameter) => parameter.parameterGroup === "out"
				);
				if (outArr.length > 0) {
					if (
						!outArr.some((outItem) => {
							return (
								(outItem.domType || "").toLowerCase() === "dataset" ||
								(outItem.domType || "").toLowerCase() === "file" ||
								(outItem.domType || "").toLowerCase() === "path"
							);
						})
					) {
						check = false;
					}
				} else {
					// 起点没有输入
					check = false;
				}
			}
		});
		return check;
	};

	useEffect(() => {
		sessionStorage.setItem("operatorList", JSON.stringify(operatorList));
	}, [operatorList]);

	const handleCheck = () => {
		if (operatorList.length === 0) {
			Message.error("内容不能为空！");
			return;
		}
		let sourceArr: string[] = [];
		let targetArr: string[] = [];
		operatorList.forEach((flowNode) => {
			flowNode.edges.forEach((edge) => {
				edge.source && sourceArr.push(edge.source);
				edge.target && targetArr.push(edge.target);
			});
		});
		console.log("operatorList", operatorList);
		console.log("sourceArr", sourceArr);
		console.log("targetArr", targetArr);
		if (!checkHasOneLine([...sourceArr], [...targetArr])) {
			console.log("checkHasOneLine");
			Message.error("内容校验未通过，请检查！");
			return;
		}
		if (!checkIn([...targetArr])) {
			console.log("checkIn");
			Message.error("内容校验未通过，请检查！");
			return;
		}
		if (!checkOut([...sourceArr])) {
			console.log("checkOut");
			Message.error("内容校验未通过，请检查！");
			return;
		}
		setSaveFormDialog(true);
	};

	return (
		<FullScreenDrawer handleClose={setShowCustomOperator} zIndex={1100}>
			<div className={styles.customOperator}>
				<div className={styles.coTop}>
					<div className={styles.coTitle}>添加算子</div>
					<MyButton
						text="添加"
						onClick={() => {
							handleCheck();
						}}
					></MyButton>
					<SaveOperator
						saveFormDialog={saveFormDialog}
						setSaveFormDialog={setSaveFormDialog}
						operatorList={operatorList}
					></SaveOperator>
				</div>
				<div className={styles.coContent} id="customOperatorFlow">
					<OperatorList
						operatorList={operatorList}
						setOperatorList={setOperatorList}
					/>
					<BatchOperatorFlow
						tasks={operatorList}
						setTasks={setOperatorList}
						type="edit"
						onFlowNodeClick={handleNodeClick}
						flowNodeDraggable={true}
						ListenState={!saveFormDialog}
						showVersion={true}
						showControls={false}
					/>
				</div>
			</div>
		</FullScreenDrawer>
	);
});

export default CustomOperator;
