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 TemplateItem from "@/views/ResourceCenter/UserResources/UserResourcesTemplate/TemplateItem";
import CardTable from "@/components/CommonComponents/CardTable";
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);
		}
	};

	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}
							/>
						</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>
					)}
					<CardTable
						data={addTemplateList}
						renderBefore={() => {
							if (templateType !== "public") {
								return (
									<div
										className={classNames({
											[style.addTemplate]: true,
										})}
										onClick={handleAddCustomTemplate}
									>
										<AddIcon />
										<span className={style.addCustomTemplateText}>
											创建自定义模板
										</span>
									</div>
								);
							}
							return null;
						}}
						renderItem={(item: any) => {
							return (
								<TemplateItem
									templateInfo={item}
									footer={() => {
										return (
											<div className={style.templateLiEditBox}>
												<MySwitch
													defaultChecked={item.favorited}
													onChange={(e: any) => templateSwitch(e, item.id)}
												></MySwitch>
											</div>
										);
									}}
								></TemplateItem>
							);
						}}
						itemMinWidth={377}
					></CardTable>
				</div>
			</div>
			{customTemplateInfo?.show ? (
				<WorkFlowEdit
					id={customTemplateInfo.id || ""}
					onBack={() => {
						setCustomTemplateInfo({
							id: "",
							show: false,
						});
						getAddTemplateListFun();
					}}
				/>
			) : null}
		</FullScreenDrawer>
	);
};

export default AddTemplate;
