/*
 * @Author: 吴永生#A02208 yongsheng.wu@wholion.com
 * @Date: 2022-05-31 10:18:13
 * @LastEditors: 吴永生 15770852798@163.com
 * @LastEditTime: 2022-07-28 19:02:19
 * @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, useCallback, useEffect, useState } from "react";
import _ from "lodash";
import { useNavigate } from "react-router-dom";
import { Box, Typography } from "@mui/material";
import OutlinedInput from "@mui/material/OutlinedInput";
import { TablePagination } from "@mui/material";

import MySelect from "@/components/mui/MySelect";
import SimpleDialog from "./components/simpleDialog";
import { useStores } from "@/store";
import useMyRequest from "@/hooks/useMyRequest";
import ActionsComponent from "../../../../components/Material.Ui/Table/ActionsComponent";
import runTime from "../../../../assets/project/runTime.svg";
import jobCost from "../../../../assets/project/jobCost.svg";
import jobSue from "../../../../assets/project/jobSue.svg";
import jobFail from "../../../../assets/project/jobFail.svg";
import jobRun from "../../../../assets/project/jobRun.svg";
import jobCadence from "../../../../assets/project/jobCadence.svg";
import jobStop from "../../../../assets/project/jobStop.svg";
import jobDel from "../../../../assets/project/jobDel.svg";
import noData from "../../../../assets/project/noTemplate.svg";
import onload from "../../../../assets/project/onload.svg";
import {
	getWorkflowJobList,
	deleteWorkflowJob,
	cancelWorkflowJob,
} from "@/api/workbench_api";
import { toJS } from "mobx";
import { observer } from "mobx-react-lite";
import usePass from "@/hooks/usePass";
import MyProgress from "@/components/mui/MyProgress";
import SearchInput from "@/components/BusinessComponents/SearchInput";
import MyCircularProgress from "@/components/mui/MyCircularProgress";
import moment from "moment";

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

const currencies = [
	{
		value: "ALL",
		label: "全部",
	},
	{
		value: "RUNNING",
		label: "正在运行",
	},
	{
		value: "SUCCEEDED",
		label: "运行成功",
	},
	{
		value: "FAILED",
		label: "运行失败",
	},
	{
		value: "ABORTED",
		label: "运行终止",
	},
];

let timer: string | number | NodeJS.Timeout | null | undefined = null;
const ProjectMembers = observer(() => {
	const { currentProjectStore } = useStores();

	const projectId = toJS(currentProjectStore.currentProjectInfo.id);
	const isPass = usePass();
	const [jobName, setJobName] = useState("");
	const [jobList, setJobList] = useState([]);
	const [currency, setCurrency] = useState("ALL");
	const [page, setPage] = useState(0);
	const [size, setSize] = useState(10);
	const [rowsPerPage, setRowsPerPage] = useState(10);
	const [count, setCount] = useState(0);
	const [loading, setLoading] = useState(false)
	/** 简单弹窗 */
	const [jobData, setJobData] = useState("");
	const [openDialog, setOpenDialog] = useState(false);
	const [dialogType, setDialogType] = useState("del");
	// 获取作业列表
	const { run: getWorkflowJobInfo } = useMyRequest(getWorkflowJobList, {
		onSuccess: (result: any) => {
			setJobList(result.data.content);
			setCount(result.data.totalElements);
			setLoading(false);
			timer && clearTimeout(timer as number);
			timer = null;
			timer = setTimeout(() => {
				getWorkflowJobInfo({
					projectId: currentProjectStore.currentProjectInfo.id as string,
					page: page,
					size: size,
					name: jobName,
					state: currency === "ALL" ? "" : currency,
				});
			}, 60000);
		},
	});

	useEffect(() => {
		return () => {
			clearTimeout(timer as number);
		};
	}, []);

	const navigate = useNavigate();

	// 删除作业
	const { run: delWorkflowJob } = useMyRequest(deleteWorkflowJob, {
		onSuccess: (result: any) => {
			setOpenDialog(false);
			getWorkflowJobInfo({
				projectId: currentProjectStore.currentProjectInfo.id as string,
				page: page,
				size: size,
				name: jobName,
				state: currency === "ALL" ? "" : currency,
			});
		},
	});

	// 中止作业
	const { run: cancelWorkflowJobInfo } = useMyRequest(cancelWorkflowJob, {
		onSuccess: (result: any) => {
			setOpenDialog(false);
			getWorkflowJobInfo({
				projectId: currentProjectStore.currentProjectInfo.id as string,
				page: page,
				size: size,
				name: jobName,
				state: currency === "ALL" ? "" : currency,
			});
		},
	});

	const handleChange = (val: string) => {
		setCurrency(val);
	};

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

	/** 弹窗确认 */
	const onConfirm = () => {
		if (dialogType === "del") {
			delWorkflowJob({
				id: jobData,
			});
		} else {
			cancelWorkflowJobInfo({
				jobid: jobData,
			});
		}
	};

	useEffect(() => {
		getWorkflowJobInfo({
			projectId: currentProjectStore.currentProjectInfo.id as string,
			page: page,
			size: size,
			name: jobName,
			state: currency === "ALL" ? "" : currency,
		});
	}, [projectId, getWorkflowJobInfo]);

	const handleChangePage = (event: any, newPage: any) => {
		setPage(newPage);
		getWorkflowJobInfo({
			projectId: currentProjectStore.currentProjectInfo.id as string,
			page: newPage,
			size: size,
			name: jobName,
			state: currency === "ALL" ? "" : currency,
		});
	};

	const handleChangeRowsPerPage = (event: any) => {
		setRowsPerPage(event.target.value);
		setSize(event.target.value);
		getWorkflowJobInfo({
			projectId: currentProjectStore.currentProjectInfo.id as string,
			page: page,
			size: event.target.value,
			name: jobName,
			state: currency === "ALL" ? "" : currency,
		});
	};

	useEffect(() => {
		setTimeout(() => {
			getWorkflowJobInfo({
				projectId: currentProjectStore.currentProjectInfo.id as string,
				page: page,
				size: size,
				name: jobName,
				state: currency === "ALL" ? "" : currency,
			});
		}, 300);
	}, [jobName, currency]);

	const renderStatusIcon = (data: string) => {
		switch (data) {
			case "SUBMITTED":
				return jobRun;
			case "RUNNING":
				return jobRun;
			case "ABORTED":
				return jobCadence;
			case "FAILED":
				return jobFail;
			case "SUCCEEDED":
				return jobSue;
			default:
				return jobCadence;
		}
	};

	const renderStatusText = (data: string) => {
		switch (data) {
			case "SUBMITTED":
				return "正在启动";
			case "RUNNING":
				return "正在运行";
			case "ABORTED":
				return "运行终止";
			case "FAILED":
				return "运行失败";
			case "SUCCEEDED":
				return "运行成功";
			default:
				return "未知";
		}
	};

	/** 渲染字体颜色 */
	const renderTextColor = (data: any) => {
		switch (data) {
			case "SUBMITTED":
				return "#1370FF";
			case "RUNNING":
				return "#1370FF";
			case "ABORTED":
				return "#C2C6CC";
			case "FAILED":
				return "#FF4E4E";
			case "SUCCEEDED":
				return "#0DD09B";
			default:
				return "#C2C6CC";
		}
	};

	/** 渲染进度条颜色 */
	const renderProgressColor = useCallback((data: any) => {
		switch (data) {
			case "SUBMITTED":
				return "info";
			case "RUNNING":
				return "info";
			case "ABORTED":
				return "disable";
			case "FAILED":
				return "error";
			case "SUCCEEDED":
				return "success";
			default:
				return "disable";
		}
	}, []);

	/** 点击每一行 */
	const rowClick = useCallback(
		(id: string) => {
			navigate(`/product/cadd/projectJobDetail`, {
				state: { taskId: id, from: 'workbenchList' },
			});
		},
		[navigate]
	);

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

	return (
		<Box className={styles.headerBox}>
			<Box className={styles.tabHeader}>
				<Box sx={{ display: "flex" }}>
					<SearchInput onKeyUp={handleKeyWordChangeKeyUp} sx={{ width: 340 }} />
					{/* <Box className={styles.tabHeaderSelect}>
                        <TextField
                            select
                            label="运行状态"
                            value={currency}
                            onChange={handleChange}
                            size="small"
                            sx={{
                                width: 180, height: 32,
                                '& .MuiOutlinedInput-root': {
                                    height: '32px',
                                    color: "#1E2633",
                                    fontSize: '14px'
                                },
                                '& .MuiInputLabel-root': {
                                    color: "#8A9099",
                                    fontSize: '14px'
                                },
                            }}
                        >
                            {currencies.map((option) => (
                                    {option.label}
                            ))}
                        </TextField>
                    </Box> */}

					<Box className={styles.tabHeaderSelect}>
						<MySelect
							input={<OutlinedInput />}
							value={currency}
							onChange={handleChange}
							options={currencies}
							size="small"
							sx={{
								width: 180,
								height: 32,
								"& .MuiOutlinedInput-root": {
									height: "32px",
									color: "#1E2633",
									fontSize: "14px",
								},
								"& .MuiInputLabel-root": {
									color: "#8A9099",
									fontSize: "14px",
								},
							}}
						/>
					</Box>
				</Box>

				<Box
					className={styles.tabUpdate}
					onClick={() => {
						getWorkflowJobInfo({
							projectId: currentProjectStore.currentProjectInfo.id as string,
							page: page,
							size: size,
							name: jobName,
							state: currency === "ALL" ? "" : currency,
						});
						setLoading(true)
					}}
				>
					<img alt="" src={onload} />
				</Box>
			</Box>

			<Box className={styles.body} style={{ position: "relative" }}>
				<MyCircularProgress loading={loading} />
				{jobList.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>
				)}
				{jobList.length > 0 &&
					jobList.map((item: any, key) => {
						return (
							<Box className={styles.tabBox} onClick={() => rowClick(item.id)}>
								<Box className={styles.tabBoxInfo}>
									<div className={styles.tabBoxTitle}>{item.name}</div>
									<Box className={styles.tabBoxDescInfo}>
										<div
											className={styles.tabBoxDesc}
											style={{ marginRight: "24px" }}
										>
											创建时间：{moment(item.createTime).format("YYYY-MM-DD")}
										</div>
										<div className={styles.tabBoxDesc}>
											创建人：{item.creator}
										</div>
									</Box>
								</Box>
								<Box className={styles.tabBoxMiddle}>
									<img alt="" src={runTime} />
									<div className={styles.tabBoxTime}>{item.costTime}</div>
								</Box>
								<Box className={styles.tabBoxMiddle}>
									<img alt="" src={jobCost} />
									<div className={styles.tabBoxTime}>{item.jobCost.toFixed(2)}元</div>
								</Box>
								<Box className={styles.tabBoxJobStatus}>
									<img alt="" src={renderStatusIcon(item.state)} />
									<div className={styles.tabBoxStatusText}>
										{renderStatusText(item.state)}
									</div>
									<Box sx={{ width: "100%" }}>
										<MyProgress
											color={renderProgressColor(item.state)}
											value={(item.completeNum / item.totalNum) * 100}
											sx={{
												marginRight: "16px",
											}}
										/>
									</Box>
									<div
										style={{ color: renderTextColor(item.state), margin: '0px' }}
										className={styles.tabBoxStatusText}
									>
										{item.completeNum + "/" + item.totalNum}
									</div>
								</Box>

								{item.state === "RUNNING" &&
									isPass("PROJECT_WORKBENCH_JOBS_STOP", "USER") && (
										<Box className={styles.tabBoxJobOperate}>
											{
												currentProjectStore.currentProjectInfo.projectRole === "USER" && (item.creator !== JSON.parse(localStorage.getItem("userInfo") || "{}")?.name) ? "" : <img
													alt=""
													src={jobStop}
													style={{ cursor: "pointer" }}
													onClick={(event) => {
														event.stopPropagation();
														event.nativeEvent.stopImmediatePropagation();
														setJobData(item.id);
														setOpenDialog(true);
														setDialogType("stop");
													}}
												/>
											}
										</Box>
									)}
								{item.state !== "RUNNING" &&
									isPass("PROJECT_WORKBENCH_JOBS_DELETE", "MANAGER") && (
										<Box className={styles.tabBoxJobOperate}>
											<img
												alt=""
												src={jobDel}
												style={{ cursor: "pointer" }}
												onClick={(event) => {
													event.stopPropagation();
													event.nativeEvent.stopImmediatePropagation();
													setJobData(item.id);
													setOpenDialog(true);
													setDialogType("del");
												}}
											/>
										</Box>
									)}
							</Box>
						);
					})}
			</Box>

			<TablePagination
				rowsPerPageOptions={[5, 10, 20, 50]}
				labelRowsPerPage={"每页行数："}
				ActionsComponent={ActionsComponent}
				component="div"
				count={count || jobList.length}
				rowsPerPage={rowsPerPage || 10}
				page={page}
				onPageChange={handleChangePage} //
				onRowsPerPageChange={handleChangeRowsPerPage} //
			/>

			<SimpleDialog
				text={
					dialogType === "del"
						? "任务被删除后将无法恢复，确认继续吗？"
						: "正在运行的任务终止后将无法重新运行，确认继续吗？"
				}
				title={dialogType === "del" ? "删除任务" : "终止任务"}
				openDialog={openDialog}
				closeDialog={closeDialog}
				onConfirm={onConfirm}
			/>
		</Box>
	);
});

export default memo(ProjectMembers);
