import { makeAutoObservable } from 'mobx';
import { Children, lazy, Suspense, useEffect } from 'react';
import { Spin } from 'antd';
import { apis } from '@/apis';

import {
    RobotOutlined,
} from '@ant-design/icons'
import {
    RouteObject, useNavigate
} from 'react-router-dom';
import path from 'path';
import router from '@/router';
import { resolveAlias } from '@/utils/index'
import { c } from 'node_modules/vite/dist/node/moduleRunnerTransport.d-DJ_mE5sf';

interface StateGenerator {
    constantRoutes: RouteObject[]
}
// 按需加载
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>
    );
};
export const businessRoutes: RouteObject[] = [
    {
        "path": "/overview",
        "element": "@/pages/home/index",
        "handle": {
            "breadcrumbName": "概览",
            "hidden": false
        }
    },
    {
        "path": "/appCenter",
        "handle": {
            "breadcrumbName": "应用中心",
            "hidden": false
        },
        "children": [
            {
                "path": "/appCenter/questionAnswer",
                "element": "@/pages/deepseek/questionAnswer/list/index",
                "handle": {
                    "breadcrumbName": "我创建的应用",
                    "hidden": false
                }
            },
            {
                "path": "/appCenter/questionAnswer/list",
                "element": "@/pages/deepseek/questionAnswer/list/index",
                "handle": {
                    "breadcrumbName": "我创建的应用列表",
                    "hidden": true
                }
            },
            {
                "path": "/appCenter/questionAnswer/create",
                "element": "@/pages/deepseek/questionAnswer/info/index",
                "handle": {
                    "breadcrumbName": "创建应用",
                    "hidden": true
                }
            },
            {
                "path": "/appCenter/questionAnswer/modify",
                "element": "@/pages/deepseek/questionAnswer/info/index",
                "handle": {
                    "breadcrumbName": "修改应用",
                    "hidden": true
                }
            },
            {
                "index": true,
                "element": "@/pages/deepseek/questionAnswer/appPlazaList/index",
                "handle": {
                    "hidden": true
                }
            }
        ]
    },
    {
        "path": "/knowledge",
        "handle": {
            "breadcrumbName": "知识库管理",
            "hidden": false
        },
        "children": [
            {
                "path": "/knowledge/knowledgeLib",
                "handle": {
                    "breadcrumbName": "知识库",
                    "hidden": false
                },
                "children": [
                    {
                        "index": true,
                        "element": "@/pages/deepseek/knowledgeLib/list/index",
                        "handle": {
                            "hidden": true
                        }
                    },
                    {
                        "path": "/knowledge/knowledgeLib/:knowledgeId/:createBy",
                        "element": "@/pages/deepseek/knowledgeLib/detail/index",
                        "handle": {
                            "breadcrumbName": "知识库详情",
                            "hidden": true
                        }
                    }
                ]
            },
            {
                "path": "/knowledge/revisionTool",
                "handle": {
                    "breadcrumbName": "修订工具",
                    "hidden": false
                },
                "children": [
                    {
                        "index": true,
                        "element": "@/pages/deepseek/knowledgeLib/revisionTool/list/index",
                        "handle": {
                            "hidden": true
                        }
                    }
                ]
            }
        ]
    },
    {
        "path": "/evaluationTool",
        "handle": {
            "breadcrumbName": "评测工具",
            "hidden": false
        },
        "children": [
            {
                "path": "/evaluationTool/evaluationTask",
                "handle": {
                    "breadcrumbName": "评测任务",
                    "hidden": false
                },
                "children": [
                    {
                        "index": true,
                        "element": "@/pages/deepseek/evaluationTool/evaluationTask/list/index",
                        "handle": {
                            "hidden": true
                        }
                    }
                ]
            },
            {
                "path": "/evaluationTool/datasetManagement",
                "handle": {
                    "breadcrumbName": "数据集管理",
                    "hidden": false
                },
                "children": [
                    {
                        "index": true,
                        "element": "@/pages/deepseek/evaluationTool/datasetManagement/list/index",
                        "handle": {
                            "hidden": true
                        }
                    }
                ]
            }
        ]
    },
    {
        "path": "/deepseek/audit",
        "element": "@/pages/deepseek/audit/index",
        "handle": {
            "breadcrumbName": "应用审核",
            "hidden": false
        }
    }
]
export const stateGenerator: StateGenerator = {
    constantRoutes: [
        ...businessRoutes,
    ]
}
// 修改状态
const setStateGenerator = (state: any) => {
    return {
        setConstantRoutes: (routes: any) => {
            state.constantRoutes = [...routes,
                // {   /* 系统管理 */
                //     path: '/system',
                //     handle: {
                //         hidden: false,
                //         breadcrumbName: '系统管理',
                //         icon: null,
                //     },
                //     children: [
                //         {
                //             path: '/system/apiKey',
                //             handle: {
                //                 breadcrumbName: 'API key',
                //                 hidden: false,
                //             },
                //             children:[{
                //                 index: true,
                //                 handle: {
                //                     hidden: true
                //                 },
                //                 element: lazyLoad(() => import('@/pages/system/apiKey/index')),
                //             }]
                //         },
                //         {
                //             path: '/system/usageStatistics',
                //             handle: {
                //                 breadcrumbName: '用量统计',
                //                 hidden: false,
                //             },
                //             children:[{
                //                 index: true,
                //                 handle: {
                //                     hidden: true
                //                 },
                //                 element: lazyLoad(() => import('@/pages/system/usageStatistics/index')),
                //             }]
                //         },
                //         {
                //             path: '/system/contentManagement',
                //             handle: {
                //                 breadcrumbName: '内容安全管理',
                //                 hidden: false,
                //             },
                //             children:[{
                //                 index: true,
                //                 handle: {
                //                     hidden: true
                //                 },
                //                 element: lazyLoad(() => import('@/pages/system/contentManagement/index')),
                //             }]
                //         },
                //     ]
                // },
                {
                    path:'/help',
                    handle: {
                        breadcrumbName: '帮助文档',
                        icon: null,
                    },
                    children:[
                        {
                            index: true,
                            handle: {
                                hidden: true
                            },
                            element: lazyLoad(() => import('@/pages/help/index')),
                        }
                    ]
                }
            ];
        }
    }
}
// 本地存储 key
const STORAGE_KEY = 'jk_constant_routes_v1'

