import { View } from "@tarojs/components";
import React, { useMemo, useState } from "react";
import './index.less'
import RouteUtil from '../../utils/routeUtil';
// @ts-ignore
import routes from "../../routes/route";
import RouteContext, { IHistoryRoutes, RouteComponentContext } from "./provider/route";

export const Router = (props: React.PropsWithChildren<{ url: string }>) => {
    const [history, setHistory] = useState<IHistoryRoutes[]>([
        {
            "url": props.url,
            "params": {},
            routeKey: (+new Date()).toString(),
            visible: true
        }
    ]);

    useMemo(() => {
        RouteUtil.push = (urls: string, option?: { params: any }) => {
            setHistory([...history, { url: urls, routeKey: (+new Date()).toString(), visible: true, params: option?.params }]);
        }
        RouteUtil.pop = () => {
            history[history.length - 1].visible = false;
            setHistory([...history]);
        }
        RouteUtil.removeLast = () => {
            history.splice(history.length - 1, 1);
            setHistory([...history]);
            console.log("路由栈", history);
        }
    }, [history])

    return (
        <RouteContext.Provider value={{ history }}>
            {
                history.map(p => {
                    let _find = routes[p.url]!;
                    return (
                        <RouteComponentContext.Provider key={p.routeKey} value={{ data: p }} >
                            <RouteComponent component={_find.component} url={p.url} visible={p.visible} />
                        </RouteComponentContext.Provider>
                    );
                })
            }
        </RouteContext.Provider>
    );
}

interface IRouteProps {
    component: any;
    url: string;

}

export const RouteComponent = (props: React.PropsWithChildren<IRouteProps & { visible: boolean }>) => {
    const [visible, setVisible] = useState(false);
    React.useEffect(() => {
        setVisible(props.visible);
        if (!props.visible) {
            setTimeout(() => {
                RouteUtil.removeLast();
            }, 200);
        }
    }, [props.visible]);
    return (
        <View onClick={e => { e.stopPropagation(); }} style={{ position: "fixed", left: 0, top: 0, width: "100vw", height: "100vh" }} >
            <View className="show" style={{
                position: "fixed", "left": visible ? 0 : document.body.clientWidth, top: 0, width: "100%", height: "100%", background: "#fff",
                boxShadow: "0 0px 0px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19)"
            }} >
                {React.createElement(props.component)}
            </View>
        </View>
    )
}