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/deepseek/questionAnswer/list/index')),
                    },
                    {   /* 问答应用-创建应用 */
                        path: '/deepseek/questionAnswer/create',
                        handle: {
                            menuLevel: 1,
                            breadcrumbName: '创建应用',
                        },
                        element: lazyLoad(() => import('@/pages/deepseek/questionAnswer/info/index')),
                    },
                    {   /* 问答应用-修改应用 */
                        path: '/deepseek/questionAnswer/modify',
                        handle: {
                            menuLevel: 1,
                            breadcrumbName: '修改应用',
                        },
                        element: lazyLoad(() => import('@/pages/deepseek/questionAnswer/info/index')),
                    },
                ]
            },
            {   /* 知识库 */
                path: '/deepseek/knowledgeLib',
                handle: {
                    menuLevel: 1,
                    breadcrumbName: '知识库',
                },
                children: [
                    {
                        index: true,
                        element: lazyLoad(() => import('@/pages/deepseek/knowledgeLib/list/index')),
                    },
                    {   /* 知识库-知识库详情 */
                        path: '/deepseek/knowledgeLib/:knowledgeId/:createBy',
                        handle: {
                            menuLevel: 1,
                            breadcrumbName: '知识库详情',
                        },
                        children: [
                            {
                                index: true,
                                element: lazyLoad(() => import('@/pages/deepseek/knowledgeLib/detail/index'))
                            },
                            {   /* 知识库-知识库详情-切片信息 */
                                path: '/deepseek/knowledgeLib/:knowledgeId/:createBy/slice/:documentId/:embeddingId',
                                handle: {
                                    menuLevel: 1,
                                    breadcrumbName: '切片信息',
                                },
                                children: [
                                    {
                                        index: true,
                                        element: lazyLoad(() => import('@/pages/deepseek/knowledgeLib/slice/index')),
                                    },
                                    {   /* 知识库-知识库详情-切片信息-切片详情 */
                                        path: '/deepseek/knowledgeLib/:knowledgeId/:createBy/slice/:documentId/:embeddingId/:sliceId',
                                        handle: {
                                            menuLevel: 1,
                                            breadcrumbName: '切片详情',
                                        },
                                        element: lazyLoad(() => import('@/pages/deepseek/knowledgeLib/slice/detail/index')),
                                    },
                                ]
                            },
                        ]
                    },
                ]
            },
            {   /* 数据导出 */
                path: '/deepseek/dataExport',
                handle: {
                    menuLevel: 1,
                    breadcrumbName: '数据导出',
                },
                element: lazyLoad(() => import('@/pages/deepseek/dataExport/index')),
            },
            {   /* 数据导出 */
                path: '/deepseek/audit',
                handle: {
                    menuLevel: 1,
                    breadcrumbName: '应用审核',
                },
                element: lazyLoad(() => import('@/pages/deepseek/audit/index')),
            },
            {   /* 帮助文档 */
                path: '/help/*',
                handle: {
                    menuLevel: 1,
                    breadcrumbName: '帮助文档',
                },
                element: lazyLoad(() => import('@/help/components/HelpLayout')),
            },
            {   /* 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='/zhipu/questionAnswer' />,
            },
            {   /* 问答应用 */
                path: '/zhipu/questionAnswer',
                handle: {
                    menuLevel: 1,
                    breadcrumbName: '问答应用',
                },
                children: [
                    {
                        index: true,
                        element: lazyLoad(() => import('@/pages/platforms/zhipu/questionAnswer/list/index')),
                    },
                    {   /* 问答应用-创建应用 */
                        path: '/zhipu/questionAnswer/create',
                        handle: {
                            menuLevel: 1,
                            breadcrumbName: '创建应用',
                        },
                        element: lazyLoad(() => import('@/pages/platforms/zhipu/questionAnswer/info/index')),
                    },
                    {   /* 问答应用-修改应用 */
                        path: '/zhipu/questionAnswer/modify',
                        handle: {
                            menuLevel: 1,
                            breadcrumbName: '修改应用',
                        },
                        element: lazyLoad(() => import('@/pages/platforms/zhipu/questionAnswer/info/index')),
                    },
                ]
            },
            {   /* 知识库 */
                path: '/zhipu/knowledgeLib',
                handle: {
                    menuLevel: 1,
                    breadcrumbName: '知识库',
                },
                children: [
                    {
                        index: true,
                        element: lazyLoad(() => import('@/pages/platforms/zhipu/knowledgeLib/list/index')),
                    },
                    {   /* 知识库-知识库详情 */
                        path: '/zhipu/knowledgeLib/:knowledgeId',
                        handle: {
                            menuLevel: 1,
                            breadcrumbName: '知识库详情',
                        },
                        element: lazyLoad(() => import('@/pages/platforms/zhipu/knowledgeLib/detail/index')),
                    },
                ]
            },
            {   /* 数据导出 */
                path: '/zhipu/dataExport',
                handle: {
                    menuLevel: 1,
                    breadcrumbName: '数据导出',
                },
                element: lazyLoad(() => import('@/pages/platforms/zhipu/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'))
    },
    // {   /* 登录 */
    //     path: '/imgPre',
    //     element: lazyLoad(() => import('@/pages/deepseek/knowledgeLib/slice/detail/imgPre'))
    // },
    // {   /* 登录 */
    //     path: '/mdk',
    //     element: lazyLoad(() => import('@/pages/deepseek/knowledgeLib/slice/detail/mdk'))
    // },
    // {   /* 登录 */
    //     path: '/testPreImg',
    //     element: lazyLoad(() => import('@/pages/deepseek/knowledgeLib/slice/detail/testPreImg'))
    // }
]

// 路由模式-浏览器路由
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;

        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');
        const token = urlParams.get('token');
        if (token) {// 通过token登陆
            const checkToken = async (token: string) => {
                try {
                    const res = await apis.checkToken(token);
                    if(res.data.status) {
                        localStorage.setItem('token', token);
                        LocalStorage.setPermissions(res.permissions);
                        LocalStorage.setRoles(res.roles);
                        LocalStorage.setUserInfo({
                            id: res.user.userId,
                            name: res.user.nickName,
                        });
                        // 重新登录时，重置引导展开状态为默认展开
                        localStorage.removeItem('appGuideExpanded');
                        localStorage.removeItem('knowledgeGuideExpanded');
                        localStorage.removeItem('knowledgeDocGuideExpanded');
                        window.location.replace(originUrl + path);
                    }
                } catch (error: any) {
                    Modal.error({
                        title: 'Error',
                        content: 'token验证失败',
                    })
                }
                return <Navigate to='/login' replace={true} />
            }
            checkToken(token);
        } else 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,
                    })
                }
            }

            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;
