/**
 * 基于身份的权限管理中心
 * 给定某一个身份用户有某些页面的权限
 */

// 用户身份类型
export const USER_ROLES = {
  FREIGHT_AGENT: 'freightAgent',
  AGENT: 'agent',
  BD: 'bd',
  ANCHOR: 'anchor',
  GUEST: 'guest',
  ADMIN: 'admin',
  BDLEADER: 'bdLeader', // BD Leader
}

// 页面路径常量
export const PAGES = {
  COIN_SELLER: '/coin-seller',
  COIN_SELLER_SUB_SELLERS: '/coin-seller/sub-sellers',
  AGENCY_CENTER: '/agency-center',
  BD_LEADER_CENTER: '/bd-leader-center',
  BD_CENTER: '/bd-center',
  HOST_CENTER: '/host-center',
  APPLY: '/apply',
  MESSAGE: '/message',
  TRANSFER: '/transfer',
  EXCHANGE: '/exchange-gold-coins',
  PERSONAL_SALARY: '/platform-policy',
  HOST_SETTING: '/host-setting',
  AGENCY_SETTING: '/agency-setting',
  NOT_APP: '/not_app',
  LOADING: '/loading',
  ADMIN_CENTER: '/admin-center',
  PAY_RESULT: '/pay-result',
  MAP: '/map',
}

// 邀请页面
const INVITATION_PAGES = {
  INVITE_USER: '/invitation/invite-new-user', // 当前邀请新用户活动
  LEGACY_INVITE_USER: '/invitation-to-register', // 兼容线上历史 Banner 地址
  INVITE_RECHARGE_AGENCY: '/invite-recharge-agency', //邀请代理
  INVITE_AGENCY: '/invite-agency', //邀请代理
  INVITE_BD: '/invite-bd', //邀请成为BD
  INVITE_BDLEADER: '/invite-bd-leader', //邀请成为BDLeader
}

//排行榜
const RANKING_PAGES = [
  '/top-list', //排行榜
  '/weekly-star', //每周明星
  '/ranking', //总排行榜
  '/games-king', //游戏排行榜
  '/couple', //情侣排行榜
]

// 活动页面
const ACTIVITIES = [
  INVITATION_PAGES.INVITE_USER, //邀请新用户
  INVITATION_PAGES.LEGACY_INVITE_USER, //历史邀请入口，由路由重定向到当前活动
  '/recharge-reward', //充值奖励
  '/login-reward', // 登录奖励

  '/daily-recharge', // 每日充值页面
  '/activities/lucky-dollars-season5', // 幸运美金活动
  '/activities/gulben-festival', // 古尔邦节活动
  '/activities/lucky-dollars-season4', // 幸运美金活动
  '/activities/lesser-bairam', // 开斋节打榜
  '/activities/lucky-dollars-season3', // 斋月打榜
  '/activities/spring-festival', // 春节打榜

  '/activities/world-cup', // WorldCup
  '/activities/world-cup/event-detail', // WorldCup EventDetail
  '/activities/games/the-greedy-king', //贪金王游戏排行榜
  '/activities/bounty-football', // BountyFootball
  '/activities/poker-ace', // 扑克王牌排行榜
]

