/* eslint-disable no-plusplus */

import type { ElegantConstRoute } from '@elegant-router/types';
import { getRootMenu } from '@/service/api';
import { useRouteStore } from '@/store/modules/route';
import { layouts, views } from '../elegant/imports';
import { transformElegantRoutesToVueRoutes } from '../elegant/transform';
import { generatedRoutes } from '../elegant/routes';

type ElegantRoute = ElegantConstRoute;

/**
 * custom routes
 *
 * @link https://github.com/soybeanjs/elegant-router?tab=readme-ov-file#custom-route
 */
const customRoutes: ElegantRoute[] = [
  // {
  //   name: 'exception',
  //   path: '/exception',
  //   component: 'layout.base',
  //   meta: {
  //     title: 'exception',
  //     i18nKey: 'route.exception',
  //     icon: 'ant-design:exception-outlined',
  //     order: 7
  //   },
  //   children: [
  //     {
  //       name: 'exception_403',
  //       path: '/exception/403',
  //       component: 'view.403',
  //       meta: {
  //         title: 'exception_403',
  //         i18nKey: 'route.exception_403',
  //         icon: 'ic:baseline-block'
  //       }
  //     },
  //     {
  //       name: 'exception_404',
  //       path: '/exception/404',
  //       component: 'view.404',
  //       meta: {
  //         title: 'exception_404',
  //         i18nKey: 'route.exception_404',
  //         icon: 'ic:baseline-web-asset-off'
  //       }
  //     },
  //     {
  //       name: 'exception_500',
  //       path: '/exception/500',
  //       component: 'view.500',
  //       meta: {
  //         title: 'exception_500',
  //         i18nKey: 'route.exception_500',
  //         icon: 'ic:baseline-wifi-off'
  //       }
  //     }
  //   ]
  // },
  // 以下是iframe-page的示例
  // {
  //   name: 'document',
  //   path: '/document',
  //   component: 'layout.base',
  //   meta: {
  //     title: 'document',
  //     i18nKey: 'route.document',
  //     order: 2,
  //     icon: 'mdi:file-document-multiple-outline'
  //   },
  //   children: [
  //     {
  //       name: 'document_antd',
  //       path: '/document/antd',
  //       component: 'view.iframe-page',
  //       props: {
  //         url: 'https://antdv.com/components/overview-cn',
  //         kvid: 'A0B25952-82B6-4A1E-B567-4BCDF9463Fs9A1',
  //         type: 'iframe'
  //       },
  //       meta: {
  //         title: 'document_antd',
  //         i18nKey: 'route.document_antd',
  //         order: 7,
  //         icon: 'logos:ant-design'
  //       }
  //     },
  //     {
  //       name: 'document_naive',
  //       path: '/document/naive',
  //       component: 'view.iframe-page',
  //       props: {
  //         url: 'https://www.naiveui.com/zh-CN/os-theme/docs/introduction'
  //       },
  //       meta: {
  //         title: 'document_naive',
  //         i18nKey: 'route.document_naive',
  //         order: 6,
  //         icon: 'logos:naiveui'
  //       }
  //     },
  //     {
  //       name: 'document_project',
  //       path: '/document/project',
  //       component: 'view.iframe-page',
  //       props: {
  //         url: 'https://docs.soybeanjs.cn/zh'
  //       },
  //       meta: {
  //         title: 'document_project',
  //         i18nKey: 'route.document_project',
  //         order: 1,
  //         localIcon: 'logo'
  //       }
  //     },
  //     {
  //       name: 'document_project-link',
  //       path: '/document/project-link',
  //       component: 'view.iframe-page',
  //       meta: {
  //         title: 'document_project-link',
  //         i18nKey: 'route.document_project-link',
  //         order: 2,
  //         localIcon: 'logo',
  //         href: 'https://docs.soybeanjs.cn/zh'
  //       }
  //     },
  //     {
  //       name: 'document_unocss',
  //       path: '/document/unocss',
  //       component: 'view.iframe-page',
  //       props: {
  //         url: 'https://unocss.dev/'
  //       },
  //       meta: {
  //         title: 'document_unocss',
  //         i18nKey: 'route.document_unocss',
  //         order: 5,
  //         icon: 'logos:unocss'
  //       }
  //     },
  //     {
  //       name: 'document_vite',
  //       path: '/document/vite',
  //       component: 'view.iframe-page',
  //       props: {
  //         url: 'https://cn.vitejs.dev/'
  //       },
  //       meta: {
  //         title: 'document_vite',
  //         i18nKey: 'route.document_vite',
  //         order: 4,
  //         icon: 'logos:vitejs'
  //       }
  //     },
  //     {
  //       name: 'document_vue',
  //       path: '/document/vue',
  //       component: 'view.iframe-page',
  //       props: {
  //         url: 'https://cn.vuejs.org/guide/introduction.html'
  //       },
  //       meta: {
  //         title: 'document_vue',
  //         i18nKey: 'route.document_vue',
  //         order: 3,
  //         icon: 'logos:vue'
  //       }
  //     },
  //     {
  //       name: 'document_localhost',
  //       path: '/document/localhost',
  //       component: 'view.iframe-page',
  //       props: {
  //         url: 'http://localhost/extjs6/classic/App.View.WebForm.Record.Manager',
  //         Kvid: 'A0B25952-82B6-4A1E-B567-4BCDF9463F9A1'
  //       },
  //       meta: {
  //         title: 'document_localhost',
  //         i18nKey: 'route.document_localhost',
  //         order: 10,
  //         icon: 'logos:vue'
  //       }
  //     }
  //   ]
  // }
];

