/**
 * 对账 API 客户端
 * 提供对账批次管理、三账校验、手工补录等功能
 */
import { apiClient } from './client'
import type { PageResponse } from '@/types/api'

/**
 * 对账批次
 */
export interface ReconciliationBatch {
  id: number
  batch_no: string
  physical_account_id: number
  recon_date: string
  total_count: number
  matched_count: number
  mismatch_count: number
  status: ReconciliationStatus
  bank_total?: string
  transit_net?: string
  ledger_total?: string
  three_account_balanced?: boolean
  created_at: string
  completed_at?: string
}

/**
 * 对账批次状态
 */
export type ReconciliationStatus = 'processing' | 'completed' | 'need_review'

/**
 * 对账明细项
 */
export interface ReconciliationItem {
  id: number
  batch_id: number
  system_txn_no?: string
  bank_ref_no?: string
  system_amount?: string
  bank_amount?: string
  diff_amount: string
  status: ReconciliationItemStatus
  remark?: string
  created_at: string
}

/**
 * 对账项状态
 */
export type ReconciliationItemStatus = 
  | 'matched'          // 已匹配
  | 'system_unreached' // 系统未达
  | 'bank_unreached'   // 银行未达
  | 'amount_mismatch'  // 金额不匹配
  | 'adjusted'         // 已调整

/**
 * 三账校验结果
 */
export interface ThreeAccountResult {
  physical_account_id: number
  bank_balance: string
  transit_net: string
  ledger_total: string
  expected_total: string
  difference: string
  is_balanced: boolean
  verified_at: string
}

/**
 * 手工补录
 */
export interface ManualAdjustment {
  id: number
  adjustment_no: string
  related_txn_no?: string
  reconciliation_item_id?: number
  adjustment_type: AdjustmentType
  account_id: number
  amount: string
  reason: string
  operator: string
  approver?: string
  status: AdjustmentStatus
  created_at: string
  approved_at?: string
}

/**
 * 补录类型
 */
export type AdjustmentType = 'add' | 'reverse' | 'modify'

/**
 * 补录状态
 */
export type AdjustmentStatus = 'pending' | 'approved' | 'rejected'

/**
 * 创建对账请求
 */
export interface CreateReconciliationRequest {
  physical_account_id: number
  recon_date: string
}

/**
 * 创建补录请求
 */
export interface CreateAdjustmentRequest {
  related_txn_no?: string
  reconciliation_item_id?: number
  adjustment_type: AdjustmentType
  account_id: number
  amount: string
  reason: string
}

export class ReconciliationAPI {
  // ==================== 核心对账功能 (已对接后端) ====================

  /**
   * 执行对账
   * 对应后端: POST /api/v1/reconciliation/run
   */
  static async runReconciliation(data: CreateReconciliationRequest): Promise<ReconciliationBatch> {
    return apiClient.post('/reconciliation/run', data)
  }

  /**
   * 获取对账批次详情
   * 对应后端: GET /api/v1/reconciliation/batches/:id
   */
  static async getBatch(id: number): Promise<ReconciliationBatch> {
    return apiClient.get(`/reconciliation/batches/${id}`)
  }
  
  /**
   * 获取对账明细
   * 对应后端: GET /api/v1/reconciliation/batches/:id/items
   */
  static async getBatchItems(batchId: number, params?: {
    status?: ReconciliationItemStatus
    page?: number
    page_size?: number
  }): Promise<PageResponse<ReconciliationItem>> {
    return apiClient.get(`/reconciliation/batches/${batchId}/items`, { params })
  }
  
  /**
   * 三账校验
   * 对应后端: GET /api/v1/reconciliation/three-account/:account_id
   */
  static async verifyThreeAccounts(accountId: number): Promise<ThreeAccountResult> {
    return apiClient.get(`/reconciliation/three-account/${accountId}`)
  }
  
  /**
   * 创建手工补录
   * 对应后端: POST /api/v1/reconciliation/adjustments
   */
  static async createAdjustment(data: CreateAdjustmentRequest): Promise<ManualAdjustment> {
    return apiClient.post('/reconciliation/adjustments', data)
  }

