import style from "./index.module.css";
import { TextField, MenuItem } from "@mui/material";
import MyDialog from "@/components/mui/MyDialog";
import React, { useState, useEffect, useImperativeHandle } from "react";
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";

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

const AddProject = (props: any) => {
	const { currentProjectStore } = useStores();
	const message = useMessage();
	let DialogRef: any = React.createRef();
	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 [submitloading, setSubmitloading] = useState(false);
	useImperativeHandle(props.onRef, () => {
		return {
			handleClickOpen: handleClickOpen,
		};
	});

	// 设置计算区
	const { run } = useMyRequest(hpczone, {
		onSuccess: (result: any) => {
			setZoneIdOptions(result);
			setZoneId(result[0].id || "");
		},
	});
	const { run: addProjectRun } = useMyRequest(addProject, {
		onBefore: () => {
			setSubmitloading(true);
		},
		onSuccess: async (result: any) => {
			if (result.data) {
				setSubmitloading(false);
				DialogRef.current.handleClose();
				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);
				});
			}
		},
		onError: () => {
			setSubmitloading(false);
		},
	});

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

	const handleClickOpen = () => {
		DialogRef.current.handleClickOpen();
		initData();
	};

	const initData = () => {
		setName("");
		setDesc("");
		if (zoneIdOptions.length > 0) {
			setZoneId(zoneIdOptions[0].id);
		}
	};

	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);
		if (desc.length > 100) {
			setDescCheck({
				error: true,
				help: "格式不正确，必须在100字符以内",
			});
		} 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
			handleSubmit={handleSubmit}
			onRef={DialogRef}
			title="新建项目"
			submitloading={submitloading}
		>
			<div className={style.formBox} onClick={handleFromBox}>
				<TextField
					required
					error={nameCheck.error}
					id="name"
					label="项目名称"
					variant="outlined"
					value={name}
					onChange={handleNameChange}
					helperText={nameCheck.help}
					size="small"
				/>
				<TextField
					id="zoneId"
					select
					required
					label="计算区"
					value={zoneId}
					onChange={handleZoneIdChange}
					variant="outlined"
					onClick={handleFromBox}
					size="small"
				>
					{zoneIdOptions &&
						zoneIdOptions.map((option) => (
							<MenuItem key={option.id} value={option.id}>
								{option.name}
							</MenuItem>
						))}
				</TextField>
				<TextField
					value={desc}
					error={descCheck.error}
					id="desc"
					label="项目描述"
					multiline
					rows={4}
					placeholder="请输入项目描述"
					onChange={handleDescChange}
					helperText={descCheck.help}
					size="small"
				/>
			</div>
		</MyDialog>
	);
};

export default AddProject;