// 将动态菜单路由存储在全局变量中
let dynamicMenuRoutes: ElegantRoute[] = [];

// 动态路由缓存键名
const DYNAMIC_ROUTES_CACHE_KEY = 'dynamic_routes_cache';
const GLOBAL_CONFIG_CACHE_KEY = 'ui_global_config_cache';

// 等待 uiGlobalConfig 初始化的函数
function waitForGlobalConfig(timeout = 10000): Promise<any> {
  return new Promise((resolve, reject) => {
    if (window.uiGlobalConfig?.InternalCode) {
      resolve(window.uiGlobalConfig);
      return;
    }

    let attempts = 0;
    const maxAttempts = timeout / 100;

    const checkInterval = setInterval(() => {
      attempts++;

      if (window.uiGlobalConfig?.InternalCode) {
        clearInterval(checkInterval);
        resolve(window.uiGlobalConfig);
      } else if (attempts >= maxAttempts) {
        clearInterval(checkInterval);
        console.warn('等待 uiGlobalConfig 初始化超时');
        reject(new Error('uiGlobalConfig initialization timeout'));
      }
    }, 100);
  });
}

// 缓存动态路由到 localStorage
function cacheDynamicRoutes(routes: ElegantRoute[], globalConfig: any) {
  try {
    const cacheData = {
      routes,
      timestamp: Date.now(),
      internalCode: globalConfig.InternalCode,
      version: '1.0' // 版本号，用于缓存失效
    };
    localStorage.setItem(DYNAMIC_ROUTES_CACHE_KEY, JSON.stringify(cacheData));
  } catch (error) {
    console.warn('缓存动态路由失败:', error);
  }
}

// 从 localStorage 恢复动态路由
function restoreDynamicRoutesFromCache(): boolean {
  try {
    const cached = localStorage.getItem(DYNAMIC_ROUTES_CACHE_KEY);
    if (!cached) return false;

    const cacheData = JSON.parse(cached);

    // 检查缓存是否过期（24小时）
    const now = Date.now();
    const cacheAge = now - cacheData.timestamp;
    const maxAge = 24 * 60 * 60 * 1000; // 24小时

    if (cacheAge > maxAge) {
      console.log('动态路由缓存已过期，清除缓存');
      localStorage.removeItem(DYNAMIC_ROUTES_CACHE_KEY);
      return false;
    }

    // 检查 InternalCode 是否匹配
    if (window.uiGlobalConfig?.InternalCode &&
        cacheData.internalCode !== window.uiGlobalConfig.InternalCode) {
      console.log('InternalCode 不匹配，清除缓存');
      localStorage.removeItem(DYNAMIC_ROUTES_CACHE_KEY);
      return false;
    }

    // 恢复路由数据
    if (cacheData.routes && Array.isArray(cacheData.routes)) {
      dynamicMenuRoutes = [...cacheData.routes];
      console.log(`从缓存恢复了 ${dynamicMenuRoutes.length} 个动态路由`);
      return true;
    }

    return false;
  } catch (error) {
    console.warn('恢复动态路由缓存失败:', error);
    localStorage.removeItem(DYNAMIC_ROUTES_CACHE_KEY);
    return false;
  }
}

// 动态获取菜单数据并生成路由

