import { Knex } from 'knex';
import { db } from '../database';

export class BlacklistAI {
  /**
   * 智能识别恶意买家
   * @param params 识别参数
   * @param traceInfo 追踪信息
   * @returns 识别结果
   */
  public static async identifyMaliciousBuyers(
    params: {
      buyerData: Array<{
        buyerId: string;
        buyerName: string;
        orderHistory: Array<{
          orderId: string;
          orderTime: string;
          amount: number;
          status: string;
          returnStatus?: string;
          refundStatus?: string;
        }>;
        behaviorData: Array<{
          type: string;
          timestamp: string;
          details: any;
        }>;
      }>;
      threshold?: number;
    },
    traceInfo: {
      tenantId: string;
      shopId: string;
      taskId: string;
      traceId: string;
      businessType: 'TOC' | 'TOB';
    }
  ): Promise<{
    timestamp: string;
    results: Array<{
      buyerId: string;
      buyerName: string;
      riskScore: number;
      isMalicious: boolean;
      reasons: string[];
      confidence: number;
    }>;
    summary: {
      totalAnalyzed: number;
      maliciousDetected: number;
      averageRiskScore: number;
    };
  }> {
    try {
      const threshold = params.threshold || 70;
      const timestamp = new Date().toISOString();
      const results = [];
      
      for (const buyer of params.buyerData) {
        // 计算风险评分
        const riskScore = this.calculateRiskScore(buyer);
        const isMalicious = riskScore >= threshold;
        const reasons = this.getRiskReasons(buyer, riskScore);
        const confidence = this.calculateConfidence(riskScore, buyer.orderHistory.length);
        
        results.push({
          buyerId: buyer.buyerId,
          buyerName: buyer.buyerName,
          riskScore,
          isMalicious,
          reasons,
          confidence,
        });
      }
      
      const summary = {
        totalAnalyzed: results.length,
        maliciousDetected: results.filter(r => r.isMalicious).length,
        averageRiskScore: results.reduce((sum, r) => sum + r.riskScore, 0) / results.length || 0,
      };
      
      return {
        timestamp,
        results,
        summary,
      };
    } catch (error) {
      console.error('Error identifying malicious buyers:', error);
      throw new Error('Failed to identify malicious buyers');
    }
  }

  /**
   * 计算买家风险评分
   * @param buyer 买家数据
   * @returns 风险评分
   */
  private static calculateRiskScore(buyer: {
    orderHistory: Array<{
      orderId: string;
      orderTime: string;
      amount: number;
      status: string;
      returnStatus?: string;
      refundStatus?: string;
    }>;
    behaviorData: Array<{
      type: string;
      timestamp: string;
      details: any;
    }>;
  }): number {
    let score = 0;
    
    // 分析订单历史
    const totalOrders = buyer.orderHistory.length;
    const returnOrders = buyer.orderHistory.filter(o => o.returnStatus === 'completed').length;
    const refundOrders = buyer.orderHistory.filter(o => o.refundStatus === 'completed').length;
    const cancelledOrders = buyer.orderHistory.filter(o => o.status === 'cancelled').length;
    
    // 退货率
    if (totalOrders > 0) {
      const returnRate = returnOrders / totalOrders;
      score += returnRate * 30;
      
      const refundRate = refundOrders / totalOrders;
      score += refundRate * 25;
      
      const cancellationRate = cancelledOrders / totalOrders;
      score += cancellationRate * 20;
    }
    
    // 分析行为数据
    const suspiciousBehaviors = buyer.behaviorData.filter(b => 
      ['rapid_ordering', 'multiple_returns', 'dispute_initiation', 'suspicious_ip'].includes(b.type)
    );
    score += suspiciousBehaviors.length * 5;
    
    // 限制评分范围
    return Math.min(Math.max(score, 0), 100);
  }

  /**
   * 获取风险原因
   * @param buyer 买家数据
   * @param riskScore 风险评分
   * @returns 风险原因列表
   */
  private static getRiskReasons(buyer: {
    orderHistory: Array<{
      orderId: string;
      orderTime: string;
      amount: number;
      status: string;
      returnStatus?: string;
      refundStatus?: string;
    }>;
    behaviorData: Array<{
      type: string;
      timestamp: string;
      details: any;
    }>;
  }, riskScore: number): string[] {
    const reasons = [];
    
    const totalOrders = buyer.orderHistory.length;
    const returnOrders = buyer.orderHistory.filter(o => o.returnStatus === 'completed').length;
    const refundOrders = buyer.orderHistory.filter(o => o.refundStatus === 'completed').length;
    const cancelledOrders = buyer.orderHistory.filter(o => o.status === 'cancelled').length;
    
    if (totalOrders > 0) {
      const returnRate = returnOrders / totalOrders;
      if (returnRate > 0.3) {
        reasons.push(`高退货率: ${(returnRate * 100).toFixed(1)}%`);
      }
      
      const refundRate = refundOrders / totalOrders;
      if (refundRate > 0.2) {
        reasons.push(`高退款率: ${(refundRate * 100).toFixed(1)}%`);
      }
      
      const cancellationRate = cancelledOrders / totalOrders;
      if (cancellationRate > 0.25) {
        reasons.push(`高取消率: ${(cancellationRate * 100).toFixed(1)}%`);
      }
    }
    
    const suspiciousBehaviors = buyer.behaviorData.filter(b => 
      ['rapid_ordering', 'multiple_returns', 'dispute_initiation', 'suspicious_ip'].includes(b.type)
    );
    if (suspiciousBehaviors.length > 0) {
      reasons.push(`可疑行为: ${suspiciousBehaviors.length} 次`);
    }
    
    if (reasons.length === 0) {
      reasons.push('无明显风险因素');
    }
    
    return reasons;
  }

