import { logger } from '../utils/logger';

// 退货数据接口
export interface ReturnData {
  return_id: string;
  order_id: string;
  product_id: string;
  sku_id: string;
  return_reason: string;
  return_date: Date;
  return_status: 'PENDING' | 'APPROVED' | 'REJECTED' | 'COMPLETED';
  refund_amount: number;
  return_quantity: number;
  customer_id: string;
  tenant_id: string;
  shop_id: string;
  trace_id: string;
  businessType: 'TOC' | 'TOB';
}

// 商品数据接口
export interface ProductData {
  product_id: string;
  product_name: string;
  category: string;
  brand: string;
  price: number;
  sku_data: {
    sku_id: string;
    sku_attributes: { [key: string]: string };
    sku_price: number;
    sku_stock: number;
  }[];
  tenant_id: string;
  shop_id: string;
}

// 销售数据接口
export interface SalesData {
  order_id: string;
  product_id: string;
  sku_id: string;
  quantity: number;
  sale_price: number;
  sale_date: Date;
  customer_id: string;
  tenant_id: string;
  shop_id: string;
  trace_id: string;
  businessType: 'TOC' | 'TOB';
}

// 退货原因分析结果接口
export interface ReturnReasonAnalysis {
  product_id: string;
  product_name: string;
  total_returns: number;
  return_rate: number;
  reason_distribution: {
    reason: string;
    count: number;
    percentage: number;
  }[];
  top_reasons: string[];
  trend_analysis: {
    period: string;
    return_count: number;
    return_rate: number;
  }[];
  category_comparison: {
    category: string;
    average_return_rate: number;
    comparison: 'BETTER' | 'WORSE' | 'SIMILAR';
  }[];
  timestamp: Date;
}

// 智能优化建议接口
export interface ReturnOptimizationSuggestion {
  product_id: string;
  product_name: string;
  current_return_rate: number;
  target_return_rate: number;
  optimization_score: number;
  suggestions: {
    type: string;
    description: string;
    impact: 'HIGH' | 'MEDIUM' | 'LOW';
    implementation_effort: 'HIGH' | 'MEDIUM' | 'LOW';
    expected_improvement: number;
  }[];
  estimated_savings: number;
  implementation_plan: {
    phase: string;
    tasks: string[];
  }[];
  timestamp: Date;
}

// 退货效果分析接口
export interface ReturnEffectivenessAnalysis {
  analysis_period: {
    start_date: Date;
    end_date: Date;
  };
  overall_metrics: {
    total_returns: number;
    total_sales: number;
    overall_return_rate: number;
    average_refund_amount: number;
    total_refund_amount: number;
  };
  product_level_analysis: {
    product_id: string;
    product_name: string;
    return_rate: number;
    sales_count: number;
    return_count: number;
    rank: number;
  }[];
  reason_analysis: {
    reason: string;
    count: number;
    percentage: number;
    average_refund_amount: number;
  }[];
  trend_analysis: {
    period: string;
    return_rate: number;
    sales_count: number;
    return_count: number;
  }[];
  savings_analysis: {
    prevented_returns: number;
    estimated_savings: number;
    improvement_percentage: number;
  };
  timestamp: Date;
}

// 退货风险评估接口
export interface ReturnRiskAssessment {
  product_id: string;
  product_name: string;
  risk_score: number;
  risk_level: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
  risk_factors: {
    factor: string;
    score: number;
    description: string;
  }[];
  early_warning: boolean;
  recommended_actions: string[];
  timestamp: Date;
}

export default class ReturnAnalysisService {
  private static instance: ReturnAnalysisService;

  static getInstance(): ReturnAnalysisService {
    if (!ReturnAnalysisService.instance) {
      ReturnAnalysisService.instance = new ReturnAnalysisService();
    }
    return ReturnAnalysisService.instance;
  }