  /**
   * 审批补录
   * 对应后端: POST /api/v1/reconciliation/adjustments/:id/approve
   */
  static async approveAdjustment(id: number, approver: string): Promise<ManualAdjustment> {
    return apiClient.post(`/reconciliation/adjustments/${id}/approve`, { approver })
  }

  /**
   * 拒绝补录
   * 对应后端: POST /api/v1/reconciliation/adjustments/:id/reject
   */
  static async rejectAdjustment(id: number, approver: string, reason: string): Promise<ManualAdjustment> {
    return apiClient.post(`/reconciliation/adjustments/${id}/reject`, { approver, reason })
  }

  /**
   * 获取待审批补录列表
   * 对应后端: GET /api/v1/reconciliation/adjustments/pending
   */
  static async getPendingAdjustments(): Promise<ManualAdjustment[]> {
    return apiClient.get('/reconciliation/adjustments/pending')
  }

  // ==================== 扩展功能 (需要后端支持) ====================

  /**
   * 获取对账批次列表 (需要后端扩展)
   * @todo 后端需要添加列表查询端点
   */
  static async getBatches(params?: {
    status?: ReconciliationStatus
    physical_account_id?: number
    start_date?: string
    end_date?: string
    page?: number
    page_size?: number
  }): Promise<PageResponse<ReconciliationBatch>> {
    return apiClient.get('/reconciliation/batches', { params })
  }
  
  /**
   * 获取批次的调整记录 (需要后端扩展)
   * @todo 后端需要添加此端点
   */
  static async getAdjustments(batchId: number): Promise<ManualAdjustment[]> {
    return apiClient.get(`/reconciliation/batches/${batchId}/adjustments`)
  }
  
  /**
   * 对账统计 (需要后端扩展)
   * @todo 后端需要添加此端点
   */
  static async getStats(params: {
    start_date?: string
    end_date?: string
    physical_account_id?: number
  }): Promise<{
    total_batches: number
    success_rate: number
    total_discrepancy: string
    largest_discrepancy: string
  }> {
    return apiClient.get('/reconciliation/stats', { params })
  }
  
  /**
   * 导出对账报告 (需要后端扩展)
   * @todo 后端需要添加此端点
   */
  static async exportReport(batchId: number, format: 'excel' | 'pdf' = 'excel'): Promise<Blob> {
    return apiClient.get(`/reconciliation/batches/${batchId}/export`, { 
      params: { format },
      responseType: 'blob' 
    })
  }

  // ==================== 兼容旧方法 ====================

  /**
   * @deprecated 使用 runReconciliation 替代
   */
  static async createBatch(data: {
    reconDate: string
    accountIds?: number[]
  }): Promise<ReconciliationBatch> {
    return this.runReconciliation({
      physical_account_id: data.accountIds?.[0] || 0,
      recon_date: data.reconDate,
    })
  }

  /**
   * @deprecated 使用 runReconciliation 替代
   */
  static async executeBatch(id: number): Promise<ReconciliationBatch> {
    // 获取批次信息后重新执行对账
    const batch = await this.getBatch(id)
    return this.runReconciliation({
      physical_account_id: batch.physical_account_id,
      recon_date: batch.recon_date,
    })
  }
}

/**
 * 对账状态显示名称映射
 */
export const ReconciliationStatusLabels: Record<ReconciliationStatus, string> = {
  processing: '处理中',
  completed: '已完成',
  need_review: '需要审核',
}

/**
 * 对账项状态显示名称映射
 */
export const ReconciliationItemStatusLabels: Record<ReconciliationItemStatus, string> = {
  matched: '已匹配',
  system_unreached: '系统未达',
  bank_unreached: '银行未达',
  amount_mismatch: '金额不匹配',
  adjusted: '已调整',
}

/**
 * 补录类型显示名称映射
 */
export const AdjustmentTypeLabels: Record<AdjustmentType, string> = {
  add: '补录',
  reverse: '冲销',
  modify: '修改',
}

/**
 * 补录状态显示名称映射
 */
export const AdjustmentStatusLabels: Record<AdjustmentStatus, string> = {
  pending: '待审批',
  approved: '已审批',
  rejected: '已拒绝',
}

export default ReconciliationAPI