export async function generateDynamicRoutes(forceRefresh = false) {
  try {
    // 如果不是强制刷新，先尝试从缓存中恢复
    if (!forceRefresh) {
      const cached = restoreDynamicRoutesFromCache();
      if (cached) {
        console.log('从缓存中恢复动态路由成功');
        return;
      }
    }

    // 清空之前的动态路由
    dynamicMenuRoutes = [];

    // 等待 uiGlobalConfig 初始化
    const globalConfig = await waitForGlobalConfig();
    if (!globalConfig?.InternalCode) {
      console.warn('InternalCode not found even after waiting, skipping dynamic route generation');
      return;
    }

    console.log('开始生成动态路由...');

    const { data: menus } = await getRootMenu(
      `/Restful/Kivii.Basic.Entities.Menu/Show.json?RootInternalCode=${globalConfig.InternalCode}`
    );

    if (!menus || !menus.MenusMain?.Results) {
      console.warn('菜单数据为空，无法生成动态路由');
      return;
    }

    const MenuThree = getMenuThree(menus.MenusMain.Results);
    const MenuRoot = menus.MenuRoot;

    // 存储 MenuRoot 到 store
    if (MenuRoot) {
      setTimeout(() => {
        try {
          const routeStore = useRouteStore();
          routeStore.setMenuRoot(MenuRoot);
        } catch (error) {
          console.warn('设置 MenuRoot 到 store 失败:', error);
        }
      }, 100);
    }

    const MenuThree2 = generateRoutes(MenuThree);
    if (MenuThree2.length > 0) {
      dynamicMenuRoutes = [...MenuThree2];
      // 缓存到 localStorage
      cacheDynamicRoutes(dynamicMenuRoutes, globalConfig);
      console.log(`成功生成并缓存了 ${MenuThree2.length} 个动态路由`);
    } else {
      console.warn('未生成任何动态路由');
    }
  } catch (error) {
    console.error('生成动态路由失败:', error);
    // 失败时尝试从缓存恢复
    restoreDynamicRoutesFromCache();
  }
}

function getMenuThree(data: any) {
  if (!data || !Array.isArray(data)) return [];

  const cloneData = JSON.parse(JSON.stringify(data)); // 对源数据深度克隆
  return cloneData.filter((father: { Kvid: any; children: any; ParentKvid: undefined }) => {
    const branchArr = cloneData.filter((child: { ParentKvid: any }) => father.Kvid === child.ParentKvid);
    // eslint-disable-next-line no-unused-expressions
    branchArr.length > 0 ? (father.children = branchArr) : '';
    // eslint-disable-next-line eqeqeq
    return father.ParentKvid == undefined;
  });
}

function generateRoutes(data: any[]) {
  if (!data || !Array.isArray(data)) return [];

  return data.map(item => {
    const route: any = {
      name: item.Type === 'System' ? `${item.Type}` : item.Kvid,
      path: item.Type === 'System' ? `/${item.Type}` : `/${item.Kvid}`,
      component: 'layout.base',
      meta: {
        title: item.DisplayName,
        icon: 'mdi:file-document-multiple-outline',
        order: item.SortId,
        keepAlive: true
      },
      children: []
    };

    if (item.children && item.children.length > 0) {
      route.children = item.children.map(
        (child: { Remark: string; Type: string; Kvid: any; DisplayName: any; Icon: any; SortId: any }) => {
          const sanitizedRemark =
            child.Remark && child.Remark.startsWith('/') ? child.Remark.replace(/^\//, '') : child.Remark;
          return {
            name: child.Type === 'System' ? `${item.Type}_${sanitizedRemark}` : `${item.Kvid}_${child.Kvid}`,
            path: child.Type === 'System' ? `/${item.Type}/${sanitizedRemark}` : `/${item.Kvid}/${child.Kvid}`,
            component: 'view.iframe-page',
            props: {
              url: child.Type === 'System' ? sanitizedRemark : '',
              kvid: child.Kvid,
              type: child.Type
            },
            meta: {
              title: child.DisplayName,
              icon: child.Icon,
              order: child.SortId,
              keepAlive: true,
              type: 'iframe'
            }
          };
        }
      );
    }

    return route;
  });
}

export function createStaticRoutes() {
  const constantRoutes: ElegantRoute[] = [];

  const authRoutes: ElegantRoute[] = [];
  [...customRoutes, ...dynamicMenuRoutes, ...generatedRoutes].forEach(item => {
    if (item.meta?.constant) {
      constantRoutes.push(item);
    } else {
      authRoutes.push(item);
    }
  });

  return {
    constantRoutes,
    authRoutes
  };
}

/**
 * Get auth vue routes
 *
 * @param routes Elegant routes
 */
export function getAuthVueRoutes(routes: ElegantConstRoute[]) {
  return transformElegantRoutesToVueRoutes(routes, layouts, views);
}

// 添加清除缓存的导出函数
export function clearDynamicRoutesCache() {
  try {
    localStorage.removeItem(DYNAMIC_ROUTES_CACHE_KEY);
    console.log('动态路由缓存已清除');
  } catch (error) {
    console.warn('清除动态路由缓存失败:', error);
  }
}

// 应用启动时尝试恢复动态路由
// 这会在模块加载时立即执行，确保路由尽早可用
if (typeof window !== 'undefined') {
  // 先尝试从缓存恢复
  const restored = restoreDynamicRoutesFromCache();

  if (!restored) {
    // 如果缓存恢复失败，尝试等待 uiGlobalConfig 并生成新路由
    setTimeout(async () => {
      try {
        await generateDynamicRoutes(false); // 不强制刷新，允许从缓存恢复
      } catch (error) {
        console.warn('初始动态路由生成失败:', error);
      }
    }, 500); // 增加延迟时间，确保 uiGlobalConfig 有更多时间初始化
  }
}
