/* eslint-disable no-plusplus */

import { truncate } from 'node:fs/promises';
import type { CustomRoute, ElegantConstRoute, ElegantRoute } from '@elegant-router/types';
import { getRootMenu } from '@/service/api';
import { useRouteStore } from '@/store/modules/route';
import { generatedRoutes } from '../elegant/routes';
import { layouts, views } from '../elegant/imports';
import { transformElegantRoutesToVueRoutes } from '../elegant/transform';
/**
 * custom routes
 *
 * @link https://github.com/soybeanjs/elegant-router?tab=readme-ov-file#custom-route
 */
const customRoutes: CustomRoute[] = [
  // {
  //   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'
  //       }
  //     },
  //   ]
  // }
  // {
  //   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'
  //       },
  //       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'
  //       }
  //     }
  // ]
  // }
];
/**
 * Get MenuThree
 *
 * @param MenuThree MenuThree
 */
// ${window.uiGlobalConfig.InternalCode}
// const { data: menus } = await getRootMenu(`/Restful/Kivii.Basic.Entities.Menu/Show.json?RootInternalCode=dashboard`);
const { data: menus } = await getRootMenu(
  `/Restful/Kivii.Basic.Entities.Menu/Show.json?RootInternalCode=${window.uiGlobalConfig.InternalCode}`
);
// const rootMenu =getRootMenu('/Restful/Kivii.Basic.Entities.Menu/Show.json?RootInternalCode=Dashboard');

const MenuThree = await getMenuThree(menus?.MenusMain?.Results);
const MenuRoot = menus?.MenuRoot;
// console.log(MenuRoot);
// 存储 MenuRoot 到 store

if (MenuRoot) {
  setTimeout(() => {
    const routeStore = useRouteStore();
    routeStore.setMenuRoot(MenuRoot);
  }, 1000);
}

const MenuThree2 = generateRoutes(MenuThree);
if (MenuThree2.length > 0) {
  for (let i = 0; i < MenuThree2.length; i++) {
    customRoutes.push(MenuThree2[i]);
  }
}
function getMenuThree(data: any) {
  const cloneData = JSON.parse(JSON.stringify(data)); // 对源数据深度克隆
  return cloneData.filter((father: { Kvid: any; children: any; ParentKvid: undefined }) => {
    // eslint-disable-next-line eqeqeq
    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[]) {
  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, ...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);
}
