import { lazy, Suspense ,useEffect} from 'react';
import {
    RouteObject,
    Navigate,
    createBrowserRouter,
    useLocation,
    Routes} from 'react-router-dom';
import { Spin,Modal } from 'antd';
import LocalStorage from '@/LocalStorage';
import { apis, LoginApiParams } from '@/apis';

// 按需加载
const lazyLoad = (loader: () => Promise<any>) => {
    const Component = lazy(loader);

    const Loading: React.FC = () => {
        return (
            <div className='router-lazyLoad'>
                <Spin />
            </div>
        )
    }

    return (
        <Suspense fallback={<Loading />}>
            <Component />
        </Suspense>
    );
};

// 定义登录地址常量
const loginUrl = 'http://esc.sribs.com.cn:8080/esc-sso/oauth2.0/authorize?client_id=e97f94cf93761f4d69e8&response_type=code';
// React-Router-Dom@v6 路由表
const routerList: RouteObject[] = [
    {
        path: '/',
        element: lazyLoad(() => import('@/pages/layout/index')),
        children: [
            {
                index: true,
                element: LocalStorage.getStatusFlag('deepseek:application:list') ? <Navigate to='/deepseek/questionAnswer' /> : <Navigate to='/404' />,
            },
            {   /* 问答应用 */
                path: '/deepseek/questionAnswer',
                handle: {
                    menuLevel: 1,
                    breadcrumbName: '问答应用',
                },
                children: [
                    {
                        index: true,
                        element: lazyLoad(() => import('@/pages/takai/questionAnswer/list/index')),
                    },
                    {   /* 问答应用-创建应用 */
                        path: '/deepseek/questionAnswer/create',
                        handle: {
                            menuLevel: 1,
                            breadcrumbName: '创建应用',
                        },
                        element: lazyLoad(() => import('@/pages/takai/questionAnswer/info/index')),
                    },
                    {   /* 问答应用-修改应用 */
                        path: '/deepseek/questionAnswer/modify',
                        handle: {
                            menuLevel: 1,
                            breadcrumbName: '修改应用',
                        },
                        element: lazyLoad(() => import('@/pages/takai/questionAnswer/info/index')),
                    },
                ]
            },
            {   /* 知识库 */
                path: '/deepseek/knowledgeLib',
                handle: {
                    menuLevel: 1,
                    breadcrumbName: '知识库',
                },
                children: [
                    {
                        index: true,
                        element: lazyLoad(() => import('@/pages/takai/knowledgeLib/list/index')),
                    },
                    {   /* 知识库-知识库详情 */
                        path: '/deepseek/knowledgeLib/:knowledgeId',
                        handle: {
                            menuLevel: 1,
                            breadcrumbName: '知识库详情',
                        },
                        children: [
                            {
                                index: true,
                                element: lazyLoad(() => import('@/pages/takai/knowledgeLib/detail/index'))
                            },
                            {   /* 知识库-知识库详情-切片信息 */
                                path: '/deepseek/knowledgeLib/:knowledgeId/slice/:documentId/:embeddingId',
                                handle: {
                                    menuLevel: 1,
                                    breadcrumbName: '切片信息',
                                },
                                children: [
                                    {
                                        index: true,
                                        element: lazyLoad(() => import('@/pages/takai/knowledgeLib/slice/index')),
                                    },
                                    {   /* 知识库-知识库详情-切片信息-切片详情 */
                                        path: '/deepseek/knowledgeLib/:knowledgeId/slice/:documentId/:embeddingId/:sliceId',
                                        handle: {
                                            menuLevel: 1,
                                            breadcrumbName: '切片详情',
                                        },
                                        element: lazyLoad(() => import('@/pages/takai/knowledgeLib/slice/detail/index')),
                                    },
                                ]
                            },
                        ]
                    },
                ]
            },
            {   /* 数据导出 */
                path: '/deepseek/dataExport',
                handle: {
                    menuLevel: 1,
                    breadcrumbName: '数据导出',
                },
                element: lazyLoad(() => import('@/pages/takai/dataExport/index')),
            },
            {   /* 数据导出 */
                path: '/deepseek/audit',
                handle: {
                    menuLevel: 1,
                    breadcrumbName: '知识库审核',
                },
                element: lazyLoad(() => import('@/pages/takai/audit/index')),
            },
            {   /* 404 */
                path: '/404',
                element: lazyLoad(() => import('@/components/404/index')),
            },
            {   /* 路由不存在重定向404 */
                path: '/*',
                element: <Navigate to='/404' replace={true} />,
            },
        ]
    },
    {
        path: '/',
        element: lazyLoad(() => import('@/pages/layout/index')),
        children: [
            {
                index: true,
                element: <Navigate to='/questionAnswer' />,
            },
            {   /* 问答应用 */
                path: '/questionAnswer',
                handle: {
                    menuLevel: 1,
                    breadcrumbName: '问答应用',
                },
                children: [
                    {
                        index: true,
                        element: lazyLoad(() => import('@/pages/questionAnswer/list/index')),
                    },
                    {   /* 问答应用-创建应用 */
                        path: '/questionAnswer/create',
                        handle: {
                            menuLevel: 1,
                            breadcrumbName: '创建应用',
                        },
                        element: lazyLoad(() => import('@/pages/questionAnswer/info/index')),
                    },
                    {   /* 问答应用-修改应用 */
                        path: '/questionAnswer/modify',
                        handle: {
                            menuLevel: 1,
                            breadcrumbName: '修改应用',
                        },
                        element: lazyLoad(() => import('@/pages/questionAnswer/info/index')),
                    },
                ]
            },
            {   /* 知识库 */
                path: '/knowledgeLib',
                handle: {
                    menuLevel: 1,
                    breadcrumbName: '知识库',
                },
                children: [
                    {
                        index: true,
                        element: lazyLoad(() => import('@/pages/knowledgeLib/list/index')),
                    },
                    {   /* 知识库-知识库详情 */
                        path: '/knowledgeLib/:knowledgeId',
                        handle: {
                            menuLevel: 1,
                            breadcrumbName: '知识库详情',
                        },
                        element: lazyLoad(() => import('@/pages/knowledgeLib/detail/index')),
                    },
                ]
            },
            {   /* 数据导出 */
                path: '/dataExport',
                handle: {
                    menuLevel: 1,
                    breadcrumbName: '数据导出',
                },
                element: lazyLoad(() => import('@/pages/dataExport/index')),
            },
            {   /* 404 */
                path: '/404',
                element: lazyLoad(() => import('@/components/404/index')),
            },
            {   /* 路由不存在重定向404 */
                path: '/*',
                element: <Navigate to='/404' replace={true} />,
            },
        ]
    },
    {   /* 登录 */
        path: '/login',
        element: lazyLoad(() => import('@/pages/login/index'))
    }
]

