import { useEffect, useState, useMemo, useCallback } from "react";
import style from "./index.module.css";
import classNames from "classnames";
import { Box, Typography } from "@mui/material";
import RadioGroupOfButtonStyle from "@/components/CommonComponents/RadioGroupOfButtonStyle";
import SearchIcon from "@mui/icons-material/Search";
import OutlinedInput from "@mui/material/OutlinedInput";
import MySwitch from "@/components/mui/MySwitch";
import FullScreenDrawer from "@/components/CommonComponents/FullScreenDrawer";
import useMyRequest from "@/hooks/useMyRequest";
import AddIcon from "@mui/icons-material/Add";
import WorkFlowEdit from "@/views/WorkFlowEdit";
import noData from "../../../../../../assets/project/noTemplate.svg";
import { ICustomTemplate } from "../../interface";
import { useMessage } from "@/components/MySnackbar";
import {
	getAddWorkbenchTemplate,
	addWorkbenchTemplate,
	deleteWorkbenchTemplate,
} from "@/api/workbench_api";

type IAddTemplateProps = {
	setShowAddTemplate: any;
	getTemplateInfo: any;
	projectId: string;
	productId: string;
};

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

const AddTemplate = (props: IAddTemplateProps) => {
	const Message = useMessage();
	const { setShowAddTemplate, getTemplateInfo, projectId, productId } = props;
	const [title, setTitle] = useState("");

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

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

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

	// 滚轮是否到顶,判断是否显示阴影
	const [isTop, setIsTop] = useState(true);

	// 滚动滚轮时监听是否到顶
	const onscroll = (e: any) => {
		if (e.target.scrollTop <= 0) {
			setIsTop(true);
		} else {
			setIsTop(false);
		}
	};

	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();
			// getTemplateInfo({
			// 	projectId: projectId as string,
			// });
		},
	});

	// 删除模板
	const { run: delTemplate } = useMyRequest(deleteWorkbenchTemplate, {
		onSuccess: (result: any) => {
			// setOpenDialog(false);
			// getTemplateInfo({
			// 	projectId: currentProjectStore.currentProjectInfo.id as string,
			// 	title: templateName,
			// });
		},
	});

	// 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?.content || []);
			// 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(
		(newTitle?: string) => {
			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: newTitle,
				});
			} else {
				getAddTemplateList({
					projectId: projectId as string,
					productId: productId as string,
					creator: userName,
					keyword: newTitle,
				});
			}
		},
		[
			setSelectTemplateData,
			getAddTemplateList,
			productId,
			projectId,
			templateType,
			// title,
		]
	);

	//模板启用切换
	const templateSwitch = (e: any, id: string) => {
		if (e.target.checked) {
			let arr = [];
			arr.push(id);
			addTemplate({
				projectId: projectId as string,
				workflowSpecIds: arr,
			});
		} else {
			delTemplate({
				projectId: projectId as string,
				workflowSpecId: id,
			});
		}
	};

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

	// 按回车搜索
	const handleKeyWordChangeKeyUp = (e: any) => {
		if (e.keyCode === 13) {
			getAddTemplateListFun(e.target.value);
		}
	};

	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 (
		<FullScreenDrawer handleClose={setShowAddTemplate}>
			<div className={style.content}>
				<div
					className={classNames({
						[style.headerBox]: true,
						[style.headerBoxShadow]: !isTop,
					})}
				>
					<Typography
						sx={{ fontSize: "18px", fontWeight: "600", color: "#1E2633" }}
					>
						管理工作流模板
					</Typography>
					<Box
						sx={{
							display: "flex",
							justifyContent: "space-between",
							alignItems: "center",
							paddingBottom: "20px",
							paddingTop: "20px",
						}}
					>
						<OutlinedInput
							value={title}
							onChange={(e: any) => {
								setTitle(e.target.value);
							}}
							onKeyUp={handleKeyWordChangeKeyUp}
							placeholder="输入关键词搜索"
							size="small"
							sx={{ width: 340, height: 32 }}
							endAdornment={<SearchIcon style={{ color: "#8A9099" }} />}
						/>
						<Box
							sx={{
								display: "flex",
								justifyContent: "flex-end",
								alignItems: "center",
							}}
						>
							<RadioGroupOfButtonStyle
								value={templateType}
								radioOptions={radioOptions}
								handleRadio={handleRadio}
							/>
							{/* <MyButton
							onClick={handleAddTemplate}
							size={"small"}
							style={{
								marginLeft: "12px",
							}}
							text={
								"添加模版" +
								(selectTemplateData.length === 0
									? ""
									: `(${selectTemplateData.length})`)
							}
						/> */}
						</Box>
					</Box>
				</div>
				<div className={style.templateBox} onScroll={onscroll}>
					{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>

									<div className={style.templateLiEditBox}>
										<MySwitch
											defaultChecked={item.favorited}
											onChange={(e: any) => templateSwitch(e, item.id)}
										></MySwitch>
									</div>

									{/* {templateType !== "public" && (
										<MyButton
											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>
			</div>
			{customTemplateInfo?.show ? (
				<WorkFlowEdit
					id={customTemplateInfo.id || ""}
					onBack={() => {
						setCustomTemplateInfo({
							id: "",
							show: false,
						});
						getAddTemplateListFun();
					}}
				/>
			) : null}
		</FullScreenDrawer>
	);
};

export default AddTemplate;
