import apiClient from './client'
import type { 
  MaterialAllocation, 
  CreateAllocationRequest, 
  AllocationDistribution,
  UpdateDistributionRequest,
  PaginatedResponse,
  PaginationParams 
} from '@/types'

export const allocationsApi = {
  async getAll(params?: PaginationParams): Promise<PaginatedResponse<MaterialAllocation>> {
    const response = await apiClient.get<PaginatedResponse<MaterialAllocation>>('/allocations', { params })
    return response.data
  },

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

  async create(data: CreateAllocationRequest): Promise<MaterialAllocation> {
    const response = await apiClient.post<MaterialAllocation>('/allocations', data)
    return response.data
  },

  async update(id: number, data: Partial<CreateAllocationRequest>): Promise<MaterialAllocation> {
    const response = await apiClient.put<MaterialAllocation>(`/allocations/${id}`, data)
    return response.data
  },

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

  async getDistributions(allocationId: number): Promise<AllocationDistribution[]> {
    const response = await apiClient.get<AllocationDistribution[]>(`/allocations/${allocationId}/distribution`)
    return response.data
  },

  async updateDistribution(distributionId: number, data: UpdateDistributionRequest): Promise<AllocationDistribution> {
    const response = await apiClient.put<AllocationDistribution>(`/allocations/distributions/${distributionId}`, data)
    return response.data
  },

  async getMyDistributions(): Promise<AllocationDistribution[]> {
    const response = await apiClient.get<AllocationDistribution[]>('/allocations/my-distributions')
    return response.data
  },

  async getConsumptionReports(distributionId: number): Promise<ConsumptionReport[]> {
    const response = await apiClient.get<ConsumptionReport[]>(`/allocations/distributions/${distributionId}/reports`)
    return response.data
  },

  async getReportSummaryByUnit(distributionId: number, period?: string): Promise<UnitReportSummary[]> {
    const response = await apiClient.get<UnitReportSummary[]>(`/allocations/distributions/${distributionId}/summary`, {
      params: period ? { period } : undefined
    })
    return response.data
  },

  async getConsumptionStats(allocationId: number, period: string): Promise<ConsumptionStatsResponse> {
    const response = await apiClient.get<ConsumptionStatsResponse>(`/allocations/${allocationId}/consumption-stats`, {
      params: { period }
    })
    return response.data
  }
}

export interface ConsumptionReport {
  id: number
  reportedAmount: number
  cumulativeAmount: number
  remarks?: string
  reportedByUserName?: string
  reportedByUnitId?: number
  reportedAt: string
}

export interface UnitReportSummary {
  unitId: number
  unitName: string
  unitLevel: string
  totalReported: number
  reportCount: number
  lastReportedAt?: string
}

export interface UnitConsumptionStat {
  unitId: number
  unitName: string
  unitLevel: string
  unitQuota: number
  totalConsumed: number
  completionRate: number
  reportCount: number
}

export interface ConsumptionStatsResponse {
  allocationId: number
  materialName: string
  unit: string
  totalQuota: number
  period: string
  startDate: string
  endDate: string
  unitStats: UnitConsumptionStat[]
}

// 消耗记录删改申请相关
export interface ChangeRequest {
  id: number
  consumptionReportId: number
  requestType: 'Delete' | 'Modify'
  reason: string
  status: 'Pending' | 'Approved' | 'Rejected'
  requestedAt: string
  requestedByUnitName?: string
  requestedByUserName?: string
  processedAt?: string
  processedByUnitName?: string
  processComments?: string
  consumptionReport?: {
    id: number
    reportedAmount: number
    reportedAt: string
    remarks?: string
    materialName?: string
    unit?: string
  }
}

export const changeRequestsApi = {
  // 创建删改申请
  async create(data: { consumptionReportId: number; requestType: 'Delete' | 'Modify'; reason: string }): Promise<{ message: string; id: number }> {
    const response = await apiClient.post<{ message: string; id: number }>('/ConsumptionChangeRequests', {
      consumptionReportId: data.consumptionReportId,
      requestType: data.requestType === 'Delete' ? 1 : 2,
      reason: data.reason
    })
    return response.data
  },

  // 获取待处理的申请（上级查看下级的）
  async getPending(): Promise<ChangeRequest[]> {
    const response = await apiClient.get<ChangeRequest[]>('/ConsumptionChangeRequests/pending')
    return response.data
  },

  // 获取已处理的申请（上级已处理的下级申请）
  async getProcessed(): Promise<ChangeRequest[]> {
    const response = await apiClient.get<ChangeRequest[]>('/ConsumptionChangeRequests/processed')
    return response.data
  },

  // 获取本单位的申请
  async getMy(): Promise<ChangeRequest[]> {
    const response = await apiClient.get<ChangeRequest[]>('/ConsumptionChangeRequests/my')
    return response.data
  },

  // 处理申请
  async process(id: number, data: { approved: boolean; comments?: string }): Promise<{ message: string }> {
    const response = await apiClient.post<{ message: string }>(`/ConsumptionChangeRequests/${id}/process`, data)
    return response.data
  },

  // 修改消耗记录
  async modify(id: number, data: { newAmount: number; newRemarks?: string }): Promise<{ message: string }> {
    const response = await apiClient.post<{ message: string }>(`/ConsumptionChangeRequests/${id}/modify`, data)
    return response.data
  },

  // 检查是否有待处理的申请
  async checkPending(consumptionReportId: number): Promise<{ hasPendingRequest: boolean }> {
    const response = await apiClient.get<{ hasPendingRequest: boolean }>(`/ConsumptionChangeRequests/check/${consumptionReportId}`)
    return response.data
  }
}
