/*
 * @Author: 吴永生#A02208 yongsheng.wu@wholion.com
 * @Date: 2022-05-31 10:18:13
 * @LastEditors: 吴永生 15770852798@163.com
 * @LastEditTime: 2022-09-01 10:49:46
 * @FilePath: /bkunyun/src/views/Project/ProjectSetting/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { memo, useEffect, useState } from "react";
import { Box, Typography } from "@mui/material";
import { toJS } from "mobx";
import { observer } from "mobx-react-lite";
import FormatListBulletedRoundedIcon from "@mui/icons-material/FormatListBulletedRounded";
import { getLoaclStorageOfKey } from "@/api/fileserver/utils";

import MyButton from "@/components/mui/MyButton";
import SearchInput from "@/components/BusinessComponents/SearchInput";
import useMyRequest from "@/hooks/useMyRequest";
import TemplateBox from "./components/templateBox";
import SimpleDialog from "./components/simpleDialog";
import AddTemplate from "./components/AddTemplate/index";
import noData from "../../../../assets/project/noTemplate.svg";
import {
	getWorkbenchTemplate,
	deleteWorkbenchTemplate,
} from "@/api/workbench_api";

import { getOverviewInfo, getProject } from "@/api/project_api";
import usePass from "@/hooks/usePass";
import { useStores } from "@/store";

import styles from "./index.module.css";

const userInfo = getLoaclStorageOfKey("userInfo");

const ProjectMembers = observer(() => {
	const { currentProjectStore } = useStores();
	const projectIdData = toJS(currentProjectStore.currentProjectInfo.id);
	const productId = toJS(currentProjectStore.currentProductInfo.id);
	const isPass = usePass();

	/** 搜索模板名称 */
	const [templateName, setTemplateName] = useState("");
	/** 模板列表 */
	const [templateList, setTemplateList] = useState([]);
	/** 选中的模板id */
	const [templateId, setTemplateId] = useState("");
	/** 简单弹窗（删除模板） */
	const [openDialog, setOpenDialog] = useState(false);
	const [showAddTemplate, setShowAddTemplate] = useState(false);

	// 获取模板列表
	const { run: getTemplateInfo } = useMyRequest(getWorkbenchTemplate, {
		onSuccess: (result: any) => {
			setTemplateList(result.data);
		},
	});

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

	useEffect(() => {
		getTemplateInfo({
			projectId: currentProjectStore.currentProjectInfo.id as string,
		});
	}, [currentProjectStore.currentProjectInfo.id, getTemplateInfo]);

	/** 删除模板 */
	const deleteTemplate = () => {
		delTemplate({
			projectId: currentProjectStore.currentProjectInfo.id as string,
			workflowSpecId: templateId,
		});
	};

	/** 打开弹窗 */
	const startDialog = (id: string) => {
		setTemplateId(id);
		setOpenDialog(true);
	};

	/** 关闭弹窗 */
	const closeDialog = () => {
		setOpenDialog(false);
	};

	/** 增加模板 */
	const addTemplateBlock = () => {
		setShowAddTemplate(true);
	};

	useEffect(() => {
		setTimeout(() => {
			getTemplateInfo({
				projectId: projectIdData as string,
				title: templateName,
			});
		}, 300);
	}, [templateName, getTemplateInfo, projectIdData]);

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

	// 项目剩余预算是否大于100 Greater than 100
	const [greaterThan100, setGreaterThan100] = useState(false);

	// 获取概览基本信息  用于获取项目剩余预算 projectRemainingBudget
	const { run: getOverview } = useMyRequest(getOverviewInfo, {
		onSuccess: (result: any) => {
			if (result.data.projectRemainingBudget >= 100) {
				setGreaterThan100(true);
			} else {
				setGreaterThan100(false);
			}
		},
	});

	useEffect(() => {
		if (currentProjectStore.currentProjectInfo.id) {
			getOverview({
				id: currentProjectStore.currentProjectInfo.id as string,
			});
		}
	}, [currentProjectStore.currentProjectInfo.id, getOverview]);

	// 用户是否为父用户
	const [isParentUser] = useState(!userInfo.parent ? true : false);

	// 当前用户是否为项目的所有者
	const [isOwner, setIsOwner] = useState(false);
	const { run: getProjectFn } = useMyRequest(getProject, {
		onSuccess: (result: any) => {
			if (result.data.projectRole === "OWNER") {
				setIsOwner(true);
			} else {
				setIsOwner(false);
			}
		},
	});

	useEffect(() => {
		getProjectFn({
			id: currentProjectStore.currentProjectInfo.id as string,
		});
	}, [currentProjectStore.currentProjectInfo.id, getProjectFn]);

	return (
		<Box className={styles.headerBox}>
			<Box className={styles.tabBox}>
				<SearchInput onKeyUp={handleKeyWordChangeKeyUp} sx={{ width: 340 }} />
				{isPass("PROJECT_WORKBENCH_FLOES_ADD", "MANAGER") && (
					<MyButton
						text={"管理工作流模板"}
						startIcon={<FormatListBulletedRoundedIcon fontSize="small" />}
						onClick={addTemplateBlock}
						size={"medium"}
					/>
				)}
			</Box>

			{templateList.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" }}
					>
						{templateName ? "暂未相应搜索结果" : "暂未开启模版"}
					</Typography>
				</Box>
			)}
			{templateList.length > 0 && (
				<Box className={styles.templateBox}>
					{templateList &&
						templateList.length > 0 &&
						templateList.map((item, key) => {
							return (
								<TemplateBox
									key={key}
									data={item}
									startDialog={startDialog}
									isParentUser={isParentUser}
									isOwner={isOwner}
									greaterThan100={greaterThan100}
								/>
							);
						})}
				</Box>
			)}

			{showAddTemplate && (
				<AddTemplate
					setShowAddTemplate={() => {
						setShowAddTemplate(false);
						getTemplateInfo({
							projectId: projectIdData as string,
							title: templateName,
						});
					}}
					getTemplateInfo={getTemplateInfo}
					productId={productId as string}
					projectId={projectIdData as string}
				/>
			)}

			<SimpleDialog
				text={"确认移除该模板吗？"}
				title={"删除模板"}
				openDialog={openDialog}
				closeDialog={closeDialog}
				onConfirm={deleteTemplate}
			/>
		</Box>
	);
});

export default memo(ProjectMembers);
