/*
 * @Author: 吴永生#A02208 yongsheng.wu@wholion.com
 * @Date: 2022-05-31 10:18:13
 * @LastEditors: 吴永生 15770852798@163.com
 * @LastEditTime: 2022-12-13 14:22:05
 * @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, useCallback } 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 { useNavigate } from "react-router-dom";
import TemplateItem from "@/views/ResourceCenter/UserResources/UserResourcesTemplate/TemplateItem";
import SimpleDialog from "./components/simpleDialog";
import AddTemplate from "./components/AddTemplate/index";
import noData from "../../../../assets/project/noTemplate.svg";
import RemindBudgetDialog from "./components/RemindBudgetDialog";
import CardTable from "@/components/CommonComponents/CardTable";
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 navigate = useNavigate();
	const isPass = usePass();
	const [selectId, setSelectId] = useState("");
	const [rbOpen, setRbOpen] = useState(false);

	/** 搜索模板名称 */
	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.content);
		},
	});

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

	useEffect(() => {
		getTemplateInfo({
			page: 0,
			size: 999,
			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({
				page: 0,
				size: 999,
				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]);

	const goToProjectSubmitWork = useCallback(
		(id: string) => {
			navigate(`/product/${productId || "cadd"}/projectSubmitWork`, {
				state: { id },
			});
		},
		[navigate, productId]
	);

	const handleJudgeBudget = useCallback(
		(id: string) => {
			setSelectId(id);
			if (greaterThan100) {
				goToProjectSubmitWork(id);
			} else {
				setRbOpen(true);
			}
		},
		[goToProjectSubmitWork, setRbOpen, setSelectId, greaterThan100]
	);

	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>
			)}
			<CardTable
				data={templateList}
				renderItem={(item: any) => {
					return (
						<TemplateItem
							templateInfo={item}
							footer={() => {
								return (
									<Box
										sx={{
											display: "flex",
											justifyContent: "end",
										}}
									>
										{isPass("PROJECT_WORKBENCH_FLOES_USE", "MANAGER") && (
											<MyButton
												size="medium"
												text="移除模版"
												onClick={() => {
													startDialog(item.id);
												}}
												style={{
													backgroundColor: "#F0F2F5",
													color: "#565C66",
												}}
											/>
										)}
										{isPass("PROJECT_WORKBENCH_FLOES_USE", "USER") && (
											<MyButton
												size="medium"
												text="使用模版"
												onClick={() => handleJudgeBudget(item.id)}
												style={{ marginLeft: "12px" }}
											/>
										)}
									</Box>
								);
							}}
						></TemplateItem>
					);
				}}
				itemMinWidth={377}
			></CardTable>

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

			{rbOpen && (
				<RemindBudgetDialog
					rbOpen={rbOpen}
					rbClose={() => setRbOpen(false)}
					id={selectId}
					goToProjectSubmitWork={goToProjectSubmitWork}
					isParentUser={isParentUser}
					isOwner={isOwner}
				></RemindBudgetDialog>
			)}

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

export default memo(ProjectMembers);
