import { useEffect, useState, useMemo, useCallback } from "react";
import style from "./index.module.css";
import classNames from "classnames";
import CloseOutlinedIcon from "@mui/icons-material/CloseOutlined";
import { Box, Typography } from "@mui/material";
import RadioGroupOfButtonStyle from "@/components/CommonComponents/RadioGroupOfButtonStyle";
import SearchIcon from "@mui/icons-material/Search";
import Button from "@/components/mui/MyButton";
import OutlinedInput from "@mui/material/OutlinedInput";
import Checkbox from "@mui/material/Checkbox";
import useMyRequest from "@/hooks/useMyRequest";
import AddIcon from "@mui/icons-material/Add";
import { useStores } from "@/store";
import WorkFlowEdit from "@/views/WorkFlowEdit";
import _ from "lodash";
import { observer } from "mobx-react-lite";
import noData from "../../../../../../assets/project/noTemplate.svg";
import { ICustomTemplate } from "../../interface";
import { useMessage } from "@/components/MySnackbar";
import {
	getAddWorkbenchTemplate,
	addWorkbenchTemplate,
} from "@/api/workbench_api";
import { toJS } from "mobx";

type IAddTemplateProps = {
	setShowAddTemplate: any;
	getTemplateInfo: any;
};

const radioOptions = [
	{
		value: "public",
		label: "公共",
	},
	{
		value: "custom",
		label: "自定义",
	},
];