  /**
   * 计算置信度
   * @param riskScore 风险评分
   * @param orderCount 订单数量
   * @returns 置信度
   */
  private static calculateConfidence(riskScore: number, orderCount: number): number {
    // 基于风险评分和订单数量计算置信度
    let baseConfidence = 50;
    
    // 风险评分越高，置信度越高
    if (riskScore > 80) {
      baseConfidence += 30;
    } else if (riskScore > 60) {
      baseConfidence += 20;
    } else if (riskScore > 40) {
      baseConfidence += 10;
    }
    
    // 订单数量越多，置信度越高
    if (orderCount > 10) {
      baseConfidence += 15;
    } else if (orderCount > 5) {
      baseConfidence += 10;
    } else if (orderCount > 2) {
      baseConfidence += 5;
    }
    
    // 限制置信度范围
    return Math.min(Math.max(baseConfidence, 0), 100);
  }

  /**
   * 批量处理买家数据
   * @param params 批量处理参数
   * @param traceInfo 追踪信息
   * @returns 处理结果
   */
  public static async batchProcessBuyers(
    params: {
      buyerIds: string[];
      timeRange?: { start: string; end: string };
    },
    traceInfo: {
      tenantId: string;
      shopId: string;
      taskId: string;
      traceId: string;
      businessType: 'TOC' | 'TOB';
    }
  ): Promise<{
    batchId: string;
    timestamp: string;
    processedCount: number;
    results: Array<{
      buyerId: string;
      riskScore: number;
      isMalicious: boolean;
      confidence: number;
    }>;
  }> {
    try {
      const batchId = `BATCH-${Date.now()}`;
      const timestamp = new Date().toISOString();
      const results = [];
      
      // 模拟批量处理
      for (const buyerId of params.buyerIds) {
        // 模拟买家数据
        const buyerData = {
          buyerId,
          buyerName: `Buyer ${buyerId}`,
          orderHistory: Array.from({ length: Math.floor(Math.random() * 10) + 1 }, (_, i) => ({
            orderId: `ORDER-${buyerId}-${i}`,
            orderTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
            amount: Math.random() * 1000 + 100,
            status: ['completed', 'cancelled'][Math.floor(Math.random() * 2)],
            returnStatus: Math.random() > 0.7 ? 'completed' : undefined,
            refundStatus: Math.random() > 0.8 ? 'completed' : undefined,
          })),
          behaviorData: Array.from({ length: Math.floor(Math.random() * 5) + 1 }, (_, i) => ({
            type: ['normal', 'rapid_ordering', 'multiple_returns', 'dispute_initiation', 'suspicious_ip'][Math.floor(Math.random() * 5)],
            timestamp: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
            details: {},
          })),
        };
        
        // 计算风险评分
        const riskScore = this.calculateRiskScore(buyerData);
        const isMalicious = riskScore >= 70;
        const confidence = this.calculateConfidence(riskScore, buyerData.orderHistory.length);
        
        results.push({
          buyerId,
          riskScore,
          isMalicious,
          confidence,
        });
      }
      
      return {
        batchId,
        timestamp,
        processedCount: params.buyerIds.length,
        results,
      };
    } catch (error) {
      console.error('Error batch processing buyers:', error);
      throw new Error('Failed to batch process buyers');
    }
  }

  /**
   * 生成恶意买家识别报告
   * @param params 报告参数
   * @param traceInfo 追踪信息
   * @returns 报告数据
   */
  public static async generateIdentificationReport(
    params: {
      timeRange: { start: string; end: string };
      reportType: 'summary' | 'detailed';
    },
    traceInfo: {
      tenantId: string;
      shopId: string;
      taskId: string;
      traceId: string;
      businessType: 'TOC' | 'TOB';
    }
  ): Promise<{
    reportId: string;
    timestamp: string;
    timeRange: { start: string; end: string };
    reportType: string;
    summary: {
      totalAnalyzed: number;
      maliciousDetected: number;
      averageRiskScore: number;
      highestRiskBuyer: { buyerId: string; riskScore: number } | null;
    };
    recommendations: string[];
  }> {
    try {
      const reportId = `REPORT-${Date.now()}`;
      const timestamp = new Date().toISOString();
      
      // 模拟报告数据
      const totalAnalyzed = Math.floor(Math.random() * 100) + 50;
      const maliciousDetected = Math.floor(totalAnalyzed * (Math.random() * 0.3 + 0.05));
      const averageRiskScore = Math.random() * 30 + 40;
      const highestRiskBuyer = {
        buyerId: `BUYER-${Math.floor(Math.random() * 1000)}`,
        riskScore: Math.random() * 30 + 70,
      };
      
      const recommendations = [
        '建议对高风险买家进行人工审核',
        '建议设置订单金额限制对于新买家',
        '建议加强对退货率高的买家的监控',
        '建议优化买家评分系统，纳入更多行为数据',
        '建议定期更新恶意买家识别模型',
      ];
      
      return {
        reportId,
        timestamp,
        timeRange: params.timeRange,
        reportType: params.reportType,
        summary: {
          totalAnalyzed,
          maliciousDetected,
          averageRiskScore,
          highestRiskBuyer,
        },
        recommendations,
      };
    } catch (error) {
      console.error('Error generating identification report:', error);
      throw new Error('Failed to generate identification report');
    }
  }
}
