import type { RouteLocationNormalized } from 'vue-router'
import { useUserStore } from '@/store/modules/user'

/** 页面自带左侧渠道栏，不再包一层全局渠道壳 */
const BUILTIN_CHANNEL_LAYOUT_PATHS = [
  '/system/user',
  '/system/dept'
]

/** 运维页里不需要按渠道分栏的页面 */
const NO_CHANNEL_LAYOUT_PATHS = [
  '/safeguard/dict',
  '/safeguard/attachment',
  '/safeguard/database',
  '/safeguard/server',
  '/safeguard/cache',
  '/safeguard/email-log',
  '/admin_guide'
]

/** 日志页：左侧首项为「全部」，dept_id=0 表示不按渠道过滤 */
const ALL_CHANNEL_SCOPE_PATHS = [
  '/safeguard/login-log',
  '/safeguard/oper-log'
]

export function isSuperAdminUser(): boolean {
  const userStore = useUserStore()
  return Number(userStore.info?.id ?? 0) === 1
}

/** 游戏配置类页面：显示「默认配置模板」 */
export function isConfigChannelRoute(route: Pick<RouteLocationNormalized, 'path' | 'meta'>): boolean {
  if (route.meta?.channelScope === 'config') {
    return true
  }
  return /\/(config|ante_config|lottery_pool_config|reward_config|game)(\/|$)/.test(route.path)
}

/** 角色管理：左侧渠道树含默认模板（dept_id=0）与各渠道角色 */
export function isRoleChannelRoute(route: Pick<RouteLocationNormalized, 'path' | 'meta'>): boolean {
  if (route.meta?.channelScope === 'role') {
    return true
  }
  return route.path.startsWith('/system/role')
}

export function isAllChannelScopeRoute(route: Pick<RouteLocationNormalized, 'path' | 'meta'>): boolean {
  if (route.meta?.channelScope === 'all') {
    return true
  }
  return ALL_CHANNEL_SCOPE_PATHS.some((item) => route.path.startsWith(item))
}

export function isNoChannelLayoutRoute(route: Pick<RouteLocationNormalized, 'path' | 'meta'>): boolean {
  if (route.meta?.noChannelLayout === true) {
    return true
  }
  return NO_CHANNEL_LAYOUT_PATHS.some((item) => route.path.startsWith(item))
}

export function shouldWrapSuperAdminChannelLayout(route: RouteLocationNormalized): boolean {
  if (!isSuperAdminUser()) {
    return false
  }
  if (route.meta?.isFullPage) {
    return false
  }
  const path = route.path
  if (isNoChannelLayoutRoute(route)) {
    return false
  }
  for (let i = 0; i < BUILTIN_CHANNEL_LAYOUT_PATHS.length; i++) {
    if (path.startsWith(BUILTIN_CHANNEL_LAYOUT_PATHS[i])) {
      return false
    }
  }
  return true
}
