import apiClient from './client'
import type { 
  Personnel, 
  PersonnelApprovalRequest,
  PaginatedResponse,
  PaginationParams 
} from '@/types'

export interface PersonnelFilterOptions {
  units: { id: number; name: string }[]
  positions: string[]
}

export interface PersonnelQueryParams extends PaginationParams {
  status?: string
  unitId?: number
  position?: string
  hasTraining?: string
  hasAchievements?: string
}

export const personnelApi = {
  async getAll(params?: PersonnelQueryParams): Promise<PaginatedResponse<Personnel>> {
    const response = await apiClient.get<PaginatedResponse<Personnel>>('/personnel', { params })
    return response.data
  },

  async getFilterOptions(): Promise<PersonnelFilterOptions> {
    const response = await apiClient.get<PersonnelFilterOptions>('/personnel/filter-options')
    return response.data
  },

  async getById(id: number): Promise<Personnel> {
    const response = await apiClient.get<Personnel>(`/personnel/${id}`)
    return response.data
  },

  async create(formData: FormData): Promise<Personnel> {
    const response = await apiClient.post<Personnel>('/personnel', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    return response.data
  },

  async update(id: number, formData: FormData): Promise<Personnel> {
    const response = await apiClient.put<Personnel>(`/personnel/${id}`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    return response.data
  },

  async delete(id: number): Promise<void> {
    await apiClient.delete(`/personnel/${id}`)
  },

  async approve(data: PersonnelApprovalRequest): Promise<Personnel> {
    const response = await apiClient.post<Personnel>(`/personnel/${data.personnelId}/approve`)
    return response.data
  },

  async reject(data: PersonnelApprovalRequest): Promise<Personnel> {
    const response = await apiClient.post<Personnel>(`/personnel/${data.personnelId}/reject`, {
      approved: data.approved,
      comments: data.comments
    })
    return response.data
  },

  async getPendingApprovals(): Promise<Personnel[]> {
    const response = await apiClient.get<Personnel[]>('/personnel/pending')
    return response.data
  },

  // 发起向上申报请求
  async requestUpgrade(personnelId: number): Promise<Personnel> {
    const response = await apiClient.post<Personnel>(`/personnel/${personnelId}/request-upgrade`)
    return response.data
  },

  // 审批向上申报请求
  async approveUpgrade(personnelId: number): Promise<Personnel> {
    const response = await apiClient.post<Personnel>(`/personnel/${personnelId}/approve-upgrade`)
    return response.data
  },

  // 拒绝向上申报请求
  async rejectUpgrade(personnelId: number, comments: string): Promise<Personnel> {
    const response = await apiClient.post<Personnel>(`/personnel/${personnelId}/reject-upgrade`, {
      comments
    })
    return response.data
  },

  // 师部直接升级团级人才为师级
  async directUpgrade(personnelId: number): Promise<Personnel> {
    const response = await apiClient.post<Personnel>(`/personnel/${personnelId}/direct-upgrade`)
    return response.data
  },

  // 重新提交被拒绝的人才审批
  async resubmit(personnelId: number): Promise<Personnel> {
    const response = await apiClient.post<Personnel>(`/personnel/${personnelId}/resubmit`)
    return response.data
  },

  // 获取审批历史
  async getApprovalHistory(personnelId: number): Promise<PersonnelApprovalHistory[]> {
    const response = await apiClient.get<PersonnelApprovalHistory[]>(`/personnel/${personnelId}/approval-history`)
    return response.data
  },

  // 导出Excel
  async exportExcel(params?: PersonnelQueryParams): Promise<Blob> {
    const response = await apiClient.get('/personnel/export', {
      params,
      responseType: 'blob'
    })
    return response.data
  },

  // 下载导入模板
  async downloadImportTemplate(): Promise<Blob> {
    const response = await apiClient.get('/personnel/import-template', {
      responseType: 'blob'
    })
    return response.data
  },

  // 导入Excel
  async importExcel(file: File): Promise<ImportResult> {
    const formData = new FormData()
    formData.append('file', file)
    const response = await apiClient.post<ImportResult>('/personnel/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    return response.data
  }
}

// 导入结果类型
export interface ImportResult {
  successCount: number
  failCount: number
  results: { row: number; success: boolean; name?: string; message?: string }[]
}

// 审批历史类型
export interface PersonnelApprovalHistory {
  id: number
  personnelId: number
  action: string
  previousStatus: string | null
  newStatus: string
  previousLevel: string | null
  newLevel: string | null
  reviewedByUserId: number
  reviewedByUnitId: number | null
  reviewedByUnitName?: string
  comments: string | null
  reviewedAt: string
}
