import { Injectable, Logger } from '@nestjs/common';
import { db } from '../../config/database';

interface MerchantData {
  id: string;
  tenantId: string;
  companyName: string;
  businessLicense: string;
  contactEmail: string;
  contactPhone: string;
  businessType: string;
  registrationDate: Date;
  status: string;
  createdAt: Date;
  updatedAt: Date;
}

interface SettlementData {
  id: string;
  tenantId: string;
  merchantId: string;
  amount: number;
  status: string;
  settlementDate: Date;
  createdAt: Date;
  updatedAt: Date;
}

interface OrderData {
  id: string;
  tenantId: string;
  merchantId: string;
  shopId: string;
  platform: string;
  totalAmount: number;
  status: string;
  createdAt: Date;
  updatedAt: Date;
  customerId?: string;
}

interface SkuData {
  id: string;
  productId: string;
  sku: string;
  price: number;
  stock: number;
  status: string;
  createdAt: Date;
  updatedAt: Date;
}

interface ValueScoreResult {
  merchantId: string;
  valueScore: number;
  growthScore: number;
  stabilityScore: number;
  retentionScore: number;
  complianceScore: number;
  recommendations: string[];
}

interface GrowthTrendResult {
  merchantId: string;
  period: string;
  revenueGrowth: number;
  orderGrowth: number;
  customerGrowth: number;
  trend: 'up' | 'down' | 'stable';
}

/**
 * [BE-MERCH-001] 商户分析服务
 * 负责商户价值评估、增长趋势分析、风险识别
 * AI注意: 所有商户分析操作必须通过此服务进行
 */
@Injectable()
export class MerchantAnalysisService {
  private readonly logger = new Logger(MerchantAnalysisService.name);

  constructor() {}

  /**
   * 评估商户价值
   * @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 db('cf_merchant')
        .where({ id: merchantId })
        .first();

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

      const settlements = await db('cf_settlement')
        .where({ merchant_id: merchantId })
        .select('*');

      const orders = await db('cf_order')
        .where({ merchant_id: merchantId })
        .select('*');

      const growthScore = this.calculateGrowthScore(orders);
      const stabilityScore = this.calculateStabilityScore(settlements);
      const retentionScore = this.calculateRetentionScore(orders);
      const complianceScore = this.calculateComplianceScore(merchant);

      const valueScore = (
        growthScore * 0.3 +
        stabilityScore * 0.25 +
        retentionScore * 0.25 +
        complianceScore * 0.2
      );

      const recommendations = this.generateRecommendations({
        growthScore,
        stabilityScore,
        retentionScore,
        complianceScore,
      });

      const result: ValueScoreResult = {
        merchantId,
        valueScore: Math.round(valueScore * 100) / 100,
        growthScore,
        stabilityScore,
        retentionScore,
        complianceScore,
        recommendations,
      };

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

      return result;
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      this.logger.error(`商户价值评估失败: ${errorMessage}`, { traceId, merchantId, error });
      throw error;
    }
  }

  /**
   * 分析增长趋势
   * @param merchantId 商户ID
   * @param period 分析周期
   * @param traceId 链路追踪ID
   * @returns 增长趋势结果
   */
  async analyzeGrowthTrend(
    merchantId: string,
    period: 'monthly' | 'quarterly' | 'yearly',
    traceId: string
  ): Promise<GrowthTrendResult> {
    this.logger.log(`开始分析增长趋势: ${merchantId}, 周期: ${period}`, { traceId, merchantId, period });

    try {
      const orders = await db('cf_order')
        .where({ merchant_id: merchantId })
        .orderBy('created_at', 'desc')
        .select('*');

      const revenueGrowth = this.calculateRevenueGrowth(orders, period);
      const orderGrowth = this.calculateOrderGrowth(orders, period);
      const customerGrowth = this.calculateCustomerGrowth(orders, period);

      const trend = this.determineTrend(revenueGrowth, orderGrowth, customerGrowth);

      const result: GrowthTrendResult = {
        merchantId,
        period,
        revenueGrowth,
        orderGrowth,
        customerGrowth,
        trend,
      };

      this.logger.log(`增长趋势分析完成: ${merchantId}`, { traceId, result });

      return result;
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      this.logger.error(`增长趋势分析失败: ${errorMessage}`, { traceId, merchantId, error });
      throw error;
    }
  }

  /**
   * 计算增长评分
   */
  private calculateGrowthScore(orders: OrderData[]): number {
    if (orders.length === 0) return 0;

    const monthlyOrders = this.groupByMonth(orders);
    const growthRates = Object.values(monthlyOrders).map((monthOrders, index) => {
      if (index === 0) return 0;
      const prevMonthOrders = Object.values(monthlyOrders)[index - 1];
      return ((monthOrders.length - prevMonthOrders.length) / prevMonthOrders.length) * 100;
    });

    const avgGrowthRate = growthRates.reduce((sum, rate) => sum + rate, 0) / growthRates.length;
    return Math.min(avgGrowthRate, 100);
  }