  /**
   * AI-HR001: 退货原因分析
   * 基于退货数据和商品数据进行退货原因分析
   */
  async analyzeReturnReasons(
    returnData: ReturnData[],
    productData: ProductData,
    salesData: SalesData[],
    trace_id: string
  ): Promise<ReturnReasonAnalysis> {
    try {
      logger.info(`[ReturnAnalysisService] Analyzing return reasons: productId=${productData.product_id}, traceId=${trace_id}`);

      // 过滤该商品的退货数据
      const productReturns = returnData.filter(r => r.product_id === productData.product_id);
      const totalReturns = productReturns.length;

      // 计算销售数量
      const productSales = salesData.filter(s => s.product_id === productData.product_id);
      const totalSales = productSales.length;
      const returnRate = totalSales > 0 ? (totalReturns / totalSales) * 100 : 0;

      // 分析退货原因分布
      const reasonDistribution = this.analyzeReasonDistribution(productReturns);

      // 提取 top 原因
      const topReasons = reasonDistribution
        .sort((a, b) => b.count - a.count)
        .slice(0, 3)
        .map(r => r.reason);

      // 趋势分析
      const trendAnalysis = this.analyzeReturnTrend(productReturns);

      // 类别对比
      const categoryComparison = this.compareWithCategory(productData.category, returnRate, returnData, salesData);

      logger.info(`[ReturnAnalysisService] Return reason analysis completed: productId=${productData.product_id}, returnRate=${returnRate.toFixed(2)}%, traceId=${trace_id}`);

      return {
        product_id: productData.product_id,
        product_name: productData.product_name,
        total_returns: totalReturns,
        return_rate: returnRate,
        reason_distribution: reasonDistribution,
        top_reasons: topReasons,
        trend_analysis: trendAnalysis,
        category_comparison: categoryComparison,
        timestamp: new Date()
      };
    } catch (error: any) {
      logger.error(`[ReturnAnalysisService] Failed to analyze return reasons: ${error.message}, traceId=${trace_id}`);
      return {
        product_id: productData.product_id,
        product_name: productData.product_name,
        total_returns: 0,
        return_rate: 0,
        reason_distribution: [],
        top_reasons: [],
        trend_analysis: [],
        category_comparison: [],
        timestamp: new Date()
      };
    }
  }

  /**
   * AI-HR002: 智能优化建议
   * 基于退货分析结果生成智能优化建议
   */
  async generateOptimizationSuggestions(
    returnAnalysis: ReturnReasonAnalysis,
    productData: ProductData,
    trace_id: string
  ): Promise<ReturnOptimizationSuggestion> {
    try {
      logger.info(`[ReturnAnalysisService] Generating optimization suggestions: productId=${returnAnalysis.product_id}, traceId=${trace_id}`);

      // 计算目标退货率
      const targetReturnRate = Math.max(0, returnAnalysis.return_rate * 0.8); // 目标降低 20%

      // 生成优化建议
      const suggestions = this.generateSuggestions(returnAnalysis, productData);

      // 计算优化评分
      const optimizationScore = this.calculateOptimizationScore(suggestions);

      // 估算节省
      const estimatedSavings = this.estimateSavings(returnAnalysis, suggestions);

      // 生成实施计划
      const implementationPlan = this.generateImplementationPlan(suggestions);

      logger.info(`[ReturnAnalysisService] Optimization suggestions generated: productId=${returnAnalysis.product_id}, score=${optimizationScore}, traceId=${trace_id}`);

      return {
        product_id: returnAnalysis.product_id,
        product_name: returnAnalysis.product_name,
        current_return_rate: returnAnalysis.return_rate,
        target_return_rate: targetReturnRate,
        optimization_score: optimizationScore,
        suggestions: suggestions,
        estimated_savings: estimatedSavings,
        implementation_plan: implementationPlan,
        timestamp: new Date()
      };
    } catch (error: any) {
      logger.error(`[ReturnAnalysisService] Failed to generate optimization suggestions: ${error.message}, traceId=${trace_id}`);
      return {
        product_id: returnAnalysis.product_id,
        product_name: returnAnalysis.product_name,
        current_return_rate: returnAnalysis.return_rate,
        target_return_rate: 0,
        optimization_score: 0,
        suggestions: [],
        estimated_savings: 0,
        implementation_plan: [],
        timestamp: new Date()
      };
    }
  }

