import MyInput from "@/components/mui/MyInput";
import MyDialog from "@/components/mui/MyDialog";
import RadioGroupOfButtonStyle from "@/components/CommonComponents/RadioGroupOfButtonStyle";
import style from "./index.module.css";
import MyTable from "@/components/mui/MyTableNew";
import MyMenu from "@/components/mui/MyMenu";
import cloneDeep from "lodash/cloneDeep";
import { useMessage } from "@/components/MySnackbar";
import { useEffect, useMemo, useState } from "react";

export type IQueueLi = {
	name: string;
	picUrl: string;
	cpuName: string;
	gpuName: string;
	gpuNum: number; // 卡数
	coreNum: number;
	memory: number;
	total: number;
	id: string;
};

type IQueueSelectProps = {
	value: string;
	onChange: any;
	originalCpuList: Array<IQueueLi>;
	originalGpuList: Array<IQueueLi>;
	error?: boolean;
	helperText?: string;
	disabled?: boolean;
};

type IMemoryLi = {
	memory: number;
	total: number;
	id: string;
};

export type IShowCPULi = {
	name: string;
	picUrl: string;
	cpuName: string;
	coreNum: number;
	id: string;
	memoryList: Array<IMemoryLi>;
};

const queueTypes = [
	{
		label: "CPU",
		value: "CPU",
	},
	{
		label: "GPU",
		value: "GPU",
	},
];

