import { useUserStore } from '@/store'

/** 全员默认拥有的基础操作权限，与后端 DEFAULT_BASIC_USER_PERMISSION_CODES 保持一致 */
export const BASIC_PERMISSION_CODES = [
  'page.lepao.accountList',
  'action.lepao.addAccount',
  'action.lepao.singleRun',
  'action.lepao.changeAutoRun',
  'action.lepao.updateAccount',
  'action.lepao.deleteAccount',
  'action.goods.sendCount',
  'page.service.createOrder',
  'action.service.createOrder'
]

export const isBasicPermission = (code) => BASIC_PERMISSION_CODES.includes(code)

/** 抢课助手页面访问权限，与后端 QK_ASSISTANT_ACCESS_CODES 保持一致 */
export const QK_ASSISTANT_ACCESS_CODES = [
  'page.qk.taskList',
  'page.admin.qk.client',
  'page.admin.qk.batch',
  'page.admin.qk.task',
  'page.admin.qk.report'
]

export const QK_ASSISTANT_SUBMIT_CODES = [
  'action.qk.task.submit',
  'action.qk.admin.taskManage'
]

export const QK_ASSISTANT_CONTROL_CODES = [
  'action.qk.task.control',
  'action.qk.admin.taskManage'
]

/** 根据额外授权与已关闭的基础权限，生成弹窗勾选状态 */
export const buildSelectedPermissionCodes = ({
  directPermissionCodes = [],
  deniedBasicPermissionCodes = []
} = {}) => {
  const deniedSet = new Set(deniedBasicPermissionCodes)
  const enabledBasics = BASIC_PERMISSION_CODES.filter((code) => !deniedSet.has(code))
  return [...new Set([...enabledBasics, ...directPermissionCodes])]
}

/** 保存时：额外授权（不含基础权限） */
export const filterSavablePermissionCodes = (codes = []) => {
  return codes.filter((code) => !isBasicPermission(code))
}

/** 保存时：未勾选的基础权限视为对该用户关闭 */
export const extractDeniedBasicPermissionCodes = (selectedCodes = []) => {
  const selectedSet = new Set(selectedCodes)
  return BASIC_PERMISSION_CODES.filter((code) => !selectedSet.has(code))
}

export const isSuperAdmin = (user) => {
  const roles = user?.roles || []
  return roles.includes('admin')
}

export const hasPermission = (code, user) => {
  if (!code) return true
  const currentUser = user || useUserStore()
  if (isSuperAdmin(currentUser)) return true
  return (currentUser.permissionCodes || []).includes(code)
}

export const hasAnyPermission = (codes, user) => {
  if (!codes || codes.length === 0) return true
  return codes.some(code => hasPermission(code, user))
}

export const canAccessRoute = (route, user) => {
  const meta = route?.meta || {}
  if (meta.permissionCode) return hasPermission(meta.permissionCode, user)
  if (meta.permissionCodes) return hasAnyPermission(meta.permissionCodes, user)

  const currentUser = user || useUserStore()
  if (!meta.permission || meta.permission.length === 0) return true
  return meta.permission.some(perm => (currentUser.roles || []).includes(perm))
}

export const isLoggedIn = (user) => !!(user?.uuid && user?.session)

/** 路由或其可见子路由是否为免登录公开页 */
export const hasPublicMenuDescendant = (route) => {
  if (!route || route.meta?.hideInMenu) return false
  if (route.meta?.public) return true
  if (!route.children?.length) return false
  return route.children.some((child) => hasPublicMenuDescendant(child))
}

export const hasVisibleMenuChildren = (route, user) => {
  if (!route?.children?.length) return true
  return route.children
    .filter((child) => !child.meta?.hideInMenu)
    .some((child) => canShowInMenu(child, user))
}

export const canShowInMenu = (route, user) => {
  if (!route || route.meta?.hideInMenu) return false
  if (route.redirect && !route.component && !route.meta?.title) return false
  if (!canAccessRoute(route, user)) return false
  if (route.children?.length && !hasVisibleMenuChildren(route, user)) return false
  if (isLoggedIn(user)) return true
  if (route.meta?.public) return true
  return hasPublicMenuDescendant(route)
}