  /**
   * DT-HR002: 退货效果分析
   * 基于退货数据和销售数据进行退货效果分析
   */
  async analyzeReturnEffectiveness(
    returnData: ReturnData[],
    salesData: SalesData[],
    startDate: Date,
    endDate: Date,
    trace_id: string
  ): Promise<ReturnEffectivenessAnalysis> {
    try {
      logger.info(`[ReturnAnalysisService] Analyzing return effectiveness: period=${startDate.toISOString()} to ${endDate.toISOString()}, traceId=${trace_id}`);

      // 过滤时间范围内的数据
      const filteredReturns = returnData.filter(r => 
        r.return_date >= startDate && r.return_date <= endDate
      );
      const filteredSales = salesData.filter(s => 
        s.sale_date >= startDate && s.sale_date <= endDate
      );

      // 计算总体指标
      const overallMetrics = {
        total_returns: filteredReturns.length,
        total_sales: filteredSales.length,
        overall_return_rate: filteredSales.length > 0 ? (filteredReturns.length / filteredSales.length) * 100 : 0,
        average_refund_amount: filteredReturns.length > 0 ? 
          filteredReturns.reduce((sum, r) => sum + r.refund_amount, 0) / filteredReturns.length : 0,
        total_refund_amount: filteredReturns.reduce((sum, r) => sum + r.refund_amount, 0)
      };

      // 商品级分析
      const productLevelAnalysis = this.analyzeProductLevel(filteredReturns, filteredSales);

      // 原因分析
      const reasonAnalysis = this.analyzeReasons(filteredReturns);

      // 趋势分析
      const trendAnalysis = this.analyzeEffectivenessTrend(filteredReturns, filteredSales, startDate, endDate);

      // 节省分析
      const savingsAnalysis = this.analyzeSavings(filteredReturns, trace_id);

      logger.info(`[ReturnAnalysisService] Return effectiveness analysis completed: totalReturns=${overallMetrics.total_returns}, returnRate=${overallMetrics.overall_return_rate.toFixed(2)}%, traceId=${trace_id}`);

      return {
        analysis_period: {
          start_date: startDate,
          end_date: endDate
        },
        overall_metrics: overallMetrics,
        product_level_analysis: productLevelAnalysis,
        reason_analysis: reasonAnalysis,
        trend_analysis: trendAnalysis,
        savings_analysis: savingsAnalysis,
        timestamp: new Date()
      };
    } catch (error: any) {
      logger.error(`[ReturnAnalysisService] Failed to analyze return effectiveness: ${error.message}, traceId=${trace_id}`);
      return {
        analysis_period: {
          start_date: startDate,
          end_date: endDate
        },
        overall_metrics: {
          total_returns: 0,
          total_sales: 0,
          overall_return_rate: 0,
          average_refund_amount: 0,
          total_refund_amount: 0
        },
        product_level_analysis: [],
        reason_analysis: [],
        trend_analysis: [],
        savings_analysis: {
          prevented_returns: 0,
          estimated_savings: 0,
          improvement_percentage: 0
        },
        timestamp: new Date()
      };
    }
  }

