import React, { lazy, Suspense, useEffect } from 'react';

import {
    RouteObject,
    Navigate,
    createBrowserRouter,
    useLocation,
    RouterProvider,
    useNavigate,
    Routes,
} from 'react-router-dom';
import { Spin, Modal } from 'antd';
import LocalStorage from '@/LocalStorage';
import { apis, LoginApiParams } from '@/apis';
import useRouteStore, { businessRoutes } from './store/route';
import {
    RobotOutlined,
    ReadOutlined,
    FileSearchOutlined,
    MenuFoldOutlined,
    MenuUnfoldOutlined,
    CheckSquareOutlined
} from '@ant-design/icons'
// 按需加载
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';
// 公共路由
const commonRoutes: RouteObject[] = [
    {   /* 登录 */
        path: '/login',
        element: lazyLoad(() => import('@/pages/login/index'))
    },
    {   /* 测试 */
        path: '/help',
        element: lazyLoad(() => import('@/pages/help/index'))
    },
    {   /* 智能问答 - 独立全屏页面 */
        path: '/universalChat',
        element: lazyLoad(() => import('@/pages/universalChat/index')),
        handle: {
            breadcrumbName: "智能问答",
            hidden: true
        }
    },
    {   /* 404 */
        path: '/404',
        element: lazyLoad(() => import('@/components/404/index')),
    },
    {   /* H5 移动端测试页面（独立） */
        path: '/mobile-test',
        element: lazyLoad(() => import('@/pages/appCenter/mobile/MobileH5')),
        handle: {
            breadcrumbName: "H5 测试",
            hidden: true
        }
    },
    {   /* ChatInterface 组件测试页面（独立） */
        path: '/chat-test',
        element: lazyLoad(() => import('@/pages/test/ChatTestPage.tsx')),
        handle: {
            breadcrumbName: "聊天组件测试",
            hidden: true
        }
    },
    {   /* 路由不存在重定向 404 */
        path: '/*',
        element: <Navigate to='/404' replace={true} />,
    }
]
const AppRouter: React.FC = () => {
    const {
        state
    } = useRouteStore;
    useEffect(() => {
        // console.log('you----routerList',routerList)
    }, [state.constantRoutes])
    // React-Router-Dom@v6 路由表---业务路由
    const routerList: RouteObject[] = [
        {
            path: '/',
            element: lazyLoad(() => import('@/pages/layout/index')),

            children: [
                {
                    // index: true,
                        // element: lazyLoad(() => import('@/pages/deepseek/questionAnswer/appPlazaList/index')),
                    //     handle: {
                    //         breadcrumbName: '',
                    //     }
                    index: true,
                    element: <Navigate to="/appCenter" replace={true} />
                },
                // {   /* 系统管理 */
                //     path: '/deepseek/dataExport',
                //     handle: {
                //         hidden: false,
                //         breadcrumbName: '系统管理',
                //         icon: <RobotOutlined />,
                //     },
                //     element: lazyLoad(() => import('@/pages/deepseek/dataExport/index')),
                // },
                ...state.constantRoutes,
            ]
        },
    ]
    // 路由模式 - 浏览器路由
    const router = createBrowserRouter([...routerList, ...commonRoutes,]);

    // 路由白名单 (无需登录即可访问)
    const whiteList = ['/login', '/chat-test', '/help', '/mobile-test', '/universalChat'];

    // 前置路由
    router.routes.forEach((route: any) => {
        interface RouterComponentProps {
            component?: React.ReactNode,
        }
        // 路由组件 - 路由鉴权
        function RouterComponent(props: RouterComponentProps) {
            // console.log('RouterComponent props---- 进来了 多少次',props);
            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,
                                tenantId: res?.user?.tenantId,
                            });
                            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} />
    });
    return (
        <RouterProvider router={router} />
    )
}
export default AppRouter;
