import { PaymentStatus, PaymentMethod, PaymentType, PaymentData } from '../services/core/PaymentService';

export interface Payment {
  id: string;
  tenantId: string;
  shopId: string;
  amount: number;
  currency: string;
  method: PaymentMethod;
  status: PaymentStatus;
  type: PaymentType;
  relatedId: string;
  transactionId: string;
  refundId?: string;
  refundReason?: string;
  traceId: string;
  taskId: string;
  businessType: 'TOC' | 'TOB';
  createdAt: Date;
  updatedAt: Date;
}

export interface PaymentFilter {
  tenantId: string;
  shopId: string;
  status?: PaymentStatus;
  type?: PaymentType;
  method?: PaymentMethod;
  startDate?: Date;
  endDate?: Date;
  businessType?: 'TOC' | 'TOB';
  minAmount?: number;
  maxAmount?: number;
}

export interface PaymentStats {
  total: number;
  completed: number;
  pending: number;
  failed: number;
  refunded: number;
  processing: number;
  totalAmount: number;
  completedAmount: number;
  refundedAmount: number;
  averageAmount: number;
  successRate: number;
  refundRate: number;
}

export class PaymentModel {
  /**
   * 转换数据为Payment类型
   */
  static fromData(data: any): Payment {
    return {
      id: data.id,
      tenantId: data.tenantId,
      shopId: data.shopId,
      amount: parseFloat(data.amount),
      currency: data.currency,
      method: data.method as PaymentMethod,
      status: data.status as PaymentStatus,
      type: data.type as PaymentType,
      relatedId: data.relatedId,
      transactionId: data.transactionId,
      refundId: data.refundId,
      refundReason: data.refundReason,
      traceId: data.traceId,
      taskId: data.taskId,
      businessType: data.businessType as 'TOC' | 'TOB',
      createdAt: new Date(data.createdAt),
      updatedAt: new Date(data.updatedAt)
    };
  }

  /**
   * 验证Payment数据
   */
  static validate(data: Partial<Payment>): boolean {
    return !!(data.tenantId && data.shopId && typeof data.amount === 'number' && 
      data.currency && data.method && data.type && data.relatedId && 
      data.traceId && data.taskId && data.businessType);
  }

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

  /**
   * 生成交易ID
   */
  static generateTransactionId(): string {
    return `trans_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  /**
   * 生成退款ID
   */
  static generateRefundId(): string {
    return `refund_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  /**
   * 验证支付金额
   */
  static validateAmount(amount: number): boolean {
    return amount > 0 && amount <= 1000000;
  }

  /**
   * 验证货币代码
   */
  static validateCurrency(currency: string): boolean {
    const validCurrencies = ['USD', 'CNY', 'EUR', 'GBP', 'JPY', 'AUD', 'CAD', 'HKD', 'SGD'];
    return validCurrencies.includes(currency);
  }

  /**
   * 计算支付统计信息
   */
  static calculateStats(payments: Payment[]): PaymentStats {
    const total = payments.length;
    const completed = payments.filter(p => p.status === PaymentStatus.COMPLETED).length;
    const pending = payments.filter(p => p.status === PaymentStatus.PENDING).length;
    const failed = payments.filter(p => p.status === PaymentStatus.FAILED).length;
    const refunded = payments.filter(p => p.status === PaymentStatus.REFUNDED).length;
    const processing = payments.filter(p => p.status === PaymentStatus.PROCESSING).length;
    
    const totalAmount = payments.reduce((sum, p) => sum + p.amount, 0);
    const completedAmount = payments.filter(p => p.status === PaymentStatus.COMPLETED).reduce((sum, p) => sum + p.amount, 0);
    const refundedAmount = payments.filter(p => p.status === PaymentStatus.REFUNDED).reduce((sum, p) => sum + p.amount, 0);
    const averageAmount = total > 0 ? totalAmount / total : 0;
    const successRate = total > 0 ? (completed / total) * 100 : 0;
    const refundRate = completed > 0 ? (refunded / completed) * 100 : 0;
    
    return {
      total,
      completed,
      pending,
      failed,
      refunded,
      processing,
      totalAmount,
      completedAmount,
      refundedAmount,
      averageAmount,
      successRate,
      refundRate
    };
  }

  /**
   * 格式化支付金额
   */
  static formatAmount(amount: number, currency: string): string {
    const formatter = new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: currency,
      minimumFractionDigits: 2,
      maximumFractionDigits: 2
    });
    return formatter.format(amount);
  }

  /**
   * 获取支付状态的显示文本
   */
  static getStatusText(status: PaymentStatus): string {
    const statusMap: Record<PaymentStatus, string> = {
      [PaymentStatus.PENDING]: '待处理',
      [PaymentStatus.COMPLETED]: '已完成',
      [PaymentStatus.FAILED]: '失败',
      [PaymentStatus.REFUNDED]: '已退款',
      [PaymentStatus.PROCESSING]: '处理中'
    };
    return statusMap[status] || status;
  }

  /**
   * 获取支付方式的显示文本
   */
  static getMethodText(method: PaymentMethod): string {
    const methodMap: Record<PaymentMethod, string> = {
      [PaymentMethod.CREDIT_CARD]: '信用卡',
      [PaymentMethod.PAYPAL]: 'PayPal',
      [PaymentMethod.BANK_TRANSFER]: '银行转账',
      [PaymentMethod.ALIPAY]: '支付宝',
      [PaymentMethod.WECHAT_PAY]: '微信支付'
    };
    return methodMap[method] || method;
  }

  /**
   * 获取支付类型的显示文本
   */
  static getTypeText(type: PaymentType): string {
    const typeMap: Record<PaymentType, string> = {
      [PaymentType.FEATURE]: '功能',
      [PaymentType.ORDER]: '订单',
      [PaymentType.SUBSCRIPTION]: '订阅',
      [PaymentType.REFUND]: '退款'
    };
    return typeMap[type] || type;
  }

  /**
   * 检查支付是否可退款
   */
  static canRefund(status: PaymentStatus): boolean {
    return status === PaymentStatus.COMPLETED;
  }

  /**
   * 检查支付是否已完成
   */
  static isCompleted(status: PaymentStatus): boolean {
    return status === PaymentStatus.COMPLETED;
  }

  /**
   * 检查支付是否失败
   */
  static isFailed(status: PaymentStatus): boolean {
    return status === PaymentStatus.FAILED;
  }

  /**
   * 检查支付是否处于处理中
   */
  static isProcessing(status: PaymentStatus): boolean {
    return status === PaymentStatus.PROCESSING;
  }

  /**
   * 检查支付是否处于待处理状态
   */
  static isPending(status: PaymentStatus): boolean {
    return status === PaymentStatus.PENDING;
  }

  /**
   * 检查支付是否已退款
   */
  static isRefunded(status: PaymentStatus): boolean {
    return status === PaymentStatus.REFUNDED;
  }
}
