import { createRouter, createWebHistory } from 'vue-router'
import DashboardView from '../views/DashboardView.vue'
import ActivityListView from '../views/ActivityListView.vue'
import ForbiddenView from '../views/ForbiddenView.vue'
import LoginView from '../views/LoginView.vue'
import { useAuthStore } from '../stores/auth'
import UsersView from '../views/UsersView.vue'
import RewardsView from '../views/RewardsView.vue'
import RiskView from '../views/RiskView.vue'
import AuditLogView from '../views/AuditLogView.vue'
import NotificationsView from '../views/NotificationsView.vue'
import ActivityCreateView from '../views/ActivityCreateView.vue'
import InviteUserView from '../views/InviteUserView.vue'
import ActivityDetailView from '../views/ActivityDetailView.vue'
import ActivityConfigWizardView from '../views/ActivityConfigWizardView.vue'
import ApprovalCenterView from '../views/ApprovalCenterView.vue'
import UserDetailView from '../views/UserDetailView.vue'
import PermissionsView from '../views/PermissionsView.vue'
import RoleManagementView from '../views/RoleManagementView.vue'
import DepartmentManagementView from '../views/DepartmentManagementView.vue'
import SystemConfigView from '../views/SystemConfigView.vue'
import SystemApiKeysView from '../views/SystemApiKeysView.vue'
import DashboardMonitorView from '../views/DashboardMonitorView.vue'
import RewardApplyView from '../views/RewardApplyView.vue'
import RiskRulesView from '../views/RiskRulesView.vue'
import RiskRuleFormView from '../views/RiskRuleFormView.vue'
import PermissionUsersView from '../views/PermissionUsersView.vue'
import ActivityParticipantsView from '../views/ActivityParticipantsView.vue'
import type { AdminRole, Permission } from '../auth/roles'
import { usePermission } from '../composables/usePermission'
import { isRealMode } from '../auth/authMode'

// 路由权限码配置（权限码优先于角色检查, 使用Canonical权限）
const routePermissions: Record<string, Permission[]> = {
  'dashboard': ['dashboard.index.view.ALL'],
  'dashboard-monitor': ['dashboard.monitor.view.ALL'],
  'activities': ['activity.index.view.ALL'],
  'activity-create': ['activity.index.create.ALL'],
  'activity-detail': ['activity.index.view.ALL'],
  'activity-participants': ['activity.participant.view.ALL'],
  'activity-config': ['activity.config.edit.ALL'],
  'activity-config-edit': ['activity.config.edit.ALL'],
  'users': ['user.index.view.ALL'],
  'user-detail': ['user.index.view.ALL'],
  'user-invite': ['user.index.create.ALL'],
  'rewards': ['reward.index.view.ALL'],
  'reward-apply': ['reward.index.apply.ALL'],
  'risk': ['risk.index.view.ALL'],
  'risk-rules': ['risk.rule.manage.ALL'],
  'risk-rules-new': ['risk.rule.create.ALL'],
  'risk-rules-edit': ['risk.rule.edit.ALL'],
  'audit': ['audit.index.view.ALL'],
  'approvals': ['approval.index.view.ALL'],
  'permissions': ['permission.index.view.ALL'],
  'permissions-users': ['permission.index.view.ALL'],
  'role-management': ['role.index.view.ALL'],
  'department-management': ['department.index.view.ALL'],
  'system-config': ['system.index.view.ALL'],
  'system-api-keys': ['system.api-key.view.ALL'],
  'notifications': ['notification.index.view.ALL']
}

