/*
 * @Author: 吴永生#A02208 yongsheng.wu@wholion.com
 * @Date: 2022-06-21 20:03:56
 * @LastEditors: 吴永生 15770852798@163.com
 * @LastEditTime: 2022-08-08 16:41:20
 * @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 ArrowBackIosNewIcon from "@mui/icons-material/ArrowBackIosNew";
import IconButton from "@mui/material/IconButton";
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 styles from "./index.module.css";

const ProjectSubmitWork = observer(() => {
	const Message = useMessage();
	const { currentProjectStore } = useStores();
	const projectId = toJS(currentProjectStore.currentProjectInfo.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 [selectedBatchNodeId, setSelectedBatchNodeId] = useState<string>("");

	// 前往工作台
	const goToWorkbench = (toWorkbenchList = false) => {
		navigate("/product/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 {
							value = parameter.defaultValue;
						}
					} else if (
						(parameter.domType || "").toLowerCase() === "multipleselect" ||
						(parameter.domType || "").toLowerCase() === "checkbox"
					) {
						value = [];
					} else {
						value = "";
					}
					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 } = 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) => {
					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}`;
						}
						promotedParameters[parameter.name] = {
							[parameter.classTypeName]: value,
						};
					});
			});
			submitWorkFlowRun({
				name,
				outputPath: `/${outputPath}`,
				projectId: projectId as string,
				specId: templateConfigInfo?.id as string,
				promotedParameters,
			});
		} else {
			Message.error("请完善左侧表单再提交");
		}
	};

	const [popperTitle, setPopperTitle] = useState(
		"提交前请先确认参数填写无误，确认提交吗？"
	);
	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 === "提交前请先确认参数填写无误，确认提交吗？") {
			handleSubmitForm();
		} else {
			handleGoBack();
		}
	};

	return (
		<div className={styles.swBox}>
			{fullScreenShow ? null : (
				<div className={styles.swHeader}>
					<div className={styles.swHeaderLeft}>
						<IconButton
							color="primary"
							onClick={(e: any) =>
								handleShowPopper(e, "返回将放弃当前页面所有操作，确认返回吗？")
							}
							aria-label="upload picture"
							component="span"
							size="small"
						>
							<ArrowBackIosNewIcon
								sx={{
									color: "rgba(194, 198, 204, 1)",
									width: "14px",
									height: "14px",
								}}
							/>
						</IconButton>

						<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}>
						{/* <MyPopconfirm
							title="提交前请先确认参数填写无误，确认提交吗？"
							onConfirm={handleSubmitForm}
						> */}
						<MyButton
							text="提交任务"
							onClick={(e: any) =>
								handleShowPopper(e, "提交前请先确认参数填写无误，确认提交吗？")
							}
						></MyButton>
						{/* </MyPopconfirm> */}
					</div>
				</div>
			)}
			<div className={styles.swContent}>
				{fullScreenShow ? null : (
					<div className={styles.swFormBox}>
						<ConfigForm
							onRef={configFormRef}
							templateConfigInfo={templateConfigInfo}
							setParameter={setParameter}
							setSelectedBatchNodeId={setSelectedBatchNodeId}
						/>
					</div>
				)}
				<div
					className={styles.swFlowBox}
					style={fullScreenShow ? { height: "100vh" } : undefined}
				>
					<WorkFlow
						templateConfigInfo={templateConfigInfo}
						setSelectedBatchNodeId={setSelectedBatchNodeId}
						selectedBatchNodeId={selectedBatchNodeId}
					/>
				</div>
			</div>
			<img
				className={styles.fullScreenBox}
				src={fullScreenShow ? partialScreen : fullScreen}
				onClick={() => setFullScreenShow(!fullScreenShow)}
				alt="全屏"
			/>
			<MyPopconfirm
				title={popperTitle}
				anchorEl={anchorEl}
				onCancel={handleCancel}
				onConfirm={handleConfirm}
			/>
		</div>
	);
});

export default ProjectSubmitWork;