// 🎯 核心改变：基于身份的权限配置
// 每个身份拥有的页面权限列表
export const ROLE_PERMISSIONS = {
  // 公共页面（所有身份都可以访问）
  PUBLIC_PAGES: [
    PAGES.APPLY, //申请主播页面
    PAGES.NOT_APP, // 错误页面
    PAGES.PAY_RESULT, // 支付成功页面
    PAGES.MAP, // 地图选择页面
    ...RANKING_PAGES, //排行榜
    ...ACTIVITIES, //活动页面

    '/cp-reward', //情侣奖励说明页面

    '/recharge', //搜索充值对象页面
    '/recharge-pay-way', //充值方式页面
    '/recharge-guide', //充值引导页面
    '/recharge-agency-recruit', //充值代理介绍页面

    '/search-payee', //搜索收款人
    '/cash-withdraw', // 提现页面
    '/cash-out', // 活动提现页面
    '/cash-out-details', //提现详情页面
    '/KYC', //提现资料提交
    '/bank-card', //选择银行卡

    '/good-ID', //靓号申请页
  ],

  // Admin（管理员）
  [USER_ROLES.ADMIN]: [
    PAGES.ADMIN_CENTER, //管理员中心
    INVITATION_PAGES.INVITE_BDLEADER, //邀请成为BDLeader
    INVITATION_PAGES.INVITE_BD, //邀请成为BD
    INVITATION_PAGES.INVITE_RECHARGE_AGENCY, //邀请金币代理
    INVITATION_PAGES.INVITE_AGENCY, //邀请代理
    '/item-distribution', //赠送商品页面
    '/my-BDLeader-teams', //我的BDLeader团队页面
    '/my-BD-teams', //我的BD团队页面
    '/my-agency-teams', //我的代理团队页面
    '/my-recharge-agency', //我的金币代理团队页面
    '/admin-policy', //管理员政策页面
  ],

  // BD (商务拓展)
  [USER_ROLES.BD]: [
    PAGES.BD_CENTER, // 主页面
    PAGES.TRANSFER, // 转账功能
    PAGES.EXCHANGE, // 兑换功能
    PAGES.MESSAGE, // 消息功能
    INVITATION_PAGES.INVITE_AGENCY, //邀请代理
    '/bd-item-distribution', //赠送商品页面
    '/team-member',
    '/history-salary',
    '/available-income', //操作收益页
    '/income-details', //操作结果页
    '/policy', //政策页
  ],

  // BD Leader (商务拓展领导)
  get [USER_ROLES.BDLEADER]() {
    return [
      PAGES.BD_LEADER_CENTER, // 主页面
      INVITATION_PAGES.INVITE_BDLEADER, //邀请成为BDLeader
      INVITATION_PAGES.INVITE_BD, //邀请成为BD
      ...this[USER_ROLES.BD],
    ]
  },
  // Freight Agent (充值代理Rechange Agency/货运代理Freight Agent/金币代理Coin Seller)
  [USER_ROLES.FREIGHT_AGENT]: [
    PAGES.COIN_SELLER, // 主页面
    PAGES.COIN_SELLER_SUB_SELLERS, // 超级经销商子coin seller
    '/seller-records',
    '/coin-seller-search',
  ],

  // Agency (代理商)
  [USER_ROLES.AGENT]: [
    PAGES.AGENCY_CENTER, // 主页面
    PAGES.TRANSFER, // 转账功能
    PAGES.EXCHANGE, // 兑换功能
    PAGES.MESSAGE, // 消息功能
    PAGES.PERSONAL_SALARY, // 个人薪资查看
    PAGES.AGENCY_SETTING, // 主播设置
    '/team-member',
    '/information-details',
    '/history-salary',
    '/invite-members',
    '/team-bill',
  ],

  // Host (主播)
  [USER_ROLES.ANCHOR]: [
    PAGES.HOST_CENTER, // 主页面
    PAGES.TRANSFER, // 转账功能
    PAGES.EXCHANGE, // 兑换功能
    PAGES.MESSAGE, // 消息功能
    PAGES.PERSONAL_SALARY, // 个人薪资查看
    PAGES.HOST_SETTING, // 主播设置
    '/information-details',
    '/history-salary',
    '/invite-members',
    '/team-bill',
  ],

  // Guest (访客/申请者)
  [USER_ROLES.GUEST]: [
    PAGES.APPLY, // 申请页面
  ],

  // 加载页面
  LOADING_PAGE: [PAGES.LOADING],
}

// 身份优先级（数字越大优先级越高）
export const ROLE_PRIORITY = {
  [USER_ROLES.ADMIN]: 6,
  [USER_ROLES.FREIGHT_AGENT]: 5,
  [USER_ROLES.BDLEADER]: 4,
  [USER_ROLES.BD]: 3,
  [USER_ROLES.AGENT]: 2,
  [USER_ROLES.ANCHOR]: 1,
  [USER_ROLES.GUEST]: 0,
}

