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

import ConfigForm from "./ConfigForm";
import WorkFlow from "./WorkFlow";
import MyButton from "@/components/mui/MyButton";
import { ITemplateConfig } from "./interface";
import useMyRequest from "@/hooks/useMyRequest";
import { fetchTemplateConfigInfo, submitWorkFlow } from "@/api/project_api";
import { getCheckResult } from "./util";
import { IResponse } from "@/api/http";
import fullScreen from "@/assets/project/fullScreen.svg";
import partialScreen from "@/assets/project/partialScreen.svg";
import { useMessage } from "@/components/MySnackbar";
import { useStores } from "@/store";
import { observer } from "mobx-react-lite";
import MyPopconfirm from "@/components/mui/MyPopconfirm";
import goback from "@/assets/project/goback.svg";

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

const ProjectSubmitWork = observer(() => {
	const Message = useMessage();
	const { currentProjectStore } = useStores();
	const projectId = toJS(currentProjectStore.currentProjectInfo.id);
	const zoneId = toJS(currentProjectStore.currentProjectInfo.zoneId);
	const productId = toJS(currentProjectStore.currentProductInfo.id); // 产品ID
	const [templateConfigInfo, setTemplateConfigInfo] =
		useState<ITemplateConfig>();
	const location: any = useLocation();
	const navigate = useNavigate();
	let configFormRef: any = React.createRef();
	/** 是否全屏 */
	const [fullScreenShow, setFullScreenShow] = useState<boolean>(false);
	const [externalSelectedNodeId, setExternalSelectedNodeId] =
		useState<string>("");

	// 前往工作台
	const goToWorkbench = (toWorkbenchList = false) => {
		navigate(`/product/${productId || "cadd"}/projectWorkbench`, {
			state: { type: toWorkbenchList ? "workbenchList" : "" },
		});
	};

	// 返回
	const handleGoBack = () => {
		goToWorkbench();
	};

	if (!location?.state?.id) {
		goToWorkbench();
	}

	/** 获取模版数据 */
	const { run } = useMyRequest(fetchTemplateConfigInfo, {
		onSuccess: (res: IResponse<ITemplateConfig>) => {
			// setTemplateConfigInfo(templateConfigJson as ITemplateConfig);
			res.data.tasks.forEach((task) => {
				// 设置默认值
				task.parameters.forEach((parameter) => {
					let value: any = undefined;
					if (parameter.defaultValue) {
						if (
							(parameter.domType || "").toLowerCase() === "multipleselect" ||
							(parameter.domType || "").toLowerCase() === "checkbox"
						) {
							value = parameter.defaultValue.split(",");
						} else if ((parameter.domType || "").toLowerCase() === "input") {
							value = String(parameter.defaultValue);
						} else {
							value = parameter.defaultValue;
						}
					} else if (
						(parameter.domType || "").toLowerCase() === "multipleselect" ||
						(parameter.domType || "").toLowerCase() === "checkbox"
					) {
						value = [];
					} else if ((parameter.domType || "").toLowerCase() === "input") {
						value =
							String(parameter.defaultValue) === "null"
								? ""
								: String(parameter.defaultValue);
					} else if ((parameter.domType || "").toLowerCase() === "radio") {
						value = false;
					} else if ((parameter.domType || "").toLowerCase() === "partition") {
						value = false;
					} else {
						value = parameter.defaultValue;
					}
					parameter.value = value;
				});
				// 设置右边流程图某个节点是否通过（绿点）
				let isCheck = true;
				task.parameters
					.filter((parameter) => parameter.hidden === false)
					.forEach((parameter) => {
						if (getCheckResult(parameter, parameter.value).error === true) {
							isCheck = false;
						}
					});
				task.isCheck = isCheck;
			});
			setTemplateConfigInfo(res.data);
			configFormRef.current.setInitName(res.data.title);
		},
		onError: () => {
			// setTemplateConfigInfo(templateConfigJson as ITemplateConfig);
		},
	});

	const { run: submitWorkFlowRun, loading } = useMyRequest(submitWorkFlow, {
		onSuccess: (res) => {
			Message.success("提交成功");
			goToWorkbench(true);
		},
	});

	useEffect(() => {
		run({
			id: location?.state?.id,
		});
	}, [location?.state?.id, run]);

	const setParameter = (value: any, taskId: string, parameterName: string) => {
		const result: ITemplateConfig = _.cloneDeep(templateConfigInfo);
		result.tasks.forEach((task) => {
			if (task.id === taskId) {
				let isCheck = true;
				task.parameters
					.filter((parameter) => parameter.hidden === false)
					.forEach((parameter) => {
						if (parameter.name === parameterName) {
							parameter.value = value;
							const checkResult = getCheckResult(parameter, value);
							parameter.error = checkResult.error;
							parameter.helperText = checkResult.helperText;
						}
						if (getCheckResult(parameter, parameter.value).error === true) {
							isCheck = false;
						}
					});
				task.isCheck = isCheck;
			} else {
				return;
			}
		});
		setTemplateConfigInfo(result);
	};

	const handleSubmitForm = () => {
		let check = true;
		const { name, outputPath, nameAndOutputPathCheck } =
			configFormRef.current.getNameAndPath();
		if (!nameAndOutputPathCheck) {
			check = false;
		}
		const result: ITemplateConfig = _.cloneDeep(templateConfigInfo);
		result.tasks.forEach((tack) => {
			tack.parameters
				.filter((parameter) => parameter.hidden === false)
				.forEach((parameter) => {
					if (tack.type === "BATCH" && parameter?.thrown) {
						return;
					}
					const checkResult = getCheckResult(parameter, parameter.value);
					parameter.error = checkResult.error;
					parameter.helperText = checkResult.helperText;
					if (checkResult.error) {
						check = false;
					}
				});
		});
		setTemplateConfigInfo(result);
		if (check) {
			let promotedParameters: any = {};
			result.tasks.forEach((tack) => {
				tack.parameters
					.filter((parameter) => parameter.hidden === false)
					.forEach((parameter) => {
						let value: string = "";
						if (Array.isArray(parameter.value)) {
							value = parameter.value.join(",");
						} else {
							value = parameter.value;
						}
						if (
							(parameter.domType || "").toLowerCase() === "path" ||
							(parameter.domType || "").toLowerCase() === "dataset" ||
							(parameter.domType || "").toLowerCase() === "file"
						) {
							value = `/${value}`;
						}
						if (tack.type === "BATCH") {
							if (!parameter?.thrown) {
								promotedParameters[`${tack.id}_${parameter.name}`] = {
									[parameter.classTypeName]: value,
								};
							}
						} else {
							promotedParameters[
								`${tack.parentNode}${
									parameter.thrown ? "" : "_" + tack.prefix
								}_${parameter.name}`
							] = {
								[parameter.classTypeName]: value,
							};
						}
					});
			});
			submitWorkFlowRun({
				name,
				outputPath: `/${outputPath}`,
				projectId: projectId as string,
				specId: templateConfigInfo?.id as string,
				promotedParameters,
			});
		} else {
			handleCancel();
			Message.error("请完善算子信息后提交任务");
		}
	};

	const [popperTitle, setPopperTitle] = useState(
		"提交前请先确认参数填写无误，确认提交吗？"
	);
	const [placement, setPlacement] = useState<
		"bottom" | "bottom-start" | "bottom-end"
	>("bottom");
	const [anchorEl, setAnchorEl] = useState<any>(null);
	const handleCancel = () => {
		setAnchorEl(null);
	};

	const handleShowPopper = (
		e: any,
		title: string,
		placementParams: "bottom" | "bottom-start" | "bottom-end"
	) => {
		setPlacement(placementParams);
		setPopperTitle(title);
		setAnchorEl(anchorEl ? null : e.currentTarget);
	};

	const handleConfirm = () => {
		if (popperTitle === "提交前请先确认参数填写无误，确认提交吗？") {
			handleSubmitForm();
		} else {
			handleGoBack();
		}
	};

	return (
		<div className={styles.swBox}>
			{fullScreenShow ? null : (
				<div className={styles.swHeader}>
					<div className={styles.swHeaderLeft}>
						<div className={styles.goBackIconBox}>
							<img
								className={styles.goBackIcon}
								src={goback}
								alt=""
								onClick={(e: any) =>
									handleShowPopper(
										e,
										"返回将放弃当前页面所有操作，确认返回吗？",
										"bottom-end"
									)
								}
							/>
						</div>
						<div className={styles.swTemplateTitle}>
							{templateConfigInfo?.title}
						</div>
						<div className={styles.swTemplateVersionBox}>
							<span className={styles.swHeaderLable}>版本：</span>
							<span className={styles.swHeaderValue}>
								{templateConfigInfo?.version}
							</span>
						</div>
						<div className={styles.swTemplateUpdateTimeBox}>
							<span className={styles.swHeaderLable}>更新时间：</span>
							<span className={styles.swHeaderValue}>
								{templateConfigInfo?.updatedTime
									? moment(templateConfigInfo?.updatedTime).format(
											"YYYY-MM-DD HH:mm:ss"
									  )
									: "-"}
							</span>
						</div>
						<div className={styles.swHeaderGoback}></div>
					</div>
					<div className={styles.swHeaderRight}>
						<MyButton
							text="提交任务"
							onClick={(e: any) =>
								handleShowPopper(
									e,
									"提交前请先确认参数填写无误，确认提交吗？",
									"bottom-start"
								)
							}
						></MyButton>
					</div>
				</div>
			)}
			<div className={styles.swContent}>
				{fullScreenShow ? null : (
					<div className={styles.swFormBox}>
						<ConfigForm
							onRef={configFormRef}
							templateConfigInfo={templateConfigInfo}
							setParameter={setParameter}
							setExternalSelectedNodeId={setExternalSelectedNodeId}
							zoneId={zoneId as string}
						/>
					</div>
				)}
				<div
					className={styles.swFlowBox}
					style={fullScreenShow ? { height: "100vh" } : undefined}
				>
					<WorkFlow
						templateConfigInfo={templateConfigInfo}
						setExternalSelectedNodeId={setExternalSelectedNodeId}
						externalSelectedNodeId={externalSelectedNodeId}
					/>
				</div>
			</div>
			<img
				className={styles.fullScreenBox}
				src={fullScreenShow ? partialScreen : fullScreen}
				onClick={() => setFullScreenShow(!fullScreenShow)}
				alt="全屏"
			/>
			<MyPopconfirm
				title={popperTitle}
				anchorEl={anchorEl}
				onCancel={handleCancel}
				onConfirm={handleConfirm}
				loading={loading}
				placement={placement}
			/>
		</div>
	);
});

export default ProjectSubmitWork;
