import { defHttp } from '/@/utils/http/axios';
import { getMenuListResultModel, EnfMineTreeItem, RouteItem } 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';

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

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

const generateStaticSealedMonitorRoute = (route: RouteItem, item: EnfMineTreeItem) => {
  const res: RouteItem = {
    component: route.component,
    path: getFormattedText(item, route.path),
    name: getFormattedText(item, route.name || ''),
    meta: {
      ...route.meta,
      title: getFormattedText(item, route.meta.title),
      hideMenu: false,
      // orderNo: parseInt(getFormattedText(item, String(route.meta.orderNo))),
    },
  };

  if (item.childDepart) {
    res.children = item.childDepart.map((child) => generateStaticSealedMonitorRoute(route, child));
  }

  return res;
};

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

export const getMenuList: () => Promise<getMenuListResultModel> = () => {
  return Promise.all([
    defHttp.get<getMenuListResultModel>({ url: Api.GetMenuList }),
    defHttp.get({
      url: Api.getEnfMineTreeData,
    }),
  ]).then(([res, raw]) => {
    const tree = listToTree(raw, {
      id: 'id',
      pid: 'parentId',
      children: 'childDepart',
    });
    return {
      allAuth: res.allAuth || [],
      auth: res.auth || [],
      codeList: res.codeList || [],
      // menu: __STATIC_ROUTES__,
      menu: __STATIC_ROUTES__.map((ele) => {
        if (ele.children && ele.children.length && ele.meta?.generation) {
          const template = ele.children[0];
          ele.children.push(
            ...tree.map((d) => {
              return generateStaticSealedMonitorRoute(template, d);
            })
          );
        }

        return ele;
      }),
    };
  });
};

/**
 * @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,
        },
      });
    }
  });
}

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

export function getEnfMineTree() {
  return defHttp.get<EnfMineTreeItem[]>(
    { url: Api.getEnfMineTreeData }
    // {
    //   isTransformResponse: false,
    // }
  );
}
