import request from './request'

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

export interface RoleInfo {
  id: number
  roleName: string
  roleKey: string
  roleSort: number
}

export interface EmployeeInfo {
  id: number
  username: string
  nickname: string
  email: string
  phone: string
  avatar: string | null
  status: number
  roles: RoleInfo[]
  createdAt: string
  updatedAt: string
  deletedAt: string | null
}

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

export interface SysRole {
  id: number
  roleName: string
  roleKey: string
  roleSort: number
  status: number
  createdAt: string
  updatedAt: string
}

export interface CreateEmployeeDto {
  username: string
  password: string
  nickname?: string
  email: string
  phone: string
  roles?: number[]
}

export interface UpdateEmployeeDto {
  email?: string
  roleId?: number
  status?: number
}

export interface AssignRolesDto {
  roleIds: string[]
}

export interface ChangePasswordDto {
  oldPassword: string
  newPassword: string
}

// ==================== API 方法 ====================

/** 分页获取员工列表（含角色信息） */
export function getEmployeesByPage(params: {
  page?: number
  size?: number
  sort?: string
  order?: string
  keyword?: string
  includeDeleted?: boolean
}): Promise<EmployeePageResponse> {
  return request.get('/api/employees/page', { params })
}

/** 获取已删除的账号列表 */
export function getDeletedEmployees(params: {
  page?: number
  size?: number
  keyword?: string
}): Promise<EmployeePageResponse> {
  return request.get('/api/employees/page', {
    params: { ...params, includeDeleted: true }
  })
}

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

/** 创建员工账号 */
export function createEmployee(data: CreateEmployeeDto): Promise<EmployeeInfo> {
  return request.post('/api/users', data)
}

/** 获取员工详情 */
export function getEmployeeById(id: number): Promise<EmployeeInfo> {
  return request.get(`/api/users/${id}`)
}

/** 更新员工信息 */
export function updateEmployee(id: number, data: UpdateEmployeeDto): Promise<EmployeeInfo> {
  return request.put(`/api/users/${id}`, data)
}

/** 逻辑删除员工 */
export function deleteEmployee(id: number): Promise<void> {
  return request.post(`/api/users/${id}/action/logical-delete`)
}

/** 修改员工密码（管理员重置） */
export function changeEmployeePassword(id: number, data: ChangePasswordDto): Promise<EmployeeInfo> {
  return request.post(`/api/users/${id}/action/change-password`, data)
}

/** 为员工分配角色 */
export function assignRoles(id: number, data: AssignRolesDto): Promise<void> {
  return request.post(`/api/users/${id}/roles`, data)
}