  /**
   * 评估退货风险
   */
  async assessReturnRisk(
    productData: ProductData,
    returnData: ReturnData[],
    salesData: SalesData[],
    trace_id: string
  ): Promise<ReturnRiskAssessment> {
    try {
      logger.info(`[ReturnAnalysisService] Assessing return risk: productId=${productData.product_id}, traceId=${trace_id}`);

      // 计算退货率
      const productReturns = returnData.filter(r => r.product_id === productData.product_id);
      const productSales = salesData.filter(s => s.product_id === productData.product_id);
      const returnRate = productSales.length > 0 ? (productReturns.length / productSales.length) * 100 : 0;

      // 分析风险因素
      const riskFactors = this.analyzeRiskFactors(productData, productReturns, returnRate);

      // 计算风险评分
      const riskScore = riskFactors.reduce((sum, factor) => sum + factor.score, 0) / riskFactors.length;

      // 确定风险等级
      const riskLevel = this.getRiskLevel(riskScore);

      // 生成建议操作
      const recommendedActions = this.generateRiskActions(riskLevel, riskFactors);

      // 检查是否需要预警
      const earlyWarning = riskLevel === 'HIGH' || riskLevel === 'CRITICAL';

      logger.info(`[ReturnAnalysisService] Return risk assessment completed: productId=${productData.product_id}, riskScore=${riskScore.toFixed(2)}, riskLevel=${riskLevel}, traceId=${trace_id}`);

      return {
        product_id: productData.product_id,
        product_name: productData.product_name,
        risk_score: riskScore,
        risk_level: riskLevel,
        risk_factors: riskFactors,
        early_warning: earlyWarning,
        recommended_actions: recommendedActions,
        timestamp: new Date()
      };
    } catch (error: any) {
      logger.error(`[ReturnAnalysisService] Failed to assess return risk: ${error.message}, traceId=${trace_id}`);
      return {
        product_id: productData.product_id,
        product_name: productData.product_name,
        risk_score: 0,
        risk_level: 'LOW',
        risk_factors: [],
        early_warning: false,
        recommended_actions: [],
        timestamp: new Date()
      };
    }
  }

  // 辅助方法
  private analyzeReasonDistribution(returns: ReturnData[]) {
    const reasonCounts: { [reason: string]: number } = {};

    returns.forEach(r => {
      reasonCounts[r.return_reason] = (reasonCounts[r.return_reason] || 0) + 1;
    });

    const total = returns.length;
    return Object.entries(reasonCounts).map(([reason, count]) => ({
      reason,
      count,
      percentage: total > 0 ? (count / total) * 100 : 0
    }));
  }

  private analyzeReturnTrend(returns: ReturnData[]) {
    const monthlyData: { [month: string]: { count: number; rate: number } } = {};

    // 按月分组
    returns.forEach(r => {
      const month = r.return_date.toISOString().substring(0, 7); // YYYY-MM
      monthlyData[month] = {
        count: (monthlyData[month]?.count || 0) + 1,
        rate: 0 // 后续计算
      };
    });

    // 转换为数组并排序
    return Object.entries(monthlyData)
      .sort(([a], [b]) => a.localeCompare(b))
      .map(([period, data]) => ({
        period,
        return_count: data.count,
        return_rate: data.rate
      }));
  }

  private compareWithCategory(category: string, productReturnRate: number, allReturns: ReturnData[], allSales: SalesData[]) {
    // 计算该类别的平均退货率
    const categoryProducts = new Set<string>();
    allSales.forEach(s => {
      // 假设这里可以获取商品类别，实际应用中可能需要从商品数据中获取
      categoryProducts.add(s.product_id);
    });

    const categoryReturns = allReturns.filter(r => categoryProducts.has(r.product_id));
    const categorySales = allSales.filter(s => categoryProducts.has(s.product_id));
    const categoryReturnRate = categorySales.length > 0 ? (categoryReturns.length / categorySales.length) * 100 : 0;

    let comparison: 'BETTER' | 'WORSE' | 'SIMILAR';
    if (productReturnRate < categoryReturnRate * 0.8) {
      comparison = 'BETTER';
    } else if (productReturnRate > categoryReturnRate * 1.2) {
      comparison = 'WORSE';
    } else {
      comparison = 'SIMILAR';
    }

    return [{
      category,
      average_return_rate: categoryReturnRate,
      comparison
    }];
  }