const QueueSelect = (props: IQueueSelectProps) => {
	const {
		value,
		onChange,
		originalCpuList,
		originalGpuList,
		error,
		helperText,
		disabled,
	} = props;
	const Message = useMessage();
	const [activeId, setActiveId] = useState("");
	const [open, setOpen] = useState(false);
	const [queueType, setQueueType] = useState("CPU");
	const [showCpuList, setShowCpuList] = useState<Array<IShowCPULi>>([]);
	const handleOpen = () => {
		// setActiveId("");
		setOpen(true);
	};

	// 队列id和前端展示的队列信息的映射关系
	const idInfoMap = useMemo(() => {
		return [
			...originalCpuList.map((item) => ({
				id: item.id,
				title: `${item.name}/${item.coreNum}核${item.coreNum * item.memory}G/${
					item.coreNum
				}总核心数`,
				total: item.total,
			})),
			...originalGpuList.map((item) => ({
				id: item.id,
				title: `${item.name}/${item.gpuNum}卡${item.coreNum}核${item.memory}G/${item.gpuNum}总卡数`,
				total: item.total,
			})),
		];
	}, [originalCpuList, originalGpuList]);

	useEffect(() => {
		let resultList: Array<IShowCPULi> = [];
		originalCpuList.forEach((item) => {
			const targetIndex = resultList.findIndex((resultLi) => {
				return resultLi.name === item.name;
			});
			if (targetIndex === -1) {
				resultList.push({
					name: item.name,
					picUrl: item.picUrl,
					cpuName: item.cpuName,
					coreNum: item.coreNum,
					id: item.id,
					memoryList: [
						{
							memory: item.memory,
							total: item.total,
							id: item.id,
						},
					],
				});
			} else {
				resultList[targetIndex].memoryList.push({
					memory: item.memory,
					total: item.total,
					id: item.id,
				});
			}
		});
		setShowCpuList(resultList);
	}, [originalCpuList]);

	const cpuHeadCells = [
		{
			id: "type",
			label: "类型",
			width: 510,
		},
		{
			id: "coreNumRender",
			label: "节点核数",
			width: 180,
		},
		{
			id: "memoryRender",
			label: "设置内存配比",
			width: 150,
		},
	];

	const gpuHeadCells = [
		{
			id: "type",
			label: "类型",
			width: 510,
		},
		{
			id: "gpuNumRender",
			label: "节点卡数",
			width: 100,
		},
		{
			id: "coreNumRender",
			label: "节点核数",
			width: 100,
		},
		{
			id: "gpuMemoryRender",
			label: "节点内存容量",
			width: 100,
		},
	];

	const renderType = (item: IShowCPULi) => {
		return (
			<div className={style.cpuType}>
				<img className={style.cpuIcon} src={item.picUrl} alt="" />
				<div className={style.cpuInfo}>
					<div className={style.cpuName}>{item.name}</div>
					<div className={style.cpuDetailsName}>{item.cpuName}</div>
				</div>
			</div>
		);
	};

	const renderCoreNum = (item: IShowCPULi) => {
		return item.coreNum + "核";
	};

	const renderGpuNum = (item: IQueueLi) => {
		return item.gpuNum + "卡";
	};

	const renderGpuMemory = (item: IQueueLi) => {
		return item.memory + "GB";
	};

	const setMemory = (id: string) => {
		const copyShowCpuList: Array<IShowCPULi> = cloneDeep(showCpuList);
		const selectIndex = copyShowCpuList.findIndex((item) => {
			return item.id === activeId;
		});
		if (selectIndex !== -1) {
			copyShowCpuList[selectIndex].id = id;
		}
		// 防止被 handleRow 中的 setActiveId覆盖
		setTimeout(() => {
			setActiveId(id);
		}, 10);
		setShowCpuList(copyShowCpuList);
	};

	const renderMemory = (item: IShowCPULi) => {
		return (
			<MyMenu
				value={item.id}
				options={item.memoryList.map((memoryLi) => ({
					label: `${memoryLi.memory}GB/核`,
					value: memoryLi.id,
				}))}
				hasTriangle={true}
				setValue={setMemory}
			>
				<span className={style.cpuMemory}>
					{
						item.memoryList.filter((memoryLi) => memoryLi.id === item.id)[0]
							.memory
					}
					GB/核
				</span>
			</MyMenu>
		);
	};

	const handleRow = (e: any) => {
		setActiveId(e.id);
	};

	const handleConfirm = () => {
		if (activeId) {
			onChange && onChange(activeId);
			setOpen(false);
		} else {
			Message.error("请先选择一个硬件队列。");
		}
	};

	const getTotal = () => {
		let total = 0;
		idInfoMap.forEach((item) => {
			if (item.id === activeId) {
				total = item.total;
			}
		});
		return total;
	};

	const getTitle = () => {
		let title = "";
		idInfoMap.forEach((item) => {
			if (item.id === value) {
				title = item.title;
			}
		});
		return title;
	};

	return (
		<>
			<MyInput
				placeholder="请选择硬件队列"
				value={getTitle()}
				onClick={() => handleOpen()}
				error={error}
				helperText={helperText}
				disabled={disabled}
			></MyInput>
			{open && (
				<MyDialog
					open={open}
					title="选择硬件队列"
					onClose={() => setOpen(false)}
					onConfirm={() => handleConfirm()}
					leftSideOfButtonContent={
						<div className={style.totalBox}>
							费用（每小时）：
							<span className={style.total}>
								￥{activeId ? getTotal() : "-"}
							</span>
						</div>
					}
				>
					<div className={style.queueSelectContentBox}>
						<RadioGroupOfButtonStyle
							value={queueType}
							radioOptions={queueTypes}
							handleRadio={(e: string) => setQueueType(e)}
							RadiosBoxStyle={{ width: "140px" }}
						></RadioGroupOfButtonStyle>

						<div className={style.table}>
							{queueType === "CPU" && (
								<MyTable
									rows={showCpuList.map((item) => ({
										...item,
										type: renderType(item),
										coreNumRender: renderCoreNum(item),
										memoryRender: renderMemory(item),
									}))}
									headCells={cpuHeadCells}
									fixedHead={true}
									handleRow={(e: any) => handleRow(e)}
									activeId={activeId}
								></MyTable>
							)}
							{queueType === "GPU" && (
								<MyTable
									rows={originalGpuList.map((item: any) => ({
										...item,
										type: renderType(item),
										gpuNumRender: renderGpuNum(item),
										coreNumRender: renderCoreNum(item),
										gpuMemoryRender: renderGpuMemory(item),
									}))}
									headCells={gpuHeadCells}
									fixedHead={true}
									handleRow={(e: any) => handleRow(e)}
									activeId={activeId}
								></MyTable>
							)}
						</div>
					</div>
				</MyDialog>
			)}
		</>
	);
};

export default QueueSelect;
