/**
 * 路由工具函数
 *
 * 提供路由相关的工具函数
 *
 * @module utils/router
 */
import { RouteLocationNormalized, RouteRecordRaw } from 'vue-router'
import AppConfig from '@/config'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import i18n, { $t } from '@/locales'

/**
 * 路径到菜单 i18n key 的映射
 * 当后端返回的菜单名为中文或非 i18n key 时，根据 path 仍可显示多语言
 */
export const MAP_PATH_TO_MENU_I18N_KEY: Record<string, string> = {
  '/dashboard': 'menus.dashboard.title',
  '/dashboard/console': 'menus.dashboard.console',
  '/dashboard/user-center': 'menus.userCenter.title',
  '/system': 'menus.system.title',
  '/system/user': 'menus.system.user',
  '/system/role': 'menus.system.role',
  '/system/user-center': 'menus.system.userCenter',
  '/system/menu': 'menus.system.menu',
  '/system/dept': 'menus.system.dept',
  '/system/config': 'menus.system.config',
  '/safeguard': 'menus.safeguard.title',
  '/safeguard/dict': 'menus.safeguard.dict',
  '/safeguard/server': 'menus.safeguard.server',
  '/safeguard/oper-log': 'menus.safeguard.operLog',
  '/safeguard/login-log': 'menus.safeguard.loginLog',
  '/safeguard/email-log': 'menus.safeguard.emailLog',
  '/safeguard/database': 'menus.safeguard.database',
  '/safeguard/cache': 'menus.safeguard.cache',
  '/safeguard/attachment': 'menus.safeguard.attachment',
  '/tool': 'menus.tool.title',
  '/tool/crontab': 'menus.tool.crontab',
  '/tool/code': 'menus.tool.code',
  '/dice': 'menus.dice.title',
  '/dice/lottery_pool_config': 'menus.dice.lotteryPoolConfig',
  '/dice/lottery_pool_config/index': 'menus.dice.lotteryPoolConfig',
  '/dice/ante_config': 'menus.dice.anteConfig',
  '/dice/ante_config/index': 'menus.dice.anteConfig',
  '/dice/player': 'menus.dice.player',
  '/dice/player/index': 'menus.dice.player',
  '/dice/player_wallet_record': 'menus.dice.playerWalletRecord',
  '/dice/player_wallet_record/index': 'menus.dice.playerWalletRecord',
  '/dice/play_record': 'menus.dice.playRecord',
  '/dice/play_record/index': 'menus.dice.playRecord',
  '/dice/player_ticket_record': 'menus.dice.playerTicketRecord',
  '/dice/player_ticket_record/index': 'menus.dice.playerTicketRecord',
  '/dice/reward_config': 'menus.dice.rewardConfig',
  '/dice/reward_config/index': 'menus.dice.rewardConfig',
  '/dice/reward': 'menus.dice.reward',
  '/dice/reward/index': 'menus.dice.reward',
  '/dice/reward_config_record': 'menus.dice.rewardConfigRecord',
  '/dice/reward_config_record/index': 'menus.dice.rewardConfigRecord',
  '/dice/play_record_test': 'menus.dice.playRecordTest',
  '/dice/play_record_test/index': 'menus.dice.playRecordTest',
  '/dice/config': 'menus.dice.config',
  '/dice/config/index': 'menus.dice.config',
  'game': 'menus.game.title',
  'game/index': 'menus.game.title',
  '/game': 'menus.game.title',
  '/game/index': 'menus.game.title',
  '/result/success': 'menus.result.success',
  '/result/fail': 'menus.result.fail',
  '/exception/403': 'menus.exception.forbidden',
  '/exception/404': 'menus.exception.notFound',
  '/exception/500': 'menus.exception.serverError'
}

/** 扩展的路由配置类型 */
export type AppRouteRecordRaw = RouteRecordRaw & {
  hidden?: boolean
}

/** 顶部进度条配置 */
export const configureNProgress = () => {
  NProgress.configure({
    easing: 'ease',
    speed: 600,
    showSpinner: false,
    parent: 'body'
  })
}

/**
 * 设置页面标题，根据路由元信息和系统信息拼接标题
 * @param to 当前路由对象
 */
export const setPageTitle = (to: RouteLocationNormalized): void => {
  const { title } = to.meta
  if (title) {
    setTimeout(() => {
      document.title = `${formatMenuTitle(String(title), to.path)} - ${AppConfig.systemInfo.name}`
    }, 150)
  }
}

/**
 * 根据路径获取对应的菜单 i18n key（若有）
 */
export const getMenuI18nKeyByPath = (path: string): string | undefined => {
  if (!path) return undefined
  const normalized = path.replace(/\?.*$/, '').replace(/#.*$/, '').replace(/\/$/, '') || '/'
  return MAP_PATH_TO_MENU_I18N_KEY[normalized]
}

/**
 * 格式化菜单标题
 * @param title 菜单标题，可以是 i18n 的 key（如 menus.dashboard.title），也可以是中文等纯文本
 * @param path 可选，当前菜单路由 path；当 title 非 i18n key 时，用 path 查表得到 key 再翻译，以实现多语言切换
 * @returns 格式化后的菜单标题
 */
export const formatMenuTitle = (title: string, path?: string): string => {
  if (!title) return ''

  if (title.startsWith('menus.')) {
    if (i18n.global.te(title)) {
      return $t(title)
    }
    return title.split('.').pop() || title
  }

  if (path) {
    const i18nKey = getMenuI18nKeyByPath(path)
    if (i18nKey && i18n.global.te(i18nKey)) {
      return $t(i18nKey)
    }
  }

  return title
}
