import db from '../../config/database';
import { logger } from '../../utils/logger';
import { MultiTenantCore } from '../Tenant/MultiTenantCore';

export enum ReportType {
  ADVERTISER = 'ADVERTISER',
  GMV_MAX = 'GMV_MAX',
  SETTLEMENT = 'SETTLEMENT',
  MALICIOUS_ORDER = 'MALICIOUS_ORDER',
  EMPLOYEE_LOG = 'EMPLOYEE_LOG',
  FINANCIAL = 'FINANCIAL',
  ORDER = 'ORDER',
  MATERIAL = 'MATERIAL',
  PRODUCT = 'PRODUCT',
  DEPT = 'DEPT'
}

/**
 * [BIZ_REP_01] 全业务多维报表服务
 * [BIZ_REP_05] 大数据量聚合优化
 */
export class ReportService {
  /**
   * 获取报表数据 (务实落地：基于 Summary 表聚合)
   */
  static async getReportData(tenantId: string, type: ReportType, filters: any) {
    logger.info(`[Report] Generating ${type} report for tenant: ${tenantId}`);

    switch (type) {
      case ReportType.ORDER:
        return this.getOrderReport(tenantId, filters);
      case ReportType.FINANCIAL:
        return this.getFinancialReport(tenantId, filters);
      case ReportType.MALICIOUS_ORDER:
        return this.getMaliciousOrderReport(tenantId, filters);
      case ReportType.GMV_MAX:
        return this.getGMVMaxReport(tenantId, filters);
      case ReportType.PRODUCT:
        return this.getProductEfficiencyReport(tenantId, filters);
      default:
        logger.warn(`[Report] Report type ${type} is not yet implemented.`);
        return [];
    }
  }

  /**
   * [ERP_REP_01] 预聚合宽表构建逻辑 (Incremental Aggregator)
   * @description 将 cf_consumer_orders 增量聚合到 cf_report_summary，支持分钟级看板。
   */
  static async runIncrementalAggregation(tenantId: string, date: string) {
    logger.info(`[Report] Running incremental aggregation for ${tenantId} on ${date}`);

    try {
      // 1. 获取当日所有订单汇总
      const dailyStats = await MultiTenantCore.from(tenantId, 'cf_consumer_orders')
        .whereRaw('DATE(created_at) = ?', [date])
        .select(
          'platform',
          'site',
          db.raw('SUM(total_amount) as total_revenue'),
          db.raw('COUNT(id) as order_count')
        )
        .groupBy('platform', 'site');

      // 2. 批量写入预聚合宽表 (cf_report_summary)
      for (const stat of dailyStats) {
        await db('cf_report_summary')
          .insert({
            tenant_id: tenantId,
            dimension_type: 'DAILY',
            dimension_value: date,
            platform: stat.platform,
            site: stat.site,
            total_revenue: stat.total_revenue,
            order_count: stat.order_count,
            created_at: new Date()
          })
          .onConflict(['tenant_id', 'dimension_type', 'dimension_value', 'platform', 'site'])
          .merge();
      }
    } catch (err: any) {
      logger.error(`[Report] Aggregation failed: ${err.message}`);
    }
  }

  private static async getGMVMaxReport(tenantId: string, filters: any) {
    const { startDate, endDate } = filters;
    return db('cf_report_summary')
      .where({ tenant_id: tenantId, dimension_type: 'DAILY' })
      .whereBetween('dimension_value', [startDate, endDate])
      .select('dimension_value as date', db.raw('SUM(total_revenue) as total_gmv'))
      .groupBy('date')
      .orderBy('date', 'asc');
  }

  private static async getProductEfficiencyReport(tenantId: string, filters: any) {
    // 联动 cf_product 识别动销率
    return MultiTenantCore.from(tenantId, 'cf_product as p')
      .leftJoin('cf_consumer_orders as o', 'p.id', 'o.product_id')
      .select(
        'p.id as sku_id',
        'p.title',
        db.raw('COUNT(o.id) as sales_volume'),
        db.raw('SUM(o.total_amount) as total_sales')
      )
      .groupBy('p.id', 'p.title')
      .orderBy('sales_volume', 'desc')
      .limit(50);
  }

  private static async getOrderReport(tenantId: string, filters: any) {
    // V30.0 优化：从 Summary 表读取预聚合数据，支持多维度
    const { startDate, endDate, platform, site } = filters;
    
    let query = db('cf_report_summary')
      .where({ tenant_id: tenantId, dimension_type: 'DAILY' })
      .select(
        'dimension_value as date',
        'platform',
        'site',
        'total_revenue',
        'net_profit',
        'order_count'
      );

    if (startDate && endDate) {
      query = query.whereBetween('dimension_value', [startDate, endDate]);
    }
    
    if (platform) {
      query = query.where({ platform });
    }

    if (site) {
      query = query.where({ site });
    }

    return query.orderBy('date', 'desc');
  }

  private static async getFinancialReport(tenantId: string, filters: any) {
    // 聚合 cf_settlement 与 cf_order
    return MultiTenantCore.from(tenantId, 'cf_consumer_orders as o')
      .join('cf_settlement as s', 'o.id', 's.order_id')
      .select(
        'o.id as order_id',
        'o.total_amount',
        's.net_profit',
        's.status as settlement_status',
        's.created_at as settlement_date'
      )
      .limit(100);
  }

  private static async getMaliciousOrderReport(tenantId: string, filters: any) {
    // 基于 AGI 风险审计识别恶意订单
    return MultiTenantCore.from(tenantId, 'cf_consumer_orders')
      .where({ audit_status: 'RISKY' })
      .select('id', 'total_amount', 'risk_reason', 'created_at');
  }
}