// 将 routes 清理为可序列化结构（移除函数、React 元素等）
const cleanForStorage = (routes: any[]): any[] => {
    if (!Array.isArray(routes)) return [];
    return routes.map((node: any) => {
        const item: any = {};
        if ('path' in node) item.path = node.path;
        if ('index' in node) item.index = node.index;
        if (node.handle) item.handle = node.handle;
        if (typeof node.element === 'string') item.element = node.element;
        if (Array.isArray(node.children) && node.children.length > 0) {
            item.children = cleanForStorage(node.children);
        }
        return item;
    });
}

const saveRoutesToStorage = (routes: any[]) => {
    try {
        const cleaned = cleanForStorage(routes);
        window.localStorage.setItem(STORAGE_KEY, JSON.stringify(cleaned));
    } catch (e) {
        console.warn('[route] 保存 routes 到 localStorage 失败', e);
    }
}

const loadRoutesFromStorage = (): any[] | null => {
    try {
        const raw = window.localStorage.getItem(STORAGE_KEY);
        if (!raw) return null;
        return JSON.parse(raw);
    } catch (e) {
        console.warn('[route] 从 localStorage 读取 routes 失败', e);
        return null;
    }
}
const useMenuFromRoutes = (routes: RouteObject[]) => {
    const router = useNavigate();
    // 递归函数
    const transformRoutesToMenu = (routes: RouteObject[], parentPath?: string): any[] => {
        return routes
            .filter(route => !(route.handle && (route.handle as any).hidden)) // 过滤 hidden=true 的
            .map((route, index) => {
                const handle = (route.handle || {}) as any;
                const hasVisibleChildren =
                    Array.isArray(route.children) &&
                    route.children.some(
                        child => !(child.handle && (child.handle as any).hidden)
                    );
                // 当是 index 路由且没有 path 时，使用父级 path
                const routePath = (route as any).index && !route.path ? parentPath : route.path;
                const item: any = {
                    key: route.path || parentPath + `/${index}`,
                    icon: handle.icon || null,
                    label: handle.breadcrumbName || '未命名',
                    path: routePath || '',
                };
                // 点击事件（有 path 时）
                if (item.path && !hasVisibleChildren) {
                    item.onClick = () => {
                        router({ pathname: item.path! });
                    };
                }
                // 有子节点则递归生成
                if (route.children && route.children.length > 0) {
                    const childMenus = transformRoutesToMenu(route.children, routePath || parentPath);
                    if (childMenus.length > 0) {
                        item.children = childMenus;
                    }
                }
                return item;
            });
    };
    return transformRoutesToMenu(routes);
};

