import { defHttp } from '/@/utils/http/axios';
import { getMenuListResultModel, EnfMineTreeItem } from './model/menuModel';
import { useUserStoreWithOut } from '@/store/modules/user';
import { setAuthCache } from '@/utils/auth';
import { TOKEN_KEY } from '@/enums/cacheEnum';
import { router } from '@/router';
import { PageEnum } from '@/enums/pageEnum';
import { getFormattedText } from '/@/components/Configurable/hooks/helper';
// import { listToTree } from '/@/utils/helper/treeHelper';
import { MineDepartment, useMineDepartmentStore } from '/@/store/modules/mine';
import { AppRouteRecordRaw } from '/@/router/types';
import { cloneDeep } from 'lodash-es';

enum Api {
  GetMenuList = '/sys/permission/getUserPermissionByToken',
  // 获取执法处及其下辖地区树状数据
  getEnfMineTreeDataNew = '/sys/user/getEnfMineTreeDataNew',

  // 【QQYUN-8487】
  // SwitchVue3Menu = '/sys/switchVue3Menu',
}

const generateStaticSealedMonitorRoute = (route: AppRouteRecordRaw, items: MineDepartment[]) => {
  return items.reduce((arr: AppRouteRecordRaw[], item) => {
    const [__, ___, LEAF_LEVEL_ORG] = item.memoDesc;

    // 菜单生成到叶节点为止，不包括叶节点
    if (item.orgType === LEAF_LEVEL_ORG) return arr;

    const res: AppRouteRecordRaw = {
      component: route.component,
      path: getFormattedText(item, route.path),
      name: getFormattedText(item, route.name || ''),
      meta: {
        ...route.meta,
        title: getFormattedText(item, route.meta.title),
        hideMenu: false,
      },
    };

    if (item.childDepart.length) {
      res.children = generateStaticSealedMonitorRoute(route, item.childDepart);
    }

    arr.push(res);
    return arr;
  }, []);
};

const processStaticRoutes = (routes: AppRouteRecordRaw[], mineStore: any) => {
  const ignores = mineStore.getRoot?.description || '';
  return routes.reduce((arr: AppRouteRecordRaw[], route) => {
    // 首先处理子菜单，因为子菜单的权限和父菜单是独立的，避免子菜单还有内容的情况下被父菜单过滤
    if (route.children && route.children.length) {
      // 如果子菜单有内容，则递归处理
      route.children = processStaticRoutes(route.children, mineStore);
    }

    // 最后检查，如果当前路由需要忽略且子菜单无内容则返回
    if (ignores.includes(route.name as string) && !route.children?.length) return arr;

    arr.push(route);
    return arr;
  }, []);
};

/**
 * @description: Get user menu based on id
 */

export const getMenuList: () => Promise<getMenuListResultModel> = () => {
  const mineStore = useMineDepartmentStore();
  return Promise.all([defHttp.get<getMenuListResultModel>({ url: Api.GetMenuList }), mineStore.fetchDepartTree()]).then(([res]) => {
    return {
      allAuth: res.allAuth || [],
      auth: res.auth || [],
      codeList: res.codeList || [],
      // menu: __STATIC_ROUTES__,
      menu: processStaticRoutes(cloneDeep(__STATIC_ROUTES__), mineStore).map((route) => {
        if (route.meta?.generation && route.children && route.children.length) {
          const template = route.children[0];
          route.children = generateStaticSealedMonitorRoute(
            template,
            mineStore.getRoot?.isLeaf ? mineStore.getDepartTree : mineStore.getRoot?.childDepart || []
          );
        }
        return route;
      }),
    };
  });
};

/**
 * @description: 获取后台菜单权限和按钮权限
 */
export function getBackMenuAndPerms() {
  return getMenuList().catch((e) => {
    // Token过期失效，直接跳转登录页面 2025-09-08 scott
    if (e && (e.message.includes('timeout') || e.message.includes('401') || e.message.includes('500'))) {
      const userStore = useUserStoreWithOut();
      userStore.setToken('');
      setAuthCache(TOKEN_KEY, null);
      router.push({
        path: PageEnum.BASE_LOGIN,
        query: {
          // 传入当前的路由，登录成功后跳转到当前路由
          redirect: router.currentRoute.value.fullPath,
        },
      });
    }
    throw e;
  });
}

/**
 * 切换成vue3菜单
 */
// export const switchVue3Menu = () => {
//   return new Promise((resolve) => {
//     defHttp.get({ url: Api.SwitchVue3Menu });
//   });
// };

export function getEnfMineTree() {
  return defHttp.get<EnfMineTreeItem>({ url: Api.getEnfMineTreeDataNew });
}
