/*
 * @Author: 吴永生#A02208 yongsheng.wu@wholion.com
 * @Date: 2022-06-21 20:03:56
 * @LastEditors: 吴永生#A02208 yongsheng.wu@wholion.com
 * @LastEditTime: 2022-07-20 15:01:18
 * @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 } from "react";
import ArrowBackIosNewIcon from "@mui/icons-material/ArrowBackIosNew";
import IconButton from "@mui/material/IconButton";
import _ from "lodash";
import { observer } from "mobx-react-lite";

import MyPopconfirm from "@/components/mui/MyPopconfirm";
import RadioGroupOfButtonStyle from "@/components/CommonComponents/RadioGroupOfButtonStyle";
import ButtonComponent 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 SaveCustomTemplate from "./components/SaveCustomTemplate";

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

	// 编辑时获取模板详情的方法
	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 [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 check = true;
		templateConfigInfoClone.forEach((task) => {
			task.parameters.forEach((parameter) => {
				const checkResult = getCustomTemplateParameterCheckResult(parameter);
				parameter.error = checkResult.error;
				parameter.helperText = checkResult.helperText;
				if (checkResult.error) {
					check = false;
				}
			});
		});
		setTemplateConfigInfo(templateConfigInfoClone);
		if (!check) {
			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}>
					<IconButton
						color="primary"
						aria-label="upload picture"
						component="span"
						size="small"
						onClick={(e: any) =>
							handleShowPopper(
								e,
								"返回后，当前页面已填写内容将不保存，确认返回吗？"
							)
						}
					>
						<ArrowBackIosNewIcon
							sx={{
								color: "rgba(194, 198, 204, 1)",
								width: "12px",
								height: "12px",
							}}
						/>
					</IconButton>
				</div>
				<div className={styles.swHeaderRight}>
					<ButtonComponent
						text="保存"
						onClick={() => handlePreserve()}
					></ButtonComponent>
				</div>
			</div>
			<div className={styles.swContent}>
				<div className={styles.swFormBox}>
					<div className={styles.radiosBox}>
						<RadioGroupOfButtonStyle
							radioOptions={radioOptions}
							value={leftContentType}
							handleRadio={setLeftContentType}
							RadiosBoxStyle={{
								height: "36px",
								padding: "3px",
							}}
							radioStyle={{
								fontSize: "16px",
								height: "30px",
							}}
						></RadioGroupOfButtonStyle>
					</div>
					{leftContentType === "list" && (
						<OperatorList
							templateConfigInfo={templateConfigInfo}
							setTemplateConfigInfo={setTemplateConfigInfo}
						/>
					)}
					{leftContentType !== "list" && (
						<ParameterSetting
							templateConfigInfo={templateConfigInfo}
							setTemplateConfigInfo={setTemplateConfigInfo}
							taskId={selectTaskId || ""}
						/>
					)}
				</div>
				<div className={styles.swFlowBox} id="workFlowEditRight">
					<Flow
						tasks={templateConfigInfo}
						setTasks={setTemplateConfigInfo}
						type="edit"
						onFlowNodeClick={handleNodeClick}
						ListenState={!saveFormDialog}
					/>
				</div>
			</div>
			<MyPopconfirm
				title={popperTitle}
				anchorEl={anchorEl}
				onCancel={handleCancel}
				onConfirm={handleConfirm}
			/>
			{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}
				/>
			)}
		</div>
	);
});

export default WorkFlowEdit;