// 身份对应的默认首页
export const ROLE_DEFAULT_PAGES = {
  [USER_ROLES.ADMIN]: PAGES.ADMIN_CENTER,
  [USER_ROLES.FREIGHT_AGENT]: PAGES.COIN_SELLER,
  [USER_ROLES.AGENT]: PAGES.AGENCY_CENTER,
  [USER_ROLES.BDLEADER]: PAGES.BD_LEADER_CENTER,
  [USER_ROLES.BD]: PAGES.BD_CENTER,
  [USER_ROLES.ANCHOR]: PAGES.HOST_CENTER,
  [USER_ROLES.GUEST]: PAGES.APPLY,
}

// 身份显示配置
export const ROLE_DISPLAY_CONFIG = {
  [USER_ROLES.FREIGHT_AGENT]: {
    name: 'Freight Agent',
    tag: '💰 Coin Seller',
    color: '#FCD34D',
    bgColor: '#FEF3C7',
  },
  [USER_ROLES.AGENT]: {
    name: 'Agent',
    tag: '🏢 Agency',
    color: '#1E40AF',
    bgColor: '#DBEAFE',
  },
  [USER_ROLES.BD]: {
    name: 'BD',
    tag: '📈 BD',
    color: '#059669',
    bgColor: '#D1FAE5',
  },
  [USER_ROLES.ANCHOR]: {
    name: 'Anchor',
    tag: '👑 Host',
    color: '#5B21B6',
    bgColor: '#E0E7FF',
  },
  [USER_ROLES.GUEST]: {
    name: 'Guest',
    tag: '👤 Guest',
    color: '#6B7280',
    bgColor: '#F3F4F6',
  },
}

/**
 * 基于身份的权限管理类
 */
class RoleBasedPermissionManager {
  constructor() {
    this.userIdentity = null
    this.primaryRole = null
    this.allRoles = []
    this.isIdentityLoaded = false
    this.allowedPages = []
  }

  /**
   * 设置用户身份信息
   * @param {Object} identity - 身份信息对象
   */
  setUserIdentity(identity) {
    this.userIdentity = identity
    this.allRoles = this.calculateAllRoles(identity)
    this.primaryRole = this.calculatePrimaryRole(this.allRoles)
    this.allowedPages = this.calculateAllowedPages(this.allRoles)
    this.isIdentityLoaded = true

    console.debug('🔐 User identity updated:', {
      identity: this.userIdentity,
      allRoles: this.allRoles,
      primaryRole: this.primaryRole,
      allowedPages: this.allowedPages,
    })
  }

  /**
   * 计算用户所有身份
   * @param {Object} identity - 身份信息
   * @returns {Array} 所有身份列表
   */
  calculateAllRoles(identity) {
    if (!identity) return [USER_ROLES.GUEST]

    const roles = []
    if (identity.freightAgent) roles.push(USER_ROLES.FREIGHT_AGENT)
    if (identity.agent) roles.push(USER_ROLES.AGENT)
    if (identity.bdLeader) roles.push(USER_ROLES.BDLEADER)
    if (identity.bd) roles.push(USER_ROLES.BD)
    if (identity.anchor) roles.push(USER_ROLES.ANCHOR)
    if (identity.admin) roles.push(USER_ROLES.ADMIN)

    return roles.length > 0 ? roles : [USER_ROLES.GUEST]
  }

  /**
   * 计算用户主要身份（优先级最高的身份）
   * @param {Array} roles - 所有身份
   * @returns {string} 主要身份
   */
  calculatePrimaryRole(roles) {
    if (!roles || roles.length === 0) return USER_ROLES.GUEST

    // 按优先级排序，返回优先级最高的身份
    return roles.reduce((highest, current) => {
      return ROLE_PRIORITY[current] > ROLE_PRIORITY[highest] ? current : highest
    }, USER_ROLES.GUEST)
  }