  private generateSuggestions(analysis: ReturnReasonAnalysis, product: ProductData) {
    const suggestions = [];

    // 基于退货原因生成建议
    const topReasons = analysis.top_reasons;
    if (topReasons.includes('质量问题')) {
      suggestions.push({
        type: '质量控制',
        description: '加强产品质量检测，确保发货前产品符合标准',
        impact: 'HIGH' as const,
        implementation_effort: 'MEDIUM' as const,
        expected_improvement: 30
      });
    }

    if (topReasons.includes('尺寸不符')) {
      suggestions.push({
        type: '产品信息',
        description: '提供更详细的尺寸表和测量指南',
        impact: 'MEDIUM' as const,
        implementation_effort: 'LOW' as const,
        expected_improvement: 20
      });
    }

    if (topReasons.includes('与描述不符')) {
      suggestions.push({
        type: '产品描述',
        description: '更新产品描述和图片，确保与实际产品一致',
        impact: 'HIGH' as const,
        implementation_effort: 'MEDIUM' as const,
        expected_improvement: 25
      });
    }

    // 基于退货率生成建议
    if (analysis.return_rate > 15) {
      suggestions.push({
        type: '定价策略',
        description: '考虑调整产品价格，反映产品价值',
        impact: 'MEDIUM' as const,
        implementation_effort: 'LOW' as const,
        expected_improvement: 15
      });

      suggestions.push({
        type: '营销调整',
        description: '优化产品营销信息，设置更合理的客户期望',
        impact: 'MEDIUM' as const,
        implementation_effort: 'MEDIUM' as const,
        expected_improvement: 20
      });
    }

    // 通用建议
    suggestions.push({
      type: '客户服务',
      description: '加强售前咨询，帮助客户做出更合适的购买决策',
      impact: 'LOW' as const,
      implementation_effort: 'LOW' as const,
      expected_improvement: 10
    });

    return suggestions;
  }

  private calculateOptimizationScore(suggestions: any[]) {
    if (suggestions.length === 0) return 0;

    const totalImpact = suggestions.reduce((sum, s) => {
      switch (s.impact) {
        case 'HIGH': return sum + 3;
        case 'MEDIUM': return sum + 2;
        case 'LOW': return sum + 1;
        default: return sum;
      }
    }, 0);

    const totalImprovement = suggestions.reduce((sum, s) => sum + s.expected_improvement, 0);

    return (totalImpact * 0.4 + totalImprovement * 0.6) / (suggestions.length * 5) * 100;
  }

  private estimateSavings(analysis: ReturnReasonAnalysis, suggestions: any[]) {
    const averageRefund = 50; // 假设平均退款金额
    const totalSales = 1000; // 假设总销售额
    const improvementRate = suggestions.reduce((sum, s) => sum + s.expected_improvement, 0) / suggestions.length / 100;

    const currentReturns = (analysis.return_rate / 100) * totalSales;
    const expectedReturns = currentReturns * (1 - improvementRate);
    const preventedReturns = currentReturns - expectedReturns;

    return preventedReturns * averageRefund;
  }

  private generateImplementationPlan(suggestions: any[]) {
    const plan = [
      {
        phase: '短期（1-2周）',
        tasks: []
      },
      {
        phase: '中期（3-4周）',
        tasks: []
      },
      {
        phase: '长期（1-2个月）',
        tasks: []
      }
    ];

    suggestions.forEach(s => {
      if (s.implementation_effort === 'LOW') {
        plan[0].tasks.push(s.description);
      } else if (s.implementation_effort === 'MEDIUM') {
        plan[1].tasks.push(s.description);
      } else {
        plan[2].tasks.push(s.description);
      }
    });

    return plan;
  }

  private analyzeProductLevel(returns: ReturnData[], sales: SalesData[]) {
    const productStats: { [productId: string]: { returns: number; sales: number; name: string } } = {};

    // 统计每个商品的退货数
    returns.forEach(r => {
      if (!productStats[r.product_id]) {
        productStats[r.product_id] = { returns: 0, sales: 0, name: '' };
      }
      productStats[r.product_id].returns++;
    });

    // 统计每个商品的销售数
    sales.forEach(s => {
      if (!productStats[s.product_id]) {
        productStats[s.product_id] = { returns: 0, sales: 0, name: '' };
      }
      productStats[s.product_id].sales++;
    });

    // 转换为数组并计算退货率
    return Object.entries(productStats)
      .map(([productId, stats]) => ({
        product_id: productId,
        product_name: stats.name,
        return_rate: stats.sales > 0 ? (stats.returns / stats.sales) * 100 : 0,
        sales_count: stats.sales,
        return_count: stats.returns,
        rank: 0 // 后续计算
      }))
      .sort((a, b) => b.return_rate - a.return_rate)
      .map((item, index) => ({
        ...item,
        rank: index + 1
      }));
  }

