import request from './request'

// ==================== 类型定义 ====================

export interface SysRole {
  id: number
  roleName: string
  roleKey: string
  roleSort: number
  status: number
  createBy?: string
  updateBy?: string
  createdAt: string
  updatedAt: string
  deletedAt?: string | null
}

export interface SysPermission {
  id: number
  permissionName: string
  permissionCode: string
  resource: string
  action: string
  description: string
  status: number
  createBy?: string
  updateBy?: string
  createdAt: string
  updatedAt: string
  deletedAt?: string | null
}

export interface RolePageResponse {
  content: SysRole[]
  totalPages: number
  totalElements: number
  currentPage: number
  pageSize: number
  first: boolean
  last: boolean
}

export interface CreateRoleDto {
  roleName: string
  roleKey: string
  roleSort?: number
  status?: number
}

export interface UpdateRoleDto {
  roleName?: string
  roleKey?: string
  roleSort?: number
  status?: number
}

export interface CreatePermissionDto {
  permissionName: string
  permissionCode: string
  resource: string
  action: string
  description?: string
  status?: number
}

/** 权限分组（按业务模块） */
export interface PermissionGroup {
  category: string
  module: string
  moduleLabel: string
  permissions: SysPermission[]
}

// ==================== 权限工具函数 ====================

/** 模块中文名映射 */
const moduleLabelMap: Record<string, string> = {
  user: '用户管理',
  role: '角色管理',
  permission: '权限管理',
  menu: '菜单管理',
  dict: '字典管理',
  config: '系统配置',
  log: '日志管理',
  file: '文件管理',
  notice: '公告管理',
  member: '会员管理',
  memberCard: '会员卡管理',
  groupCourse: '团课管理',
  groupCourseType: '团课类型管理',
  groupCourseRecommend: '团课推荐管理',
  groupCourseBooking: '团课预约管理',
  checkIn: '签到管理',
  dataCount: '数据统计',
  employee: '员工管理',
}

/** 从权限编码中解析模块名 */
export function parseModuleFromCode(code: string): { category: string; module: string } {
  const parts = code.split(':')
  return { category: parts[0] || 'other', module: parts[1] || 'other' }
}

/** 获取模块中文标签 */
export function getModuleLabel(mod: string): string {
  return moduleLabelMap[mod] || mod
}

/** 将权限列表按模块分组 */
export function groupPermissionsByModule(permissions: SysPermission[]): PermissionGroup[] {
  const map = new Map<string, PermissionGroup>()
  for (const perm of permissions) {
    const { category, module } = parseModuleFromCode(perm.permissionCode)
    const key = `${category}:${module}`
    if (!map.has(key)) {
      map.set(key, { category, module, moduleLabel: getModuleLabel(module), permissions: [] })
    }
    map.get(key)!.permissions.push(perm)
  }
  // 业务模块在前，系统模块在后；同类别按模块名排序
  return [...map.values()].sort((a, b) => {
    if (a.category !== b.category) return a.category === 'business' ? -1 : 1
    return a.module.localeCompare(b.module)
  })
}

// ==================== 角色 API ====================

/** 获取所有角色 */
export function getAllRoles(): Promise<SysRole[]> {
  return request.get('/api/roles')
}

/** 分页获取角色 */
export function getRolesByPage(params: {
  page?: number
  size?: number
  sort?: string
  order?: string
  keyword?: string
}): Promise<RolePageResponse> {
  return request.get('/api/roles/page', { params })
}

/** 获取角色详情 */
export function getRoleById(id: number): Promise<SysRole> {
  return request.get(`/api/roles/${id}`)
}

/** 创建角色 */
export function createRole(data: CreateRoleDto): Promise<SysRole> {
  return request.post('/api/roles', data)
}

/** 更新角色 */
export function updateRole(id: number, data: UpdateRoleDto): Promise<SysRole> {
  return request.put(`/api/roles/${id}`, data)
}

/** 删除角色（逻辑删除） */
export function deleteRole(id: number): Promise<SysRole> {
  return request.delete(`/api/roles/${id}`)
}

/** 恢复角色 */
export function restoreRole(id: number): Promise<SysRole> {
  return request.post(`/api/roles/${id}/restore`)
}

// ==================== 角色权限关联 API ====================

/** 获取角色的权限列表 */
export function getRolePermissions(roleId: number): Promise<SysPermission[]> {
  return request.get(`/api/roles/${roleId}/permissions`)
}

/** 为角色分配权限 */
export function assignPermissionsToRole(roleId: number, permissionIds: number[]): Promise<void> {
  return request.post(`/api/roles/${roleId}/permissions`, { permissionIds })
}

// ==================== 权限 API ====================

/** 获取所有权限 */
export function getAllPermissions(): Promise<SysPermission[]> {
  return request.get('/api/permissions')
}

/** 获取权限详情 */
export function getPermissionById(id: number): Promise<SysPermission> {
  return request.get(`/api/permissions/${id}`)
}

/** 创建权限 */
export function createPermission(data: CreatePermissionDto): Promise<SysPermission> {
  return request.post('/api/permissions', data)
}

/** 更新权限 */
export function updatePermission(id: number, data: SysPermission): Promise<SysPermission> {
  return request.put(`/api/permissions/${id}`, data)
}

/** 删除权限 */
export function deletePermission(id: number): Promise<void> {
  return request.delete(`/api/permissions/${id}`)
}