  /**
   * 🎯 核心方法：基于身份计算允许访问的页面
   * @param {Array} roles - 用户拥有的所有身份
   * @returns {Array} 允许访问的页面列表
   */
  calculateAllowedPages(roles) {
    const allowedPages = new Set()

    // 添加公共页面
    ROLE_PERMISSIONS.PUBLIC_PAGES.forEach((page) => {
      allowedPages.add(page)
    })

    // 添加loading页面
    ROLE_PERMISSIONS.LOADING_PAGE.forEach((page) => {
      allowedPages.add(page)
    })

    // 根据用户拥有的每个身份，添加对应的页面权限
    roles.forEach((role) => {
      const rolePages = ROLE_PERMISSIONS[role] || []
      rolePages.forEach((page) => {
        allowedPages.add(page)
      })
    })

    return Array.from(allowedPages)
  }

  /**
   * 检查页面访问权限
   * @param {string} page - 页面路径
   * @returns {boolean} 是否有权限访问
   */
  hasPagePermission(page) {
    if (!this.isIdentityLoaded) {
      console.warn('⚠️ Identity not loaded yet')
      return false
    }

    const hasPermission = this.allowedPages.includes(page)

    console.debug('🔍 Permission check:', {
      page,
      allRoles: this.allRoles,
      primaryRole: this.primaryRole,
      hasPermission,
    })

    return hasPermission
  }

  /**
   * 检查特定身份是否有页面权限
   * @param {string} role - 身份
   * @param {string} page - 页面路径
   * @returns {boolean} 是否有权限
   */
  hasRolePagePermission(role, page) {
    const rolePages = ROLE_PERMISSIONS[role] || []
    const publicPages = ROLE_PERMISSIONS.PUBLIC_PAGES || []

    return rolePages.includes(page) || publicPages.includes(page)
  }

  /**
   * 获取指定身份的所有页面权限
   * @param {string} role - 身份
   * @returns {Array} 页面权限列表
   */
  getRolePermissions(role) {
    const rolePages = ROLE_PERMISSIONS[role] || []
    const publicPages = ROLE_PERMISSIONS.PUBLIC_PAGES || []

    return [...new Set([...rolePages, ...publicPages])]
  }

  /**
   * 获取用户默认首页
   * @returns {string} 默认页面路径
   */
  getDefaultPage() {
    return ROLE_DEFAULT_PAGES[this.primaryRole] || PAGES.APPLY
  }

  /**
   * 获取当前用户主要身份
   * @returns {string} 当前主要身份
   */
  getPrimaryRole() {
    return this.primaryRole
  }

  /**
   * 获取当前用户所有身份
   * @returns {Array} 所有身份
   */
  getAllRoles() {
    return this.allRoles
  }

  /**
   * 获取身份显示信息
   * @param {string} role - 身份标识
   * @returns {Object} 显示信息
   */
  getRoleDisplayInfo(role = this.primaryRole) {
    return ROLE_DISPLAY_CONFIG[role] || ROLE_DISPLAY_CONFIG[USER_ROLES.GUEST]
  }

  /**
   * 检查是否有多重身份
   * @returns {boolean} 是否有多重身份
   */
  hasMultipleRoles() {
    return this.allRoles.length > 1
  }

  /**
   * 切换到指定身份的默认页面
   * @param {string} role - 目标身份
   * @returns {string} 目标页面路径
   */
  switchToRole(role) {
    if (!this.allRoles.includes(role)) {
      console.warn(`⚠️ User does not have role: ${role}`)
      return this.getDefaultPage()
    }

    return ROLE_DEFAULT_PAGES[role] || PAGES.APPLY
  }

  /**
   * 获取身份导航菜单
   * @returns {Array} 可访问的页面菜单
   */
  getNavigationMenu() {
    const menu = []

    this.allowedPages.forEach((page) => {
      const menuItem = this.getPageMenuInfo(page)
      if (menuItem) {
        menu.push(menuItem)
      }
    })

    return menu
  }