const AddTemplate = observer((props: IAddTemplateProps) => {
	const { currentProjectStore } = useStores();
	const Message = useMessage();
	const projectId = toJS(currentProjectStore.currentProjectInfo.id);
	const productId = toJS(currentProjectStore.currentProductInfo.id);
	const { setShowAddTemplate, getTemplateInfo } = props;
	const [title, setTitle] = useState("");

	/** 可增加模板列表 */
	const [addTemplateList, setAddTemplateList] = useState([]);

	/** 已选择增加的模板列表 */
	const [selectTemplateData, setSelectTemplateData] = useState<string[]>([]);

	const [templateType, setTemplateType] = useState("public");

	const handleRadio = (value: string) => {
		setTemplateType(value);
	};

	const handleSelectTemplate = (id: string) => {
		let list: string[] = [...selectTemplateData];
		if (selectTemplateData.filter((e) => e === id).length > 0) {
			list = list.filter((e) => e !== id);
			setSelectTemplateData(list);
		} else {
			list.push(id);
			setSelectTemplateData(list);
		}
	};

	// 项目管理员-添加工作流模板-提交
	const { run: addTemplate } = useMyRequest(addWorkbenchTemplate, {
		onSuccess: (result: any) => {
			Message.success("添加成功");
			setSelectTemplateData([]);
			setShowAddTemplate(false);
			getTemplateInfo({
				projectId: projectId as string,
			});
		},
	});

	const handleAddTemplate = () => {
		if (selectTemplateData.length === 0) {
			Message.error("请选择要添加的模板");
		} else {
			addTemplate({
				projectId: projectId as string,
				workflowSpecIds: selectTemplateData,
			});
		}
	};

	// 添加工作流模板-获取模板列表
	const { run: getAddTemplateList } = useMyRequest(getAddWorkbenchTemplate, {
		onSuccess: (result: any) => {
			setAddTemplateList(result.data);
			// setOpenAddTemplate(true);
		},
	});

	/** 是否显示自定义模版编辑并带有参数 */
	const [customTemplateInfo, setCustomTemplateInfo] = useState<ICustomTemplate>(
		{
			show: false,
		}
	);

	// 显示新增、编辑自定义模板弹窗
	const handleAddCustomTemplate = () => {
		setCustomTemplateInfo({
			show: true,
		});
	};

	// 编辑模板
	const handleEditTemplate = (item: any) => {
		setCustomTemplateInfo({
			show: true,
			id: item.id,
		});
	};

	// 获取模板列表
	const getAddTemplateListFun = useCallback(() => {
		const userName = JSON.parse(localStorage.getItem("userInfo") || "{}")?.name;
		setSelectTemplateData([]);
		setAddTemplateList([]);
		if (templateType === "public") {
			getAddTemplateList({
				projectId: projectId as string,
				productId: productId as string,
				creator: "root",
				keyword: title,
			});
		} else {
			getAddTemplateList({
				projectId: projectId as string,
				productId: productId as string,
				creator: userName,
				keyword: title,
			});
		}
	}, [
		setSelectTemplateData,
		getAddTemplateList,
		productId,
		projectId,
		templateType,
		title,
	]);
	// title,

	useEffect(() => {
		getAddTemplateListFun();
	}, [getAddTemplateListFun]);

	const hiddenBoxArr = useMemo(() => {
		const length =
			templateType === "public"
				? addTemplateList.length
				: addTemplateList.length + 1;
		const hiddenBoxNumber = 4 - (length % 4);
		const arr = new Array(hiddenBoxNumber).fill("");
		return arr;
	}, [addTemplateList, templateType]);

	return (
		<div className={style.addTemplateBox}>
			<div className={style.closeBox}>
				<CloseOutlinedIcon
					sx={{ color: "#ffffff", marginRight: "10px", cursor: "pointer" }}
					onClick={() => {
						setShowAddTemplate(false);
					}}
				/>
			</div>
			<div className={style.content}>
				<Typography
					sx={{ fontSize: "18px", fontWeight: "600", color: "#1E2633" }}
				>
					添加工作流模版
				</Typography>
				<Box
					sx={{
						display: "flex",
						justifyContent: "space-between",
						alignItems: "center",
						marginBottom: "20px",
					}}
				>
					<OutlinedInput
						value={title}
						onChange={(e: any) => {
							setTitle(e.target.value);
						}}
						placeholder="输入关键词搜索"
						size="small"
						sx={{ width: 340, height: 32, marginTop: "20px" }}
						endAdornment={<SearchIcon style={{ color: "#8A9099" }} />}
					/>
					<Box
						sx={{
							display: "flex",
							justifyContent: "flex-end",
							alignItems: "center",
						}}
					>
						<RadioGroupOfButtonStyle
							value={templateType}
							radioOptions={radioOptions}
							handleRadio={handleRadio}
						></RadioGroupOfButtonStyle>
						<Button
							onClick={handleAddTemplate}
							size={"small"}
							style={{
								marginLeft: "12px",
							}}
							text={
								"添加模版" +
								(selectTemplateData.length === 0
									? ""
									: `(${selectTemplateData.length})`)
							}
						/>
					</Box>
				</Box>
				{templateType === "public" && addTemplateList.length === 0 && (
					<Box
						sx={{
							display: "flex",
							alignItems: "center",
							flexDirection: "column",
							minHeight: "calc(100vh - 376px)",
							justifyContent: "center",
						}}
					>
						<img alt="" src={noData} />
						<Typography
							sx={{ fontSize: "12px", fontWeight: "400", color: "#8A9099" }}
						>
							暂无相关模版
						</Typography>
					</Box>
				)}
				<div className={style.templateList}>
					{templateType !== "public" && (
						<div
							className={classNames({
								[style.templateLi]: true,
								[style.addCustomTemplate]: true,
							})}
							onClick={handleAddCustomTemplate}
						>
							<AddIcon />
							<span className={style.addCustomTemplateText}>
								创建自定义模板
							</span>
						</div>
					)}
					{addTemplateList.map((item: any, index) => {
						return (
							<div
								className={classNames({
									[style.templateLi]: true,
									[style.templateLiCustom]: templateType !== "public",
								})}
								key={index}
								onClick={() => {
									handleSelectTemplate(item.id);
								}}
							>
								<div className={style.templateLiTop}>
									<span className={style.templateTitle}>{item.title}</span>
									<Checkbox
										size="small"
										sx={{ padding: "0px" }}
										checked={selectTemplateData.includes(item.id)}
									/>
								</div>
								<div className={style.templateLiInfo}>
									<span
										className={style.templateLiInfoText}
										style={{ marginRight: "24px" }}
									>
										版本：{item.version}
									</span>
									<span className={style.templateLiInfoText}>
										更新时间：{item.updatedTime}
									</span>
								</div>
								<div className={style.templateLiDesc}>{item.description}</div>
								{templateType !== "public" && (
									<div className={style.templateLiEditBox}>
										<Button
											onClick={() => handleEditTemplate(item)}
											size={"small"}
											style={{
												height: "32px",
											}}
											color="inherit"
											text="编辑模板"
										/>
									</div>
								)}
							</div>
						);
					})}

					{hiddenBoxArr.length !== 4 &&
						hiddenBoxArr.map((item, index) => {
							return (
								<div
									key={`-${index}`}
									className={classNames({
										[style.templateLi]: true,
										[style.templateLiHidden]: true,
									})}
								/>
							);
						})}
				</div>
			</div>
			{customTemplateInfo?.show ? (
				<WorkFlowEdit
					id={customTemplateInfo.id || ""}
					onBack={() => {
						setCustomTemplateInfo({
							id: "",
							show: false,
						});
						getAddTemplateListFun();
					}}
				/>
			) : null}
		</div>
	);
});

export default AddTemplate;
