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 [inputActive, setInputActive] = useState(false);
	// const [showCustomOperator, setShowCustomOperator] = useState(false);

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

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

	// 判断   每个起始算子（可以有多个起始点）的输入必须为文件的路径输入或数据集的路径输入。
	const checkIn = (targetArr: string[]) => {
		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[]) => {
		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" ||
								(outItem.domType || "").toLowerCase() === "input"
							);
						})
					) {
						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);
			});
		});
		if (!checkHasOneLine([...sourceArr], [...targetArr])) {
			Message.error("部分算子没有流程线，请检查流程！");
			return;
		}
		if (!checkIn([...targetArr])) {
			Message.error("每个流程第一步需读取文件/数据集，请检查流程！");
			return;
		}
		if (!checkOut([...sourceArr])) {
			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}
						setShowCustomOperator={setShowCustomOperator}
					></SaveOperator>
				</div>
				<div className={styles.coContent} id="customOperatorFlow">
					<OperatorList
						operatorList={operatorList}
						setOperatorList={setOperatorList}
						setInputActive={setInputActive}
					/>
					<BatchOperatorFlow
						tasks={operatorList}
						setTasks={setOperatorList}
						type="edit"
						onFlowNodeClick={handleNodeClick}
						flowNodeDraggable={true}
						ListenState={!saveFormDialog && !inputActive}
						showVersion={true}
						showControls={false}
					/>
				</div>
			</div>
		</FullScreenDrawer>
	);
});

export default CustomOperator;
