import router from '@/router';

/**
 * 菜单 component 与业务页 router.push 路径对照（与动态菜单 path 可能不一致时的兜底）
 */
const ROUTE_FALLBACK: Record<string, string> = {
  'workflow/task/taskWaiting': '/task/taskWaiting',
  'workflow/task/taskFinish': '/task/taskFinish',
  'workflow/task/taskCopyList': '/task/taskCopyList',
  'workflow/task/myDocument': '/task/myDocument',
  'oa/erp/timesheetInfo/index': '/timesheet/timesheetInfo',
  'oa/erp/projectReport/index': '/project/projectReport',
  'oa/erp/projectInfo/index': '/project/projectInfo',
  'oa/erp/contractInfo/index': '/contract/contractInfo',
  'oa/erp/orderLedger/contractOrderTodoIndex': '/contract/contractOrderTodo',
  'system/notice/index': '/system/notice',
  'user/profile': '/user/profile'
};

/**
 * 根据菜单 component 字段解析可跳转的路由 path（需在登录后、动态路由已注册）
 */
export function resolveMenuPath(component: string): string | null {
  if (!component) {
    return null;
  }
  const normalized = component.replace(/^\//, '').replace(/\.vue$/, '');
  const withoutIndex = normalized.replace(/\/index$/, '');

  const fallback = ROUTE_FALLBACK[normalized] ?? ROUTE_FALLBACK[withoutIndex];
  if (fallback && router.getRoutes().some((r) => r.path === fallback)) {
    return fallback;
  }

  const segments = withoutIndex.split('/');
  const leaf = segments[segments.length - 1] || '';
  const leafShort = leaf.replace(/Index$/, '');

  let bestPath: string | null = null;
  let bestScore = 0;

  for (const route of router.getRoutes()) {
    const path = route.path;
    if (!path || path === '/' || path.includes('redirect') || path.includes(':')) {
      continue;
    }
    let score = 0;
    if (path === `/${withoutIndex}` || path === `/${normalized}`) {
      score = 200;
    } else if (path.endsWith(`/${leaf}`) || path.endsWith(`/${leafShort}`)) {
      score = 150;
    } else if (path.includes(leafShort) && leafShort.length > 4) {
      score = 100;
    } else if (segments.length > 1 && segments.every((s) => path.includes(s))) {
      score = 80;
    }
    if (score > bestScore || (score === bestScore && bestPath && path.length < bestPath.length)) {
      bestScore = score;
      bestPath = path;
    }
  }

  if (bestPath) {
    return bestPath;
  }
  return fallback ?? null;
}
