import { Injectable, Logger } from '@nestjs/common';
import { Merchant, Settlement, Order } from '@prisma/client';
import { PrismaService } from '../../config/database';

interface MerchantData {
  id: string;
  tenantId: string;
  companyName: string;
  businessLicense: string;
  contactEmail: string;
  contactPhone: string;
  status: 'PENDING' | 'ACTIVE' | 'SUSPENDED' | 'TERMINATED';
  tier: 'BASIC' | 'PRO' | 'ENTERPRISE';
  createdAt: Date;
  updatedAt: Date;
}

interface TransactionData {
  orderId: string;
  merchantId: string;
  totalAmount: number;
  status: string;
  createdAt: Date;
}

interface ValueScoreResult {
  merchantId: string;
  score: number;
  rank: string;
  factors: {
    transactionVolume: number;
    transactionFrequency: number;
    averageOrderValue: number;
    retentionPeriod: number;
    complianceScore: number;
  };
  recommendations: string[];
}

@Injectable()
export class MerchantAnalysisService {
  private readonly logger = new Logger(MerchantAnalysisService.name);

  constructor(private readonly prisma: PrismaService) {}

  /**
   * 评估商户价值
   * @param merchantId 商户ID
   * @param traceId 链路追踪ID
   * @returns 商户价值评分结果
   */
  async evaluateMerchantValue(merchantId: string, traceId: string): Promise<ValueScoreResult> {
    this.logger.log(`开始评估商户价值: ${merchantId}`, { traceId, merchantId });

    try {
      // 获取商户基本信息
      const merchant = await this.prisma.merchant.findUnique({
        where: { id: merchantId },
      });

      if (!merchant) {
        throw new Error(`商户不存在: ${merchantId}`);
      }

      // 获取商户交易数据
      const transactions = await this.prisma.order.findMany({
        where: { merchantId },
        select: {
          id: true,
          merchantId: true,
          totalAmount: true,
          status: true,
          createdAt: true,
        },
      });

      // 计算价值因子
      const factors = this.calculateValueFactors(merchant, transactions);

      // 计算综合评分
      const score = this.calculate综合评分(factors);

      // 确定等级
      const rank = this.determineRank(score);

      // 生成建议
      const recommendations = this.generateRecommendations(factors, score);

      const result: ValueScoreResult = {
        merchantId,
        score,
        rank,
        factors,
        recommendations,
      };

      this.logger.log(`商户价值评估完成: ${merchantId}, 评分: ${score}, 等级: ${rank}`, { traceId, result });

      return result;
    } catch (error) {
      this.logger.error(`商户价值评估失败: ${error.message}`, { traceId, merchantId, error });
      throw error;
    }
  }

  /**
   * 批量评估商户价值
   * @param merchantIds 商户ID列表
   * @param traceId 链路追踪ID
   * @returns 商户价值评分结果列表
   */
  async batchEvaluateMerchantValue(merchantIds: string[], traceId: string): Promise<ValueScoreResult[]> {
    this.logger.log(`开始批量评估商户价值, 数量: ${merchantIds.length}`, { traceId });

    const results: ValueScoreResult[] = [];

    for (const merchantId of merchantIds) {
      try {
        const result = await this.evaluateMerchantValue(merchantId, traceId);
        results.push(result);
      } catch (error) {
        this.logger.error(`批量评估商户价值失败: ${merchantId}, 错误: ${error.message}`, { traceId, merchantId });
      }
    }

    this.logger.log(`批量评估商户价值完成, 成功: ${results.length}/${merchantIds.length}`, { traceId });

    return results;
  }

  /**
   * 计算价值因子
   */
  private calculateValueFactors(merchant: Merchant, transactions: TransactionData[]) {
    // 交易总额
    const transactionVolume = transactions.reduce((sum, tx) => sum + tx.totalAmount, 0);

    // 交易频率
    const transactionFrequency = transactions.length;

    // 平均订单价值
    const averageOrderValue = transactionFrequency > 0 ? transactionVolume / transactionFrequency : 0;

    // 留存期（天数）
    const retentionPeriod = merchant.createdAt ? 
      Math.floor((new Date().getTime() - merchant.createdAt.getTime()) / (1000 * 60 * 60 * 24)) : 0;

    // 合规评分（基于状态和交易情况）
    let complianceScore = 100;
    if (merchant.status === 'SUSPENDED') {
      complianceScore -= 30;
    } else if (merchant.status === 'TERMINATED') {
      complianceScore -= 60;
    }

    // 交易失败率影响合规评分
    const failedTransactions = transactions.filter(tx => tx.status === 'CANCELLED' || tx.status === 'REFUNDED').length;
    if (transactionFrequency > 0) {
      const failureRate = failedTransactions / transactionFrequency;
      complianceScore -= failureRate * 20;
    }

    return {
      transactionVolume,
      transactionFrequency,
      averageOrderValue,
      retentionPeriod,
      complianceScore: Math.max(0, complianceScore),
    };
  }