  private analyzeReasons(returns: ReturnData[]) {
    const reasonStats: { [reason: string]: { count: number; totalAmount: number } } = {};

    returns.forEach(r => {
      if (!reasonStats[r.return_reason]) {
        reasonStats[r.return_reason] = { count: 0, totalAmount: 0 };
      }
      reasonStats[r.return_reason].count++;
      reasonStats[r.return_reason].totalAmount += r.refund_amount;
    });

    const total = returns.length;
    return Object.entries(reasonStats)
      .map(([reason, stats]) => ({
        reason,
        count: stats.count,
        percentage: total > 0 ? (stats.count / total) * 100 : 0,
        average_refund_amount: stats.count > 0 ? stats.totalAmount / stats.count : 0
      }))
      .sort((a, b) => b.count - a.count);
  }

  private analyzeEffectivenessTrend(returns: ReturnData[], sales: SalesData[], startDate: Date, endDate: Date) {
    const trendData: { [period: string]: { returns: number; sales: number } } = {};

    // 按周分组
    const currentDate = new Date(startDate);
    while (currentDate <= endDate) {
      const weekStart = new Date(currentDate);
      weekStart.setDate(weekStart.getDate() - weekStart.getDay());
      const period = weekStart.toISOString().substring(0, 10);
      trendData[period] = { returns: 0, sales: 0 };
      currentDate.setDate(currentDate.getDate() + 7);
    }

    // 统计每周数据
    returns.forEach(r => {
      const weekStart = new Date(r.return_date);
      weekStart.setDate(weekStart.getDate() - weekStart.getDay());
      const period = weekStart.toISOString().substring(0, 10);
      if (trendData[period]) {
        trendData[period].returns++;
      }
    });

    sales.forEach(s => {
      const weekStart = new Date(s.sale_date);
      weekStart.setDate(weekStart.getDate() - weekStart.getDay());
      const period = weekStart.toISOString().substring(0, 10);
      if (trendData[period]) {
        trendData[period].sales++;
      }
    });

    return Object.entries(trendData)
      .sort(([a], [b]) => a.localeCompare(b))
      .map(([period, data]) => ({
        period,
        return_rate: data.sales > 0 ? (data.returns / data.sales) * 100 : 0,
        sales_count: data.sales,
        return_count: data.returns
      }));
  }

  private analyzeSavings(returns: ReturnData[], trace_id: string) {
    // 假设通过优化措施预防了 10% 的退货
    const preventedReturns = Math.round(returns.length * 0.1);
    const averageRefund = returns.length > 0 ? 
      returns.reduce((sum, r) => sum + r.refund_amount, 0) / returns.length : 0;
    const estimatedSavings = preventedReturns * averageRefund;
    const improvementPercentage = 10; // 假设改进了 10%

    return {
      prevented_returns: preventedReturns,
      estimated_savings: estimatedSavings,
      improvement_percentage: improvementPercentage
    };
  }

