import { MenuItem } from "@mui/material";
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";

import MyInput from "@/components/mui/MyInput";
import MyDialog from "@/components/mui/MyDialog";
import useMyRequest from "@/hooks/useMyRequest";
import { hpczone, addProject } from "@/api/project_api";
import { useMessage } from "@/components/MySnackbar";
import { getProjectList } from "../../project";
import { useStores } from "@/store";
import { checkIsNumberLetterChinese } from "@/utils/util";
import {
	setFileServerEndPointLocalStorage,
	getFiletokenAccordingToId,
} from "@/views/Project/project";

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

type zoneIdOption = {
	id: string;
	name: string;
};

type IAddProjectProps = {
	addOpen: boolean;
	setAddOpen: any;
};

const AddProject = (props: IAddProjectProps) => {
	const { addOpen, setAddOpen } = props;
	const { currentProjectStore } = useStores();
	const navigate = useNavigate();
	const message = useMessage();
	const [name, setName] = useState("");
	const [nameCheck, setNameCheck] = useState({
		error: false,
		help: "",
	});
	const [desc, setDesc] = useState("");
	const [descCheck, setDescCheck] = useState({
		error: false,
		help: "",
	});
	const [zoneId, setZoneId] = useState("");
	const [zoneIdOptions, setZoneIdOptions] = useState<Array<zoneIdOption>>([]);
	const [loading, setLoading] = useState(false);

	// 设置计算区
	const { run } = useMyRequest(hpczone, {
		onSuccess: (result: any) => {
			setZoneIdOptions(result);
			setZoneId(result[0].id || "");
		},
	});
	const { run: addProjectRun } = useMyRequest(addProject, {
		onBefore: () => {
			setLoading(true);
		},
		onSuccess: async (result: any) => {
			if (result.data) {
				setAddOpen(false);
				setLoading(false);
				message.success("新建项目成功");
				const projectList = await getProjectList();
				currentProjectStore.setProjectList(projectList);
				let project: any = {};
				projectList.forEach((item: any) => {
					if (item.name === name) {
						project = { ...item };
					}
				});
				currentProjectStore.changeProject(project);
				setFileServerEndPointLocalStorage(project.zoneId);
				getFiletokenAccordingToId(project.id).then((res) => {
					project.filetoken = res;
					currentProjectStore.changeProject(project);
				});
				navigate(`/product/cadd/projectOverview`)
			}
		},
		onError: () => {
			setLoading(false);
		},
	});

	useEffect(() => {
		run();
	}, [run]);

	useEffect(() => {
		if (addOpen) {
			setName("");
			setDesc("");
			setLoading(false);
			if (zoneIdOptions.length > 0) {
				setZoneId(zoneIdOptions[0].id);
			}
		}
	}, [addOpen, setZoneId, zoneIdOptions]);

	const checkName = (name: string) => {
		if (name) {
			if (name.length > 30) {
				setNameCheck({
					error: true,
					help: "格式不正确，必须在30字符以内，仅限大小写字母、数字、中文",
				});
			} else if (checkIsNumberLetterChinese(name)) {
				setNameCheck({
					error: false,
					help: "",
				});
			} else {
				setNameCheck({
					error: true,
					help: "格式不正确，必须在30字符以内，仅限大小写字母、数字、中文",
				});
			}
		} else {
			setNameCheck({
				error: true,
				help: "项目名称不能为空",
			});
		}
	};

	const handleNameChange = (e: any) => {
		const name = e.target.value;
		setName(name);
		checkName(name);
	};

	const handleZoneIdChange = (e: any) => {
		setZoneId(e.target.value);
	};

	const handleDescChange = (e: any) => {
		const desc = e.target.value;
		setDesc(desc.slice(0,300));
		// if (desc.length > 300) {
		// 	setDescCheck({
		// 		error: true,
		// 		help: "格式不正确，必须在300字符以内",
		// 	});
		// } else {
		// 	setDescCheck({
		// 		error: false,
		// 		help: "",
		// 	});
		// }
	};

	const handleSubmit = () => {
		checkName(name);
		if (!nameCheck.error && !descCheck.error && zoneId) {
			addProjectRun({
				name,
				desc,
				zoneId,
				product: "cadd",
			});
		} else {
			return;
		}
	};

	const handleFromBox = (e: React.SyntheticEvent) => {
		e.nativeEvent.stopImmediatePropagation();
	};

	return (
		<MyDialog
			open={addOpen}
			onConfirm={handleSubmit}
			onClose={() => setAddOpen(false)}
			title="新建项目"
			loading={loading}
		>
			<div className={style.formBox} onClick={handleFromBox}>
				<MyInput
					required
					error={nameCheck.error}
					id="name"
					label="项目名称"
					variant="outlined"
					value={name}
					onChange={handleNameChange}
					helperText={nameCheck.help}
					sx={{ marginBottom: "20px" }}
				/>
				<MyInput
					id="zoneId"
					select
					required
					label="计算区"
					value={zoneId}
					onChange={handleZoneIdChange}
					variant="outlined"
					onClick={handleFromBox}
					sx={{ marginBottom: "20px" }}
				>
					{zoneIdOptions &&
						zoneIdOptions.map((option) => (
							<MenuItem key={option.id} value={option.id}>
								{option.name}
							</MenuItem>
						))}
				</MyInput>
				<div style={{ position: "relative" }}>
					<MyInput
						value={desc}
						error={descCheck.error}
						id="desc"
						label="项目描述"
						multiline
						rows={4}
						placeholder="请输入项目描述"
						onChange={handleDescChange}
						helperText={descCheck.help}
					/>
					<span
						style={{
							position: "absolute",
							bottom: "7px",
							right: "12px",
							color: desc.length >= 300 ? "#d32f2f" : "#C2C6CC"
						}}
					>
						{desc.length}/300
					</span>
				</div>
			</div>
		</MyDialog>
	);
};

export default AddProject;
