import AllComponents, { Header } from '@pages/index';
import { Route, Routes, useNavigate } from 'react-router-dom';
import React, { cloneElement, lazy, Suspense, Fragment } from "react";
import SmallLoading from "@components/SmallLoading";
import TransitionGroup from "react-transition-group/TransitionGroup";
import CSSTransition from "react-transition-group/CSSTransition";
import SubScreen from "@components/SubScreen";
import RouteContainer from "@layout/Routes/RouteContainer";
import { Navigate } from "react-router";
import { ROUTE_PATH, ROUTE_TYPE_POP_OR_FULL } from "@constants/routes";
import { useThemeProvider } from "@contexts/themeContext";
import useAuthLockRoute from "@hooks/useAuthLockRoute";
const RouteWrapper = lazy(() => import('@layout/Routes/RouteWrapper'));

const PageNotFound = lazy(() => import('@pages/PageNotFound'));
const CreateRoute = (props) => {
    const { route, path, isLogin } = props;
    const component = (route.component != null && route.component !== "") ? route.component : "ModulePage";
    const Component = AllComponents[component];
    const topath = path ? path : route.path;
    const checkLogin = () => {
        if (!isLogin && route.login === 1) {
            return (<Navigate to={route.lpath} replace={true} />)
        }
        return (
            <RouteWrapper {...{ ...props, Comp: Component, route: route }} />
        )
    }
    return (
        <>
            <Route
                key={route.path}
                exact
                path={topath}
                element={checkLogin()}
            >

            </Route>
        </>
    )
}

const CBrowserRouter = (props) => {
    const { routes, isLogin } = props;
    return (
        <Routes>
            <Route path="*" element={<PageNotFound />} />
            {
                routes.map((route, index) => {
                    return (
                        <Fragment key={index}>
                            {CreateRoute({ ...props, route, path: route.path, isLogin: isLogin })}
                        </Fragment>
                    )


                })
            }
        </Routes>
    )
}
const CHashRouter = (props) => {
    const { routes, hlocation, isLogin } = props;
    const { checkRoute, handleRoutes, setIsOpenSub } = useThemeProvider();
    const navigate = useNavigate();
    //多hash 切到最后一个
    let { pathname, hash, search } = hlocation;
    if (hash != null) {
        hash = hash.split("?").shift();
    }
    let paths = pathname.split("#");
    pathname = paths.shift();
    let hashs = hash.split("#");
    hashs.shift();
    let currpath = pathname + hash;
    let currhash = "";
    let subIndex = -1;
    // const timeout=500;
    //多hash 切到最后一个
    const getRoutes = (path) => {
        for (const route of routes) {
            if (route.path === path) return route;
        }
        return null;
    }
    const handleClose = () => {
        if (hash.endsWith(ROUTE_PATH.PAYIFRAME)) {
            // 防止iframe 内部后退
            const temp = ROUTE_PATH.PAYMENTMETHODS + ROUTE_PATH.PAYIFRAME;
            const url = hash.replace(temp, "");
            window.location.hash = "";
            navigate(pathname + url, { replace: true });
            return;
        };

        let state = window.history.state;
        if (state != null && state.idx <= 0) {
            navigate("", { replace: true });
        }
        else navigate(ROUTE_PATH.BACK);
    }
    return (
        <TransitionGroup
            className="app-hash"
            childFactory={child => {
                let isopen = child.props.in;
                return cloneElement(child, { open: isopen })
            }}>
            {
                hashs.map((item, index) => {
                    if (item == "") return (<></>);
                    let hash = "#" + item;
                    let route = getRoutes(hash);
                    if (route == null) return (<></>);
                    if (!isLogin && route.login == 1) {
                        //检测未登录
                        global.authLockPath = currpath;
                        navigate(pathname + currhash + route.lpath, { replace: true });
                        return (<></>);
                        // return (<Navigate to={pathname + currhash + route.lpath} replace={true}/>)
                    }
                    //再次检查路由
                    if (!checkRoute(route.path)) {
                        navigate(pathname + currhash, { replace: true });
                        return (<></>);
                        // return (<Navigate to={pathname+currhash} replace={true}/>)
                    }

                    if (handleRoutes(route.path, pathname)) {
                        return (<></>);
                    }

                    currhash += hash;
                    if (route.type === ROUTE_TYPE_POP_OR_FULL) subIndex++;
                    return (
                        // <CSSTransition timeout={timeout}>
                        <RouteContainer level={subIndex} route={route} onClose={handleClose} header={Header[route.component]}>
                            <Suspense fallback={<SmallLoading />}>
                                <Routes key={index} location={{ pathname: currpath, hash: hash, search }}>
                                    {
                                        routes.map((route) => {
                                            if (route.path === hash) {
                                                return CreateRoute({ ...props, route, path: currpath, close: handleClose, isLogin: isLogin });
                                            }
                                            else return (<></>);
                                        })
                                    }
                                </Routes>
                            </Suspense>
                        </RouteContainer>
                        // </CSSTransition>
                    )
                })
            }
        </TransitionGroup>
    )
}
export { CBrowserRouter, CHashRouter };