  private analyzeRiskFactors(product: ProductData, returns: ReturnData[], returnRate: number) {
    const factors = [];

    // 退货率因素
    if (returnRate > 20) {
      factors.push({
        factor: '退货率过高',
        score: 90,
        description: `当前退货率为 ${returnRate.toFixed(2)}%，远高于行业平均水平`
      });
    } else if (returnRate > 10) {
      factors.push({
        factor: '退货率偏高',
        score: 60,
        description: `当前退货率为 ${returnRate.toFixed(2)}%，高于行业平均水平`
      });
    }

    // 退货原因因素
    const qualityReturns = returns.filter(r => r.return_reason.includes('质量')).length;
    const qualityReturnRate = returns.length > 0 ? (qualityReturns / returns.length) * 100 : 0;
    if (qualityReturnRate > 30) {
      factors.push({
        factor: '质量问题严重',
        score: 85,
        description: `质量相关退货占比 ${qualityReturnRate.toFixed(2)}%，需要重点关注`
      });
    }

    // 价格因素
    if (product.price > 1000) {
      factors.push({
        factor: '高价值商品',
        score: 70,
        description: '高价值商品退货风险较高，建议加强质量控制'
      });
    }

    // 类别因素
    const highRiskCategories = ['电子产品', '服装', '鞋类'];
    if (highRiskCategories.includes(product.category)) {
      factors.push({
        factor: '高风险类别',
        score: 65,
        description: `${product.category} 属于高退货风险类别`
      });
    }

    return factors;
  }

  private getRiskLevel(score: number): 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL' {
    if (score >= 80) return 'CRITICAL';
    if (score >= 60) return 'HIGH';
    if (score >= 40) return 'MEDIUM';
    return 'LOW';
  }

  private generateRiskActions(riskLevel: string, factors: any[]) {
    const actions = [];

    if (riskLevel === 'CRITICAL') {
      actions.push('立即进行产品质量审计');
      actions.push('暂停该产品的销售，直至问题解决');
      actions.push('联系所有近期购买该产品的客户，主动提供解决方案');
      actions.push('重新评估产品定价策略');
    } else if (riskLevel === 'HIGH') {
      actions.push('加强产品质量检测流程');
      actions.push('更新产品描述和图片，确保与实际产品一致');
      actions.push('提供更详细的产品信息和使用指南');
      actions.push('考虑调整产品价格或促销策略');
    } else if (riskLevel === 'MEDIUM') {
      actions.push('优化产品描述和图片');
      actions.push('加强客户服务培训，提高售前咨询质量');
      actions.push('定期监控退货率变化');
    } else {
      actions.push('继续保持当前的质量管理流程');
      actions.push('定期监控退货率变化');
    }

    // 基于具体风险因素添加针对性建议
    factors.forEach(factor => {
      if (factor.factor === '质量问题严重') {
        actions.push('与供应商协商改善产品质量');
        actions.push('增加产品检测环节');
      } else if (factor.factor === '退货率过高') {
        actions.push('分析退货数据，找出具体原因');
        actions.push('制定针对性的改进计划');
      }
    });

    return actions;
  }

  /**
   * 获取完整的退货分析报告
   */
  async getReturnAnalysisReport(
    productData: ProductData,
    returnData: ReturnData[],
    salesData: SalesData[],
    startDate: Date,
    endDate: Date,
    trace_id: string
  ) {
    try {
      logger.info(`[ReturnAnalysisService] Generating return analysis report: productId=${productData.product_id}, traceId=${trace_id}`);

      // 并行执行所有分析
      const [reasonAnalysis, optimizationSuggestion, effectivenessAnalysis, riskAssessment] = await Promise.all([
        this.analyzeReturnReasons(returnData, productData, salesData, trace_id),
        this.generateOptimizationSuggestions(
          await this.analyzeReturnReasons(returnData, productData, salesData, trace_id),
          productData,
          trace_id
        ),
        this.analyzeReturnEffectiveness(returnData, salesData, startDate, endDate, trace_id),
        this.assessReturnRisk(productData, returnData, salesData, trace_id)
      ]);

      return {
        product_id: productData.product_id,
        product_name: productData.product_name,
        reason_analysis: reasonAnalysis,
        optimization_suggestions: optimizationSuggestion,
        effectiveness_analysis: effectivenessAnalysis,
        risk_assessment: riskAssessment,
        generated_at: new Date()
      };
    } catch (error: any) {
      logger.error(`[ReturnAnalysisService] Failed to generate return analysis report: ${error.message}, traceId=${trace_id}`);
      throw error;
    }
  }
}