  /**
   * 计算综合评分
   */
  private calculate综合评分(factors: any): number {
    // 权重分配
    const weights = {
      transactionVolume: 0.3,
      transactionFrequency: 0.25,
      averageOrderValue: 0.2,
      retentionPeriod: 0.15,
      complianceScore: 0.1,
    };

    // 标准化处理
    const normalizedFactors = {
      transactionVolume: Math.min(factors.transactionVolume / 10000, 1), // 10000作为满分阈值
      transactionFrequency: Math.min(factors.transactionFrequency / 100, 1), // 100笔作为满分阈值
      averageOrderValue: Math.min(factors.averageOrderValue / 1000, 1), // 1000作为满分阈值
      retentionPeriod: Math.min(factors.retentionPeriod / 365, 1), // 365天作为满分阈值
      complianceScore: factors.complianceScore / 100,
    };

    // 计算加权总分
    let score = 0;
    for (const [factor, value] of Object.entries(normalizedFactors)) {
      score += value * (weights[factor as keyof typeof weights]);
    }

    // 转换为0-100分
    return Math.round(score * 100);
  }

  /**
   * 确定等级
   */
  private determineRank(score: number): string {
    if (score >= 90) return 'S';
    if (score >= 80) return 'A';
    if (score >= 70) return 'B';
    if (score >= 60) return 'C';
    if (score >= 50) return 'D';
    return 'E';
  }

  /**
   * 生成建议
   */
  private generateRecommendations(factors: any, score: number): string[] {
    const recommendations: string[] = [];

    if (factors.transactionVolume < 1000) {
      recommendations.push('建议增加营销投入，提升交易量');
    }

    if (factors.transactionFrequency < 10) {
      recommendations.push('建议优化产品结构，提高客户复购率');
    }

    if (factors.averageOrderValue < 100) {
      recommendations.push('建议推出高价值产品或捆绑销售策略');
    }

    if (factors.retentionPeriod < 30) {
      recommendations.push('建议加强客户关系管理，提高留存率');
    }

    if (factors.complianceScore < 80) {
      recommendations.push('建议加强合规管理，避免交易纠纷');
    }

    if (score >= 80) {
      recommendations.push('建议升级至高级商户等级，享受更多平台权益');
    }

    return recommendations.length > 0 ? recommendations : ['商户运营状况良好，继续保持'];
  }

  /**
   * 获取商户价值排名
   * @param limit 返回数量
   * @param traceId 链路追踪ID
   * @returns 商户价值排名列表
   */
  async getMerchantValueRanking(limit: number = 10, traceId: string): Promise<Array<{ merchantId: string; companyName: string; score: number; rank: string }>> {
    this.logger.log(`获取商户价值排名, 限制: ${limit}`, { traceId });

    try {
      // 获取所有活跃商户
      const merchants = await this.prisma.merchant.findMany({
        where: { status: 'ACTIVE' },
        select: {
          id: true,
          companyName: true,
        },
      });

      const merchantIds = merchants.map(m => m.id);
      const valueResults = await this.batchEvaluateMerchantValue(merchantIds, traceId);

      // 合并商户信息并排序
      const ranking = valueResults
        .map(result => {
          const merchant = merchants.find(m => m.id === result.merchantId);
          return {
            merchantId: result.merchantId,
            companyName: merchant?.companyName || '未知商户',
            score: result.score,
            rank: result.rank,
          };
        })
        .sort((a, b) => b.score - a.score)
        .slice(0, limit);

      this.logger.log(`获取商户价值排名完成, 数量: ${ranking.length}`, { traceId });

      return ranking;
    } catch (error) {
      this.logger.error(`获取商户价值排名失败: ${error.message}`, { traceId, error });
      throw error;
    }
  }
}
