/**
 * 部门管理服务
 */

export interface Department {
  id?: number
  deptName: string
  parentId?: number
  deptCode?: string
  leaderId?: number
  sortOrder?: number
  status: number
  createdAt?: string
}

export interface ApiResponse<T> {
  code: number
  data: T
  message?: string
}

class DepartmentService {
  private baseUrl = '/api'

  async getDepartments(): Promise<Department[]> {
    const response = await fetch(`${this.baseUrl}/departments`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<Department[]>
    if (result.code !== 200) {
      throw new Error(result.message || '获取部门列表失败')
    }
    return result.data
  }

  async getDepartmentById(id: number): Promise<Department | null> {
    const response = await fetch(`${this.baseUrl}/departments/${id}`, {
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<Department>
    if (result.code !== 200) {
      return null
    }
    return result.data
  }

  async createDepartment(data: Department): Promise<number> {
    const response = await fetch(`${this.baseUrl}/departments`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify(data)
    })
    const result = await response.json() as ApiResponse<number>
    if (result.code !== 200) {
      throw new Error(result.message || '创建部门失败')
    }
    return result.data
  }

  async updateDepartment(id: number, data: Department): Promise<void> {
    const response = await fetch(`${this.baseUrl}/departments/${id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify(data)
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '更新部门失败')
    }
  }

  async deleteDepartment(id: number): Promise<void> {
    const response = await fetch(`${this.baseUrl}/departments/${id}`, {
      method: 'DELETE',
      credentials: 'include'
    })
    const result = await response.json() as ApiResponse<void>
    if (result.code !== 200) {
      throw new Error(result.message || '删除部门失败')
    }
  }
}

export const departmentService = new DepartmentService()
export default departmentService