// 路由权限配置
const routeRoles: Record<string, AdminRole[]> = {
  'dashboard': ['super_admin', 'system_admin', 'operation_director', 'operation_manager', 'operation_specialist', 'marketing_director', 'marketing_manager', 'marketing_specialist', 'finance_manager', 'finance_specialist', 'risk_manager', 'risk_specialist', 'cs_manager', 'cs_agent', 'auditor', 'viewer'],
  'dashboard-monitor': ['super_admin', 'system_admin', 'operation_director', 'operation_manager', 'risk_manager', 'auditor'],
  'activities': ['super_admin', 'system_admin', 'operation_director', 'operation_manager', 'operation_specialist', 'marketing_director', 'marketing_manager', 'marketing_specialist', 'cs_manager', 'cs_agent', 'auditor', 'viewer'],
  'activity-create': ['super_admin', 'system_admin', 'operation_director', 'operation_manager', 'operation_specialist', 'marketing_director', 'marketing_manager', 'marketing_specialist'],
  'activity-detail': ['super_admin', 'system_admin', 'operation_director', 'operation_manager', 'operation_specialist', 'marketing_director', 'marketing_manager', 'marketing_specialist', 'cs_manager', 'cs_agent', 'auditor', 'viewer'],
  'activity-config': ['super_admin', 'system_admin', 'operation_director', 'operation_manager', 'marketing_director', 'marketing_manager'],
  'activity-participants': ['super_admin', 'system_admin', 'operation_director', 'operation_manager', 'operation_specialist', 'marketing_director', 'marketing_manager', 'marketing_specialist', 'auditor', 'viewer'],
  'users': ['super_admin', 'system_admin'],
  'user-detail': ['super_admin', 'system_admin'],
  'user-invite': ['super_admin', 'system_admin'],
  'rewards': ['super_admin', 'system_admin', 'operation_director', 'operation_manager', 'operation_specialist', 'marketing_director', 'marketing_manager', 'marketing_specialist', 'finance_manager', 'finance_specialist', 'auditor', 'viewer'],
  'reward-apply': ['super_admin', 'system_admin', 'operation_director', 'operation_manager', 'operation_specialist', 'marketing_director', 'marketing_manager', 'marketing_specialist', 'finance_manager', 'finance_specialist'],
  'risk': ['super_admin', 'system_admin', 'operation_director', 'risk_manager', 'risk_specialist', 'auditor'],
  'risk-rules': ['super_admin', 'system_admin', 'risk_manager', 'risk_specialist'],
  'risk-rules-new': ['super_admin', 'system_admin', 'risk_manager', 'risk_specialist'],
  'risk-rules-edit': ['super_admin', 'system_admin', 'risk_manager', 'risk_specialist'],
  'audit': ['super_admin', 'system_admin', 'operation_director', 'finance_manager', 'auditor'],
  'approvals': ['super_admin', 'system_admin', 'operation_director', 'operation_manager', 'marketing_director', 'marketing_manager', 'finance_manager', 'risk_manager', 'cs_manager'],
  'permissions': ['super_admin', 'system_admin'],
  'permissions-users': ['super_admin', 'system_admin'],
  'role-management': ['super_admin', 'system_admin'],
  'department-management': ['super_admin', 'system_admin'],
  'system-config': ['super_admin', 'system_admin', 'auditor'],
  'system-api-keys': ['super_admin', 'system_admin'],
  'notifications': ['super_admin', 'system_admin', 'operation_director', 'operation_manager', 'operation_specialist', 'marketing_director', 'marketing_manager', 'marketing_specialist', 'finance_manager', 'finance_specialist', 'risk_manager', 'risk_specialist', 'cs_manager', 'cs_agent', 'auditor', 'viewer']
}

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/login', name: 'login', component: LoginView },
    // PRD 9.x 规范路径
    { path: '/dashboard', name: 'dashboard', component: DashboardView, meta: { roles: routeRoles.dashboard } },
    { path: '/dashboard/monitor', name: 'dashboard-monitor', component: DashboardMonitorView, meta: { roles: routeRoles['dashboard-monitor'] } },
    { path: '/', redirect: '/dashboard' },
    // 活动管理 PRD路径: /activity/*
    { path: '/activity', name: 'activities', component: ActivityListView, meta: { roles: routeRoles.activities } },
    { path: '/activities', redirect: '/activity' }, // 兼容旧路径
    { path: '/activity/new', name: 'activity-create', component: ActivityCreateView, meta: { roles: routeRoles['activity-create'] } },
    { path: '/activity/:id', name: 'activity-detail', component: ActivityDetailView, meta: { roles: routeRoles['activity-detail'] } },
    { path: '/activities/:id', redirect: to => `/activity/${to.params.id}` }, // 兼容旧路径
    { path: '/activity/config', name: 'activity-config', component: ActivityConfigWizardView, meta: { roles: routeRoles['activity-config'] } },
    { path: '/activity/config/:id', name: 'activity-config-edit', component: ActivityConfigWizardView, meta: { roles: routeRoles['activity-config'] } },
    { path: '/activity/participants', name: 'activity-participants', component: ActivityParticipantsView, meta: { roles: routeRoles['activity-participants'] } },
    // 用户管理 PRD路径: /users/*
    { path: '/users', name: 'users', component: UsersView, meta: { roles: routeRoles.users } },
    { path: '/users/:id', name: 'user-detail', component: UserDetailView, meta: { roles: routeRoles['user-detail'] } },
    { path: '/users/invite', name: 'user-invite', component: InviteUserView, meta: { roles: routeRoles['user-invite'] } },
    // 奖励管理 PRD路径: /rewards
    { path: '/rewards', name: 'rewards', component: RewardsView, meta: { roles: routeRoles.rewards } },
    { path: '/rewards/apply', name: 'reward-apply', component: RewardApplyView, meta: { roles: routeRoles['reward-apply'] } },
    // 风险管理 PRD路径: /risks
    { path: '/risks', name: 'risk', component: RiskView, meta: { roles: routeRoles.risk } },
    { path: '/risks/rules', name: 'risk-rules', component: RiskRulesView, meta: { roles: routeRoles['risk-rules'] } },
    { path: '/risks/new', name: 'risk-rules-new', component: RiskRuleFormView, meta: { roles: routeRoles['risk-rules-new'] } },
    { path: '/risks/edit/:id', name: 'risk-rules-edit', component: RiskRuleFormView, meta: { roles: routeRoles['risk-rules-edit'] } },
    { path: '/risk', redirect: '/risks' }, // 兼容旧路径
    // 审计日志 PRD路径: /audits
    { path: '/audits', name: 'audit', component: AuditLogView, meta: { roles: routeRoles.audit } },
    { path: '/audit', redirect: '/audits' }, // 兼容旧路径
    // 审批中心 PRD路径: /approvals
    { path: '/approvals', name: 'approvals', component: ApprovalCenterView, meta: { roles: routeRoles.approvals } },
    // 权限管理 PRD路径: /permissions/*
    { path: '/permissions', name: 'permissions', component: PermissionsView, meta: { roles: routeRoles.permissions } },
    { path: '/permissions/users', name: 'permissions-users', component: PermissionUsersView, meta: { roles: routeRoles['permissions-users'] } },
    { path: '/permissions/roles', name: 'role-management', component: RoleManagementView, meta: { roles: routeRoles['role-management'] } },
    { path: '/roles', redirect: '/permissions/roles' }, // 兼容旧路径
    { path: '/permissions/departments', name: 'department-management', component: DepartmentManagementView, meta: { roles: routeRoles['department-management'] } },
    { path: '/departments', redirect: '/permissions/departments' }, // 兼容旧路径
    // 系统配置 PRD路径: /system/*
    { path: '/system', name: 'system-config', component: SystemConfigView, meta: { roles: routeRoles['system-config'] } },
    { path: '/system/config', name: 'system-config-page', component: SystemConfigView, meta: { roles: routeRoles['system-config'] } },
    { path: '/system/api-keys', name: 'system-api-keys', component: SystemApiKeysView, meta: { roles: routeRoles['system-api-keys'] } },
    // 通知管理 PRD路径: /notifications
    { path: '/notifications', name: 'notifications', component: NotificationsView, meta: { roles: routeRoles.notifications } },
    { path: '/403', name: 'forbidden', component: ForbiddenView }
  ]
})