// 路由模式-浏览器路由
const router = createBrowserRouter(routerList);

// 路由白名单
const whiteList = ['/login'];

// 前置路由
router.routes.forEach((route: any) => {
    interface RouterComponentProps {
        component?: React.ReactNode,
    }
    // 路由组件-路由鉴权
    function RouterComponent(props: RouterComponentProps) {
        const { component } = props;

        const location = useLocation();
        const path = location.pathname;

        if (LocalStorage.getToken()) {// 已登录
            return <>{component}</>
        } else {// 未登录

            const jkLogin = async (data: { code: string, redirectUrl: string }, url: string) => {
                try {
                    const res = await apis.jklogin(data);
                    console.log(res.data,"res.data");
                    localStorage.setItem('token', res.data.token);
                    window.location.replace(url);
                } catch (error: any) {
                    Modal.error({
                        title: '登录失败',
                        content: error.msg,
                    })
                }
            }

            const originUrl = window.location.origin;
            const fullUrl = window.location.href;
            const urlParams = new URLSearchParams(new URL(fullUrl).search);
            const code = urlParams.get('code');
            const state = urlParams.get('state');
            const userInfo = localStorage.getItem('userInfo');

            if (fullUrl.includes(originUrl + '/?code') && code && state) {// 通过code登陆
                if (!userInfo) {
                    jkLogin({ code: code, redirectUrl: encodeURIComponent(originUrl) }, state);
                }
            }
            else {
                //测试环境
                //const loginUrl = 'https://esctest.sribs.com.cn/esc-sso/oauth2.0/authorize?client_id=e97f94cf93761f4d69e8&response_type=code';
                //生产环境
                const loginUrl = 'http://esc.sribs.com.cn:8080/esc-sso/oauth2.0/authorize?client_id=e97f94cf93761f4d69e8&response_type=code';
                const externalLoginUrl = loginUrl + `&redirect_uri=${encodeURIComponent(originUrl)}&state=${encodeURIComponent(fullUrl)}`;
                if (!userInfo) {
                    window.location.replace(externalLoginUrl);
                }
            }
            // else {// 未登录
            //     if (whiteList.includes(path)) {
            //         return <>{component}</>
            //     } else {
            //         return <Navigate to='/login' replace={true} />
            //     }
            // }

        }
    }
    route.element = <RouterComponent component={route.element} />
});

export default router;
