/** @format */
import matchAuth from "./matchRouter.ts";
import { Navigate, useLocation } from "react-router-dom";
import { message } from "antd";
import { getStorageFromKey } from "@/utils/localStorage/config.ts";
import React from "react";
export default function AuthRoute(props: { children: React.ReactNode }) {
	const location: any = useLocation();
	const isLogin = getStorageFromKey("token");
	const currentPath: string = location.pathname;
	// 未登录情况访问login
	const condition: boolean =
		(currentPath === "/login" && !isLogin) ||
		currentPath === "/404" ||
		(currentPath === "register" && !isLogin) ||
		(currentPath === "forget" && !isLogin);
	// 登录后访问login
	const conditionWithLogin: boolean =
		(currentPath === "/login" && isLogin) ||
		(currentPath === "register" && isLogin) ||
		(currentPath === "forget" && isLogin);
	const findPath: any = matchAuth(currentPath);

	if (condition) {
		return props.children;
	}
	if (conditionWithLogin && findPath) {
		return <Navigate to="/main/home" />;
	}

	if (!findPath) {
		return <Navigate to="/404" />;
	}

	if (!isLogin) {
		message
			.open({
				content: "请先登录！",
				type: "warning",
			})
			.then();
		return <Navigate to="/login" />;
	}
	return props.children;
}