router.beforeEach(async (to) => {
  const auth = useAuthStore()
  const { hasPermission, initialized: permInitialized } = usePermission()

  // 初始化认证状态
  await auth.initAuth()

  // 等待权限初始化完成
  if (!permInitialized.value) {
    await new Promise(resolve => {
      const checkInit = setInterval(() => {
        if (permInitialized.value) {
          clearInterval(checkInit)
          resolve(true)
        }
      }, 100)
      setTimeout(() => {
        clearInterval(checkInit)
        resolve(true)
      }, 5000)
    })
  }

  // 使用统一的认证模式判定函数
  const isInRealMode = isRealMode()

  // 未认证时的行为取决于认证模式
  if (!auth.isAuthenticated) {
    // 允许访问登录页
    if (to.name === 'login') {
      return true
    }

    // 真实模式下：未登录用户跳转到登录页
    if (isInRealMode) {
      return { name: 'login' }
    }

    // Demo模式下：自动进入演示模式
    if (to.name !== 'login') {
      await auth.loginDemo('super_admin')
    }
  }

  // 首先检查权限码（权限码检查优先于角色检查）
  const routeName = to.name as string
  const requiredPermissions = routePermissions[routeName]
  if (requiredPermissions && requiredPermissions.length > 0) {
    // 检查是否拥有所需权限码之一
    const hasRequiredPerm = requiredPermissions.some(perm => hasPermission(perm as Permission))
    if (!hasRequiredPerm) {
      // 没有权限码，跳转到403页面
      console.warn(`权限不足: 路由 ${routeName} 需要权限 ${requiredPermissions.join(', ')}，但用户不具备`)
      return { name: 'forbidden' }
    }
  }

  // 角色检查作为后备（在没有配置权限码时使用）
  const roles = (to.meta?.roles as AdminRole[] | undefined) ?? null
  if (roles && !roles.includes(auth.role as AdminRole)) {
    return { name: 'forbidden' }
  }
  return true
})

export default router
