import React, {useEffect} from "react";
import {BrowserRouter, HashRouter, Route, Routes, useLocation, useNavigate} from "react-router-dom";
import {APP_CONFIG} from "../config";
import {Button} from "@douyinfe/semi-ui";
import DefaultPage from "./index";
import {Result} from "../components/Result";
import {DashboardIndex} from "./dashboard";
import {useUserinfoStore} from "../store/userinfoStore.ts";

const routerMode: 'browser' | 'hash' | string = APP_CONFIG.ROUTER_MODE;

const WebRouter: React.FC<{
    children?: React.ReactNode
}> = (prop) => (
    routerMode == 'hash' ? <HashRouter>{prop.children}</HashRouter> : <BrowserRouter>{prop.children}</BrowserRouter>
)

const NotFound: React.FC = () => {
    const navigate = useNavigate();
    return <Result
        status="404"
        title="页面不存在或无法找到所请求的资源"
        // subTitle="Sorry, the page you visited does not exist."
        extra={<Button onClick={() => navigate('/')} type="primary">返回首页</Button>}/>
}
const AppRoutes = () => (<Routes>
    <Route path="/" element={<DefaultPage/>}/>
    <Route path="/dashboard" element={<DashboardIndex/>}/>
    <Route path="*" element={<NotFound/>}/>
</Routes>)
const RouteView = () => {
    const navigate = useNavigate();
    const loc = useLocation();
    const {userinfo, setUid} = useUserinfoStore();

    useEffect(() => {
        if (userinfo.id == -1 && loc.pathname !== '/') {
            setUid(0)
            navigate('/')
        }
    }, [userinfo])
    return (
        <div className="page-body-content">
            <AppRoutes></AppRoutes>
        </div>)
}
export const AppRouter = () => {
    return (<WebRouter>
        <RouteView/>
    </WebRouter>)
}
