import { ReconciliationStatus, ReconciliationData } from '../services/finance/reconciliationService';

export interface Reconciliation {
  id: string;
  tenantId: string;
  shopId: string;
  platform: string;
  periodStart: Date;
  periodEnd: Date;
  expectedAmount: number;
  actualAmount: number;
  difference: number;
  status: ReconciliationStatus;
  exceptionDetails: string;
  resolutionAction?: string;
  traceId: string;
  taskId: string;
  businessType: 'TOC' | 'TOB';
  createdAt: Date;
  updatedAt: Date;
}

export interface ReconciliationFilter {
  tenantId: string;
  shopId: string;
  status?: ReconciliationStatus;
  platform?: string;
  startDate?: Date;
  endDate?: Date;
  businessType?: 'TOC' | 'TOB';
}

export interface ReconciliationStats {
  total: number;
  completed: number;
  exception: number;
  resolved: number;
  pending: number;
  processing: number;
  totalAmount: number;
  totalDifference: number;
}

export class ReconciliationModel {
  /**
   * 转换数据为Reconciliation类型
   */
  static fromData(data: any): Reconciliation {
    return {
      id: data.id,
      tenantId: data.tenantId,
      shopId: data.shopId,
      platform: data.platform,
      periodStart: new Date(data.periodStart),
      periodEnd: new Date(data.periodEnd),
      expectedAmount: parseFloat(data.expectedAmount),
      actualAmount: parseFloat(data.actualAmount),
      difference: parseFloat(data.difference),
      status: data.status as ReconciliationStatus,
      exceptionDetails: data.exceptionDetails || '',
      resolutionAction: data.resolutionAction,
      traceId: data.traceId,
      taskId: data.taskId,
      businessType: data.businessType as 'TOC' | 'TOB',
      createdAt: new Date(data.createdAt),
      updatedAt: new Date(data.updatedAt)
    };
  }

  /**
   * 验证Reconciliation数据
   */
  static validate(data: Partial<Reconciliation>): boolean {
    return !!(data.tenantId && data.shopId && data.platform && data.periodStart && data.periodEnd && 
      typeof data.expectedAmount === 'number' && typeof data.actualAmount === 'number' && 
      data.traceId && data.taskId && data.businessType);
  }

  /**
   * 生成对账ID
   */
  static generateId(): string {
    return `reconciliation_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  /**
   * 计算差异金额
   */
  static calculateDifference(expectedAmount: number, actualAmount: number): number {
    return expectedAmount - actualAmount;
  }

  /**
   * 确定对账状态
   */
  static determineStatus(difference: number): ReconciliationStatus {
    return Math.abs(difference) < 0.01 ? ReconciliationStatus.COMPLETED : ReconciliationStatus.EXCEPTION;
  }

  /**
   * 生成异常详情
   */
  static generateExceptionDetails(expectedAmount: number, actualAmount: number, difference: number): string {
    return `Amount mismatch: expected ${expectedAmount.toFixed(2)}, actual ${actualAmount.toFixed(2)}, difference ${difference.toFixed(2)}`;
  }
}