  /**
   * 获取页面菜单信息
   * @param {string} page - 页面路径
   * @returns {Object|null} 菜单项信息
   */
  getPageMenuInfo(page) {
    const pageMenuConfig = {
      [PAGES.COIN_SELLER]: { title: 'Coin Seller', icon: '💰', order: 1 },
      [PAGES.AGENCY_CENTER]: { title: 'Agency Center', icon: '🏢', order: 2 },
      [PAGES.BD_CENTER]: { title: 'BD Center', icon: '📈', order: 3 },
      [PAGES.HOST_CENTER]: { title: 'Host Center', icon: '👑', order: 4 },
      [PAGES.TRANSFER]: { title: 'Transfer', icon: '💸', order: 5 },
      [PAGES.EXCHANGE]: { title: 'Exchange', icon: '🔄', order: 6 },
      [PAGES.MESSAGE]: { title: 'Messages', icon: '💬', order: 7 },
      [PAGES.PERSONAL_SALARY]: { title: 'Salary', icon: '💵', order: 8 },
      [PAGES.HOST_SETTING]: { title: 'Settings', icon: '⚙️', order: 9 },
    }

    const config = pageMenuConfig[page]
    return config ? { ...config, path: page } : null
  }

  /**
   * 重置权限信息
   */
  reset() {
    this.userIdentity = null
    this.primaryRole = null
    this.allRoles = []
    this.isIdentityLoaded = false
    this.allowedPages = []
    console.debug('🔄 Permission manager reset')
  }

  /**
   * 检查是否身份加载完成
   * @returns {boolean}
   */
  isLoaded() {
    return this.isIdentityLoaded
  }

  /**
   * 调试方法：打印当前权限状态
   */
  debugPermissions() {
    console.group('🔐 Current Permission State')
    console.log('User Identity:', this.userIdentity)
    console.log('All Roles:', this.allRoles)
    console.log('Primary Role:', this.primaryRole)
    console.log('Allowed Pages:', this.allowedPages)
    console.log('Default Page:', this.getDefaultPage())
    console.log('Navigation Menu:', this.getNavigationMenu())
    console.groupEnd()
  }
}

// 创建全局权限管理实例
export const permissionManager = new RoleBasedPermissionManager()

// 便捷方法
export const hasPermission = (page) => permissionManager.hasPagePermission(page)
export const hasRolePermission = (role, page) => permissionManager.hasRolePagePermission(role, page)
export const getRolePermissions = (role) => permissionManager.getRolePermissions(role)
export const getDefaultPage = () => permissionManager.getDefaultPage()
export const getPrimaryRole = () => permissionManager.getPrimaryRole()
export const getAllRoles = () => permissionManager.getAllRoles()
export const getRoleDisplayInfo = (role) => permissionManager.getRoleDisplayInfo(role)
export const setUserIdentity = (identity) => permissionManager.setUserIdentity(identity)
export const resetPermissions = () => permissionManager.reset()
export const switchToRole = (role) => permissionManager.switchToRole(role)
export const getNavigationMenu = () => permissionManager.getNavigationMenu()
export const debugPermissions = () => permissionManager.debugPermissions()

// 🎯 新增：快速查询某个身份的权限
export const QUICK_ROLE_CHECK = {
  // 检查 Freight Agent 的权限
  freightAgent: {
    pages: getRolePermissions(USER_ROLES.FREIGHT_AGENT),
    canAccess: (page) => hasRolePermission(USER_ROLES.FREIGHT_AGENT, page),
  },

  // 检查 Agent 的权限
  agent: {
    pages: getRolePermissions(USER_ROLES.AGENT),
    canAccess: (page) => hasRolePermission(USER_ROLES.AGENT, page),
  },

  // 检查 BD 的权限
  bd: {
    pages: getRolePermissions(USER_ROLES.BD),
    canAccess: (page) => hasRolePermission(USER_ROLES.BD, page),
  },

  // 检查 Anchor 的权限
  anchor: {
    pages: getRolePermissions(USER_ROLES.ANCHOR),
    canAccess: (page) => hasRolePermission(USER_ROLES.ANCHOR, page),
  },
}
