/*
 * @Author: 吴永生#A02208 yongsheng.wu@wholion.com
 * @Date: 2022-06-21 20:03:56
 * @LastEditors: 吴永生 15770852798@163.com
 * @LastEditTime: 2022-08-09 15:49:59
 * @FilePath: /bkunyun/src/views/Project/ProjectSubmitWork/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useCallback, useEffect, useState, useMemo } from "react";
import _ from "lodash";
import { useStores } from "@/store";
import { toJS } from "mobx";
import { observer } from "mobx-react-lite";

import MyPopconfirm from "@/components/mui/MyPopconfirm";
import RadioGroupOfButtonStyle from "@/components/CommonComponents/RadioGroupOfButtonStyle";
import MyButton from "@/components/mui/MyButton";
import OperatorList from "./components/OperatorList";
import Flow from "../Project/components/Flow";
import ParameterSetting from "./components/ParameterSetting";
import { useMessage } from "@/components/MySnackbar";
import { ITask } from "../Project/ProjectSubmitWork/interface";
import { fetchTemplateConfigInfo } from "@/api/project_api";
import { getCustomTemplateParameterCheckResult } from "./util";
import useMyRequest from "@/hooks/useMyRequest";
import CustomOperator from "../CustomOperator";
import SaveCustomTemplate from "./components/SaveCustomTemplate";
import AddIcon from "@mui/icons-material/Add";
import goback from "@/assets/project/goback.svg";

import styles from "./index.module.css";

const radioOptions = [
	{
		value: "list",
		label: "算子列表",
	},
	{
		value: "setting",
		label: "参数设置",
	},
];

interface IProps {
	onBack?: () => void;
	id?: string;
}

const WorkFlowEdit = observer((props: IProps) => {
	const { onBack, id } = props;
	const Message = useMessage();
	const [templateConfigInfo, setTemplateConfigInfo] = useState<ITask[]>([]); // 算子大数组
	const [showCustomOperator, setShowCustomOperator] = useState(false); // 是否显示自定义算子
	const { currentProjectStore } = useStores();
	const zoneId = toJS(currentProjectStore.currentProjectInfo.zoneId);
	const [saveFormDialog, setSaveFormDialog] = useState(false); // 保存弹窗显示与否控制
	const [title, setTitle] = useState(""); // 自定义模板名称
	const [version, setVersion] = useState("1.0.0"); // 自定义模板版本
	const [oldversion, setOldersion] = useState(""); // 编辑是自定义模板的老版本
	const [description, setDescription] = useState(""); // 自定义模板描述
	const [creator, setCreator] = useState(""); // 自定义模板创建人
	const [operatingArea, setOperatingArea] = useState<"form" | "flow">("form"); // 当前操作区域

	const [leftContentType, setLeftContentType] = useState("list"); // 页面左侧展示的是算子列表还是参数设置
	const [popperTitle, setPopperTitle] = useState(
		// 确认弹窗标题
		"返回后，当前页面已填写内容将不保存，确认返回吗？"
	);

	// 是否要监听删除时间
	const listenState = useMemo(() => {
		if (operatingArea === "form") {
			return false;
		}
		return !saveFormDialog && !showCustomOperator;
	}, [operatingArea, saveFormDialog, showCustomOperator]);

	// 编辑时获取模板详情的方法
	const { run: fetchTemplateConfigInfoRun } = useMyRequest(
		fetchTemplateConfigInfo,
		{
			onSuccess: (res: any) => {
				if (res.data) {
					setTemplateConfigInfo(res.data.tasks);
					setTitle(res.data.title);
					setOldersion(res.data.version);
					let version = res.data.version;
					let arr = version.split(".");
					if (arr.length === 3) {
						if (Number(arr[2]) < 99) {
							arr[2] = String(Number(arr[2]) + 1);
						} else {
							arr[2] = "0";
							if (Number(arr[1]) < 99) {
								arr[1] = String(Number(arr[1]) + 1);
							} else {
								arr[1] = "0";
								arr[0] = String(Number(arr[0]) + 1);
							}
						}
					}
					setVersion(arr.join("."));
					setCreator(res.data.creator);
					setDescription(res.data.description);
				}
			},
		}
	);

	// id存在时获取模板详情
	useEffect(() => {
		if (id) {
			fetchTemplateConfigInfoRun({ id });
		}
	}, [id, fetchTemplateConfigInfoRun]);

	/** 页面刷新提醒 */
	const pageRefreshTips = (e: any) => {
		const event: any = window.event || e;
		event.returnValue = "确定回退页面吗？";
	};

	/** 监听页面刷新事件 */
	useEffect(() => {
		window.addEventListener("beforeunload", pageRefreshTips, false);
		return () => {
			window.removeEventListener("beforeunload", pageRefreshTips, false);
		};
	});

	// 确认弹窗相对位置
	const [anchorEl, setAnchorEl] = useState<any>(null);
	// 隐藏确认弹窗，   确认弹窗点击取消
	const handleCancel = () => {
		setAnchorEl(null);
	};

	// 显示确认弹窗
	const handleShowPopper = (e: any, title: string) => {
		setPopperTitle(title);
		setAnchorEl(anchorEl ? null : e.currentTarget);
	};

	// 确认弹窗确认回调
	const handleConfirm = () => {
		if (popperTitle === "返回后，当前页面已填写内容将不保存，确认返回吗？") {
			onBack && onBack();
		}
	};

	// 点击保存  先校验工作流  再显示自定义模板基础信息弹窗
	const handlePreserve = () => {
		// 校验
		if (templateConfigInfo.length === 0) {
			Message.error("工作流不能为空！");
			return;
		}
		let templateConfigInfoClone: ITask[] = _.cloneDeep(templateConfigInfo);
		let tasksIsCheck = true; // 整体校验
		templateConfigInfoClone.forEach((task) => {
			let taskIsCheck = true; // 单个task校验
			task.parameters.forEach((parameter) => {
				if (task.type === "BATCH" && parameter.thrown) {
					return;
				}
				const checkResult = getCustomTemplateParameterCheckResult(parameter);
				parameter.error = checkResult.error;
				parameter.helperText = checkResult.helperText;
				if (checkResult.error) {
					taskIsCheck = false;
					tasksIsCheck = false;
				}
			});
			task.isCheck = taskIsCheck;
		});
		setTemplateConfigInfo(templateConfigInfoClone);
		if (!tasksIsCheck) {
			Message.error("工作流校验未通过，请检查！");
		} else {
			setSaveFormDialog(true);
		}
	};

	/** 选中的task 唯一标识符 */
	const [selectTaskId, setSelectTaskId] = useState<string>();

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

	return (
		<div className={styles.swBox}>
			<div className={styles.swHeader}>
				<div
					className={styles.swHeaderLeft}
					onClick={(e: any) =>
						handleShowPopper(
							e,
							"返回后，当前页面已填写内容将不保存，确认返回吗？"
						)
					}
				>
					<div className={styles.goBackIconBox}>
						<img className={styles.goBackIcon} src={goback} alt="" />
					</div>
					<span className={styles.goBack}>返回</span>
				</div>
				<div className={styles.swHeaderRight}>
					<MyButton text="保存" onClick={() => handlePreserve()}></MyButton>
				</div>
			</div>
			<div className={styles.swContent}>
				<div
					className={styles.swFormBox}
					onClick={() => {
						setOperatingArea("form");
					}}
				>
					<div className={styles.radiosBox}>
						<RadioGroupOfButtonStyle
							radioOptions={radioOptions}
							value={leftContentType}
							handleRadio={setLeftContentType}
							RadiosBoxStyle={{
								height: "36px",
								padding: "3px",
							}}
							radioStyle={{
								fontSize: "16px",
								height: "30px",
							}}
							radioActiveBgBoxStyle={{
								height: "32px",
							}}
						/>
					</div>
					{leftContentType === "list" && (
						<OperatorList
							showCustomOperator={showCustomOperator}
							templateConfigInfo={templateConfigInfo}
							setTemplateConfigInfo={setTemplateConfigInfo}
						/>
					)}
					{leftContentType !== "list" && (
						<ParameterSetting
							templateConfigInfo={templateConfigInfo}
							setTemplateConfigInfo={setTemplateConfigInfo}
							taskId={selectTaskId || ""}
							zoneId={zoneId as string}
						/>
					)}
					<div
						className={styles.addOperator}
						onClick={() => setShowCustomOperator(true)}
					>
						<AddIcon sx={{ padding: "6px" }} />
						<span className={styles.addText}>添加算子</span>
					</div>
				</div>
				<div
					className={styles.swFlowBox}
					id="workFlowEditRight"
					onClick={() => {
						setOperatingArea("flow");
					}}
				>
					<Flow
						tasks={templateConfigInfo}
						setTasks={setTemplateConfigInfo}
						type="edit"
						onFlowNodeClick={handleNodeClick}
						ListenState={listenState}
					/>
				</div>
			</div>
			<MyPopconfirm
				title={popperTitle}
				anchorEl={anchorEl}
				onCancel={handleCancel}
				onConfirm={handleConfirm}
				placement="bottom-end"
			/>
			{saveFormDialog && (
				<SaveCustomTemplate
					title={title}
					setTitle={setTitle}
					description={description}
					setDescription={setDescription}
					version={version}
					setVersion={setVersion}
					creator={creator}
					setSaveFormDialog={setSaveFormDialog}
					saveFormDialog={saveFormDialog}
					onBack={onBack}
					templateConfigInfo={templateConfigInfo}
					id={id}
					oldversion={oldversion}
				/>
			)}
			{showCustomOperator && (
				<CustomOperator
					setShowCustomOperator={() => setShowCustomOperator(false)}
					initOperatorList={JSON.parse(
						sessionStorage.getItem("operatorList") || "[]"
					)}
				/>
			)}
		</div>
	);
});

export default WorkFlowEdit;