  /**
   * 计算稳定性评分
   */
  private calculateStabilityScore(settlements: SettlementData[]): number {
    if (settlements.length === 0) return 0;

    const settlementAmounts = settlements.map(s => s.amount);
    const avgAmount = settlementAmounts.reduce((sum, amount) => sum + amount, 0) / settlementAmounts.length;
    const variance = settlementAmounts.reduce((sum, amount) => sum + Math.pow(amount - avgAmount, 2), 0) / settlementAmounts.length;
    const stdDev = Math.sqrt(variance);

    const stabilityScore = Math.max(0, 100 - (stdDev / avgAmount) * 100);
    return Math.min(stabilityScore, 100);
  }

  /**
   * 计算留存评分
   */
  private calculateRetentionScore(orders: OrderData[]): number {
    if (orders.length === 0) return 0;

    const uniqueCustomers = new Set(orders.map(o => o.customerId || ''));
    const repeatCustomers = new Set<string>();

    orders.forEach(order => {
      const customerId = order.customerId;
      if (customerId && uniqueCustomers.has(customerId)) {
        repeatCustomers.add(customerId);
      }
    });

    const retentionRate = (repeatCustomers.size / uniqueCustomers.size) * 100;
    return Math.min(retentionRate, 100);
  }

  /**
   * 计算合规评分
   */
  private calculateComplianceScore(merchant: any): number {
    let score = 100;

    if (!merchant.business_license) score -= 30;
    if (!merchant.contact_email) score -= 20;
    if (!merchant.contact_phone) score -= 20;
    if (merchant.status !== 'active') score -= 30;

    return Math.max(score, 0);
  }

  /**
   * 生成建议
   */
  private generateRecommendations(scores: {
    growthScore: number;
    stabilityScore: number;
    retentionScore: number;
    complianceScore: number;
  }): string[] {
    const recommendations: string[] = [];

    if (scores.growthScore < 50) {
      recommendations.push('建议加强营销推广，提升订单增长');
    }

    if (scores.stabilityScore < 50) {
      recommendations.push('建议优化运营策略，提升业务稳定性');
    }

    if (scores.retentionScore < 50) {
      recommendations.push('建议改善客户服务，提升客户留存');
    }

    if (scores.complianceScore < 50) {
      recommendations.push('建议完善商户资料，提升合规性');
    }

    return recommendations;
  }

  /**
   * 计算收入增长
   */
  private calculateRevenueGrowth(orders: OrderData[], period: string): number {
    const monthlyOrders = this.groupByMonth(orders);
    const monthlyRevenue = Object.entries(monthlyOrders).map(([month, monthOrders]) => ({
      month,
      revenue: monthOrders.reduce((sum, order) => sum + order.totalAmount, 0),
    }));

    if (monthlyRevenue.length < 2) return 0;

    const latestRevenue = monthlyRevenue[0].revenue;
    const previousRevenue = monthlyRevenue[1].revenue;

    return ((latestRevenue - previousRevenue) / previousRevenue) * 100;
  }

  /**
   * 计算订单增长
   */
  private calculateOrderGrowth(orders: OrderData[], period: string): number {
    const monthlyOrders = this.groupByMonth(orders);
    const monthlyOrderCount = Object.entries(monthlyOrders).map(([month, monthOrders]) => ({
      month,
      count: monthOrders.length,
    }));

    if (monthlyOrderCount.length < 2) return 0;

    const latestCount = monthlyOrderCount[0].count;
    const previousCount = monthlyOrderCount[1].count;

    return ((latestCount - previousCount) / previousCount) * 100;
  }

  /**
   * 计算客户增长
   */
  private calculateCustomerGrowth(orders: OrderData[], period: string): number {
    const monthlyOrders = this.groupByMonth(orders);
    const monthlyCustomers = Object.entries(monthlyOrders).map(([month, monthOrders]) => ({
      month,
      customers: new Set(monthOrders.map(o => o.customerId || '')).size,
    }));

    if (monthlyCustomers.length < 2) return 0;

    const latestCustomers = monthlyCustomers[0].customers;
    const previousCustomers = monthlyCustomers[1].customers;

    return ((latestCustomers - previousCustomers) / previousCustomers) * 100;
  }

  /**
   * 确定趋势
   */
  private determineTrend(revenueGrowth: number, orderGrowth: number, customerGrowth: number): 'up' | 'down' | 'stable' {
    const avgGrowth = (revenueGrowth + orderGrowth + customerGrowth) / 3;

    if (avgGrowth > 10) return 'up';
    if (avgGrowth < -10) return 'down';
    return 'stable';
  }

  /**
   * 按月分组订单
   */
  private groupByMonth(orders: OrderData[]): Record<string, OrderData[]> {
    return orders.reduce((groups, order) => {
      const month = order.createdAt.toISOString().substring(0, 7);
      if (!groups[month]) {
        groups[month] = [];
      }
      groups[month].push(order);
      return groups;
    }, {} as Record<string, OrderData[]>);
  }
}