const useRouteStore = () => {
    const state = makeAutoObservable(stateGenerator);
    const actions = setStateGenerator(state);
    // 预先收集所有页面模块，便于通过字符串路径查找对应的 loader
    // 注意：根据项目结构，这里以 /src/pages 下的 tsx 文件为例，必要时可扩展匹配其他路径或后缀
    const pagesModules: Record<string, () => Promise<any>> = import.meta.glob('/src/pages/**/*.tsx');
    const onSetRoutes = async (routelink: any) => {
        try { saveRoutesToStorage(routelink); } catch (e) { }
        const wrapElements = (nodes: any[]): any[] => {
            if (!Array.isArray(nodes)) return nodes;
            return nodes.map((node: any) => {
                const newNode = { ...node };
                // 如果 element 是字符串路径, 使用 lazyLoad + dynamic import 包裹
                if (newNode.element) {
                    if (typeof newNode.element === 'string') {
                        const p = newNode.element as string;
                        // 期望传入的 p 类似 '@/pages/deepseek/.../index' 或 'pages/..'
                        const targetSuffix = (p.startsWith('@/') ? p.replace(/^@\//, '') : p) + '.tsx';

                        // 在 pagesModules 中查找以 targetSuffix 结尾的 key
                        const matchKey = Object.keys(pagesModules).find(k => k.endsWith(targetSuffix));
                        if (matchKey) {
                            // pagesModules[matchKey] 是一个函数，调用后返回 import Promise
                            newNode.element = lazyLoad(() => pagesModules[matchKey]());
                            // console.log('[route] lazy loaded via glob:', matchKey);
                        } else {
                            // 作为后备：尝试用 resolveAlias 构造的路径直接 import（兼容原有写法）
                            try {
                                const realPath = resolveAlias(`${p}.tsx`);
                                newNode.element = lazyLoad(() => import(/* @vite-ignore */ realPath));
                                console.log('[route] lazy loaded via resolveAlias:', realPath);
                            } catch (e) {
                                console.warn('[route] 未找到匹配模块：', p, '，请确认路径或扩展 import.meta.glob 的匹配范围');
                            }
                        }
                    } else if (typeof newNode.element === 'function') {
                        // 如果已经是一个 loader 函数（返回 import promise），直接用 lazyLoad 包裹
                        try {
                            newNode.element = lazyLoad(newNode.element);
                        } catch (e) {
                            // 保持原样
                        }
                    }
                }
                if (Array.isArray(newNode.children) && newNode.children.length > 0) {
                    newNode.children = wrapElements(newNode.children);
                }
                return newNode;
            });
        }
        const processed = wrapElements(routelink);
        actions.setConstantRoutes(processed)
    }
    // 尝试从 localStorage 读取已保存的路由并设置（保证刷新后路由存在）
    try {
        const cached = loadRoutesFromStorage();
        if (cached && Array.isArray(cached) && cached.length > 0) {
            onSetRoutes(cached);
        }
    } catch (e) {
        // ignore
    }

    return {
        state,
        onSetRoutes,
        useMenuFromRoutes
    };
}
export default useRouteStore()