import db from '../../config/database';
import { FinanceService } from '../../services/FinanceService';
import { InventoryService } from '../../services/InventoryService';
import { SupplyChainService } from '../../services/SupplyChainService';
import { logger } from '../../utils/logger';
import { SummaryAggregationService } from '../Analytics/SummaryAggregationService';

export interface ConsumerOrder {
  id: string;
  tenant_id: string;
  shop_id: string;
  platform: 'AMAZON' | 'ALIEXPRESS' | 'SHOPIFY' | 'TIKTOK';
  site: string; // e.g., 'US', 'UK', 'DE', 'MY'
  platform_order_id: string;
  customer_name: string;
  customer_email?: string;
  shipping_address: any;
  items: any[];
  total_amount: number;
  currency: string;
  status: 'UNPAID' | 'PAID' | 'PENDING_AUDIT' | 'WAITING_SHIPMENT' | 'READY_TO_SHIP' | 'PROCESSING' | 'SHIPPED' | 'DELIVERED' | 'CANCELLED' | 'EXCEPTION';
  payment_status: 'PENDING' | 'COMPLETED' | 'REFUNDED' | 'FAILED';
  fulfillment_status: 'PENDING' | 'PROCESSING' | 'SHIPPED' | 'PARTIAL_SHIPPED' | 'FAILED';
  exception_reason?: string;
  auto_heal_status?: 'NONE' | 'PENDING' | 'HEALED' | 'FAILED';
  profit_snapshot?: any;
  trace_id: string;
}

/**
 * [BIZ_TOC_02] ToC 消费者订单聚合服务 (Consumer Order Aggregator)
 * [BIZ_ORD_05] 智能订单编排与异常自愈 (Orchestrator)
 * @description 核心逻辑：实现多平台订单归集、利润实时计算、FSM 状态机及异常自愈逻辑。
 */
import { SupplierService } from '../../services/SupplierService';

export class ConsumerOrderService {
  /**
   * [BIZ_SUP_20] 订单完成后反哺供应商 TrustScore
   */
  static async completeOrder(tenantId: string, orderId: string) {
    logger.info(`[Order] Completing order ${orderId} for Tenant ${tenantId}`);

    try {
      const order = await db(this.TABLE_NAME).where({ id: orderId }).first();
      if (!order) return;

      await this.transitionStatus(tenantId, orderId, 'DELIVERED');

      // 异步采集指标，不阻塞订单主流程
      if (order.supplier_id) {
        SupplierService.collectRealTimeMetrics(order.supplier_id, tenantId).catch((e: any) => {
          logger.warn(`[Order] Failed to feedback to TrustScore: ${e.message}`);
        });
      }

    } catch (err: any) {
      logger.error(`[Order] Completion failed: ${err.message}`);
    }
  }
  private static readonly TABLE_NAME = 'cf_consumer_orders';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.TABLE_NAME);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.TABLE_NAME} table...`);
      await db.schema.createTable(this.TABLE_NAME, (table) => {
        table.string('id', 64).primary();
        table.string('tenant_id', 64).notNullable();
        table.string('shop_id', 64).notNullable();
        table.string('platform', 32).notNullable();
        table.string('site', 16).notNullable(); // e.g., 'US', 'UK'
        table.string('platform_order_id', 128).notNullable();
        table.string('customer_name', 128);
        table.string('customer_email', 128);
        table.json('shipping_address');
        table.json('items');
        table.decimal('total_amount', 15, 2).defaultTo(0);
        table.string('currency', 10).defaultTo('USD');
        table.string('status', 32).defaultTo('UNPAID');
        table.string('payment_status', 32).defaultTo('PENDING');
        table.string('fulfillment_status', 32).defaultTo('PENDING');
        table.string('exception_reason', 255);
        table.string('auto_heal_status', 32).defaultTo('NONE');
        table.json('profit_snapshot');
        table.string('trace_id', 64);
        table.timestamps(true, true);

        // 核心索引优化：支持多租户 + 站点 + 平台的高效查询
        table.index(['tenant_id', 'status', 'created_at'], 'idx_order_tenant_status');
        table.index(['tenant_id', 'platform', 'site'], 'idx_order_geo');
        table.index(['platform', 'site', 'platform_order_id'], 'idx_order_platform_lookup');
        table.unique(['platform', 'site', 'platform_order_id', 'tenant_id'], 'uk_order_platform');
      });
      logger.info(`✅ Table ${this.TABLE_NAME} created`);
    } else {
      // 检查并添加缺失列 (V30.0 增量更新)
      const hasExceptionReason = await db.schema.hasColumn(this.TABLE_NAME, 'exception_reason');
      if (!hasExceptionReason) {
        await db.schema.alterTable(this.TABLE_NAME, (table) => {
          table.string('exception_reason', 255).after('fulfillment_status');
          table.string('auto_heal_status', 32).defaultTo('NONE').after('exception_reason');
        });
        logger.info(`✅ Columns exception_reason/auto_heal_status added to ${this.TABLE_NAME}`);
      }

      const hasSite = await db.schema.hasColumn(this.TABLE_NAME, 'site');
      if (!hasSite) {
        await db.schema.alterTable(this.TABLE_NAME, (table) => {
          table.string('site', 16).defaultTo('US').after('platform');
        });
        logger.info(`✅ Column site added to ${this.TABLE_NAME}`);
      }
    }
  }

  /**
   * [FSM] 状态转换核心引擎
   * @description 严格控制订单生命周期状态流转
   */
  static async transitionStatus(tenantId: string, orderId: string, nextStatus: ConsumerOrder['status'], reason?: string): Promise<void> {
    const order = await db(this.TABLE_NAME).where({ id: orderId, tenant_id: tenantId }).first();
    if (!order) throw new Error(`[OrderOrchestrator] Order ${orderId} not found`);

    const currentStatus = order.status;
    const allowedTransitions: Record<string, string[]> = {
      'UNPAID': ['PAID', 'CANCELLED', 'EXCEPTION'],
      'PAID': ['PENDING_AUDIT', 'WAITING_SHIPMENT', 'CANCELLED', 'EXCEPTION'],
      'PENDING_AUDIT': ['WAITING_SHIPMENT', 'CANCELLED', 'EXCEPTION'],
      'WAITING_SHIPMENT': ['READY_TO_SHIP', 'CANCELLED', 'EXCEPTION'],
      'READY_TO_SHIP': ['SHIPPED', 'CANCELLED', 'EXCEPTION'],
      'PROCESSING': ['SHIPPED', 'CANCELLED', 'EXCEPTION'],
      'SHIPPED': ['DELIVERED', 'EXCEPTION'],
      'EXCEPTION': ['PAID', 'PENDING_AUDIT', 'WAITING_SHIPMENT', 'PROCESSING', 'CANCELLED'],
      'CANCELLED': [],
      'DELIVERED': []
    };

    if (!allowedTransitions[currentStatus]?.includes(nextStatus)) {
      throw new Error(`[OrderOrchestrator] Invalid transition: ${currentStatus} -> ${nextStatus}`);
    }

    await db(this.TABLE_NAME).where({ id: orderId }).update({
      status: nextStatus,
      exception_reason: nextStatus === 'EXCEPTION' ? reason : null,
      updated_at: new Date()
    });

    logger.info(`[OrderOrchestrator] Order ${orderId} transitioned: ${currentStatus} -> ${nextStatus}`);

    // 触发后续自动化逻辑
    if (nextStatus === 'PAID') {
      await this.processOrderSettlement(orderId);
      await this.runHealthCheck(tenantId, orderId);
    } else if (nextStatus === 'WAITING_SHIPMENT') {
      // 联动物流选择逻辑 (BIZ_LOG_01)
    }
  }

  /**
   * [ERP_OMS_01] 批量审核订单 (Batch Audit)
   */
  static async batchAudit(tenantId: string, orderIds: string[]): Promise<{ success: number; failed: number }> {
    logger.info(`[OMS] Batch auditing ${orderIds.length} orders for Tenant ${tenantId}`);
    let success = 0;
    let failed = 0;

    for (const id of orderIds) {
      try {
        await this.transitionStatus(tenantId, id, 'WAITING_SHIPMENT', 'Batch audited via OMS');
        success++;
      } catch (err: any) {
        logger.warn(`[OMS] Audit failed for ${id}: ${err.message}`);
        failed++;
      }
    }

    return { success, failed };
  }

  /**
   * [ERP_OMS_01] 批量发货 (Batch Shipment)
   */
  static async batchShip(tenantId: string, orderIds: string[]): Promise<{ success: number; failed: number }> {
    logger.info(`[OMS] Batch shipping ${orderIds.length} orders for Tenant ${tenantId}`);
    let success = 0;
    let failed = 0;

    for (const id of orderIds) {
      try {
        await this.transitionStatus(tenantId, id, 'SHIPPED', 'Batch shipped via OMS');
        success++;
      } catch (err: any) {
        logger.warn(`[OMS] Shipment failed for ${id}: ${err.message}`);
        failed++;
      }
    }

    return { success, failed };
  }

  /**
   * [ERP_OMS_01] 异常标记 (Mark Exception)
   */
  static async markAsException(tenantId: string, orderId: string, reason: string): Promise<void> {
    await this.transitionStatus(tenantId, orderId, 'EXCEPTION', reason);
  }

  /**
   * [ERP_OMS_01] 自动改派 (Auto Reroute)
   * @description 联动 InventoryService 寻找最优仓库重新分配库存
   */
  static async autoReroute(tenantId: string, orderId: string): Promise<void> {
    logger.info(`[OMS] Auto-rerouting Order ${orderId}`);
    // 逻辑：释放旧库位锁定 -> 触发新库位健康检查
    await this.attemptAutoHeal(tenantId, orderId, 'STOCK_OUT');
  }

  /**
   * [AGI Health Check] 智能异常检测
   */
  private static async runHealthCheck(tenantId: string, orderId: string) {
    const order = await db(this.TABLE_NAME).where({ id: orderId, tenant_id: tenantId }).first();
    if (!order) return;

    logger.info(`[OrderHealth] Running AI check for Order: ${orderId}`);

    // 1. 地址合规性检查 (B2B 严禁住宅地址)
    const address = typeof order.shipping_address === 'string' ? JSON.parse(order.shipping_address) : order.shipping_address;
    if (address?.is_residential) {
      await this.transitionStatus(tenantId, orderId, 'EXCEPTION', 'Residential address prohibited for B2B trade');
      await this.attemptAutoHeal(tenantId, orderId, 'RESIDENTIAL_ADDRESS');
      return;
    }

    // 2. 欺诈风险评估 (模拟)
    const riskScore = Math.random(); // 实际应调用第三方风控 API
    if (riskScore > 0.95) {
      await this.transitionStatus(tenantId, orderId, 'EXCEPTION', 'High fraud risk score: ' + riskScore.toFixed(2));
      return;
    }

    // 3. 高价值订单审计 (High Value Audit)
    if (order.total_amount > 5000) {
      await this.transitionStatus(tenantId, orderId, 'EXCEPTION', 'High value order (>5000) requires manual audit');
      return;
    }

    // 4. 物流禁区检查 (Forbidden Zone Check)
    const forbiddenZones = ['PO BOX', 'APO', 'FPO'];
    const addrStr = JSON.stringify(address).toUpperCase();
    if (forbiddenZones.some(zone => addrStr.includes(zone))) {
      await this.transitionStatus(tenantId, orderId, 'EXCEPTION', 'Logistics forbidden zone detected (PO Box/APO)');
      return;
    }

    // 5. 库存锁定检查 (BIZ_INV_05)
    const items = typeof order.items === 'string' ? JSON.parse(order.items) : order.items;
    let allLocked = true;
    for (const item of items) {
      const locked = await InventoryService.lockStock(tenantId, item.sku, item.quantity);
      if (!locked) {
        allLocked = false;
        break;
      }
    }

    if (!allLocked) {
      await this.transitionStatus(tenantId, orderId, 'EXCEPTION', 'Stock out: all warehouses');
      await this.attemptAutoHeal(tenantId, orderId, 'STOCK_OUT');
      return;
    }

    // 如果一切正常，进入处理中
    await this.transitionStatus(tenantId, orderId, 'PROCESSING');
  }

  /**
   * [Auto-Heal] 异常自动修复逻辑
   */
  private static async attemptAutoHeal(tenantId: string, orderId: string, type: string) {
    logger.info(`[AutoHeal] Attempting to heal Order ${orderId} (Type: ${type})...`);

    await db(this.TABLE_NAME).where({ id: orderId }).update({ auto_heal_status: 'PENDING' });

    try {
      if (type === 'STOCK_OUT') {
        // 1. 触发 BIZ_SUP_15: 多源寻源路由 (Real Trace)
        logger.info(`[AutoHeal] Triggering SupplyChain trace for ${orderId}`);
        const order = await db(this.TABLE_NAME).where({ id: orderId }).first();
        const items = typeof order.items === 'string' ? JSON.parse(order.items) : order.items;
        
        // 模拟寻源第一个商品的源头厂家
        const productImageUrl = items[0]?.mainImage || 'https://example.com/placeholder.jpg';
        const suppliers = await SupplyChainService.traceSourceFactory(tenantId, 'PROD-001', productImageUrl);

        if (suppliers.length > 0) {
          const bestSupplier = suppliers[0];
          logger.info(`[AutoHeal] New supplier found: ${bestSupplier.name}`);
          
          await db(this.TABLE_NAME).where({ id: orderId }).update({ 
            auto_heal_status: 'HEALED',
            exception_reason: `Auto-healed via rerouting to ${bestSupplier.name}`
          });
          
          await this.transitionStatus(tenantId, orderId, 'PROCESSING', 'Auto-healed via multi-source routing');
        } else {
          logger.warn(`[AutoHeal] No alternative supplier found for ${orderId}`);
          await db(this.TABLE_NAME).where({ id: orderId }).update({ auto_heal_status: 'FAILED' });
        }
      } else if (type === 'RESIDENTIAL_ADDRESS') {
        // 自动申请地址变更或标记为轻 B 模式 (视配置而定)
        logger.info(`[AutoHeal] Flagging ${orderId} for manual review or Light-B conversion`);
        await db(this.TABLE_NAME).where({ id: orderId }).update({ auto_heal_status: 'FAILED' });
      }
    } catch (err: any) {
      logger.error(`[AutoHeal] Failed for Order ${orderId}: ${err.message}`);
      await db(this.TABLE_NAME).where({ id: orderId }).update({ auto_heal_status: 'FAILED' });
    }
  }

  /**
   * 手动重试异常订单
   */
  static async retryException(tenantId: string, orderId: string): Promise<void> {
    logger.info(`[OrderOrchestrator] Manually retrying Order: ${orderId}`);
    // 先转回 PAID 状态重新触发健康检查
    await this.transitionStatus(tenantId, orderId, 'PAID', 'Manual retry');
  }

  /**
   * 取消订单并执行资源释放
   */
  static async cancelOrder(tenantId: string, orderId: string, reason: string): Promise<void> {
    logger.warn(`[OrderOrchestrator] Cancelling Order ${orderId}: ${reason}`);
    
    const order = await db(this.TABLE_NAME).where({ id: orderId, tenant_id: tenantId }).first();
    if (!order) throw new Error('Order not found');

    await this.transitionStatus(tenantId, orderId, 'CANCELLED', reason);
    
    // 联动 BIZ_INV_05 释放库存
    await this.releaseOrderInventory(tenantId, orderId);
    
    // 联动 BIZ_FIN_04 记录取消流水
    await FinanceService.recordTransaction({
      tenantId,
      amount: order.total_amount || 0,
      type: 'REFUND',
      orderId,
      traceId: 'manual-cancel',
      metadata: { reason }
    });
  }

  /**
   * 释放订单占用的库存
   */
  private static async releaseOrderInventory(tenantId: string, orderId: string): Promise<void> {
    const order = await db(this.TABLE_NAME).where({ id: orderId, tenant_id: tenantId }).first();
    if (!order) return;

    const items = typeof order.items === 'string' ? JSON.parse(order.items) : order.items;
    for (const item of items) {
      await InventoryService.releaseStock(tenantId, item.sku, item.quantity, 'DEFAULT').catch((e: any) => {
        logger.warn(`[Order] Failed to release stock for ${item.sku}: ${e.message}`);
      });
    }
  }

  /**
   * 申请退款
   */
  static async requestRefund(tenantId: string, orderId: string, reason: string, amount: number): Promise<string> {
    logger.info(`[Refund] Requesting refund for Order ${orderId}: ${reason}`);

    const order = await db(this.TABLE_NAME).where({ id: orderId, tenant_id: tenantId }).first();
    if (!order) throw new Error('Order not found');

    if (order.status !== 'PAID' && order.status !== 'SHIPPED' && order.status !== 'DELIVERED') {
      throw new Error('Order cannot be refunded in current status');
    }

    const refundId = `REF-${Date.now()}`;
    
    // 记录退款申请
    await db('cf_refunds').insert({
      id: refundId,
      order_id: orderId,
      tenant_id: tenantId,
      amount: amount,
      reason: reason,
      status: 'PENDING',
      created_at: new Date(),
      updated_at: new Date()
    });

    return refundId;
  }

  /**
   * 审批退款
   */
  static async approveRefund(tenantId: string, refundId: string, approved: boolean, note?: string): Promise<void> {
    logger.info(`[Refund] ${approved ? 'Approving' : 'Rejecting'} refund ${refundId}`);

    const refund = await db('cf_refunds').where({ id: refundId, tenant_id: tenantId }).first();
    if (!refund) throw new Error('Refund not found');

    const status = approved ? 'APPROVED' : 'REJECTED';
    await db('cf_refunds').where({ id: refundId }).update({
      status: status,
      note: note,
      updated_at: new Date()
    });

    if (approved) {
      // 执行退款
      await this.processRefund(tenantId, refund.order_id, refund.amount, refund.reason);
    }
  }

  /**
   * 处理退款
   */
  private static async processRefund(tenantId: string, orderId: string, amount: number, reason: string): Promise<void> {
    logger.info(`[Refund] Processing refund for Order ${orderId}`);

    // 更新订单状态
    await db(this.TABLE_NAME).where({ id: orderId, tenant_id: tenantId }).update({
      payment_status: 'REFUNDED',
      updated_at: new Date()
    });

    // 释放库存
    await this.releaseOrderInventory(tenantId, orderId);

    // 记录财务交易
    await FinanceService.recordTransaction({
      tenantId,
      amount: amount,
      type: 'REFUND',
      orderId,
      traceId: `refund-${Date.now()}`,
      metadata: { reason }
    });

    logger.info(`✅ [Refund] Processed refund for Order ${orderId}: ${amount}`);
  }

  /**
   * 申请售后
   */
  static async requestAfterSales(tenantId: string, orderId: string, type: 'REFUND' | 'EXCHANGE' | 'REPAIR', reason: string, items: any[]): Promise<string> {
    logger.info(`[AfterSales] Requesting ${type} for Order ${orderId}: ${reason}`);

    const order = await db(this.TABLE_NAME).where({ id: orderId, tenant_id: tenantId }).first();
    if (!order) throw new Error('Order not found');

    if (order.status !== 'DELIVERED') {
      throw new Error('After-sales service is only available for delivered orders');
    }

    const serviceId = `SVC-${Date.now()}`;
    
    // 记录售后申请
    await db('cf_after_sales').insert({
      id: serviceId,
      order_id: orderId,
      tenant_id: tenantId,
      type: type,
      reason: reason,
      items: JSON.stringify(items),
      status: 'PENDING',
      created_at: new Date(),
      updated_at: new Date()
    });

    return serviceId;
  }

  /**
   * 处理售后申请
   */
  static async processAfterSales(tenantId: string, serviceId: string, action: 'APPROVE' | 'REJECT', note?: string): Promise<void> {
    logger.info(`[AfterSales] ${action === 'APPROVE' ? 'Approving' : 'Rejecting'} service ${serviceId}`);

    const service = await db('cf_after_sales').where({ id: serviceId, tenant_id: tenantId }).first();
    if (!service) throw new Error('After-sales service not found');

    const status = action === 'APPROVE' ? 'APPROVED' : 'REJECTED';
    await db('cf_after_sales').where({ id: serviceId }).update({
      status: status,
      note: note,
      updated_at: new Date()
    });

    if (action === 'APPROVE') {
      if (service.type === 'REFUND') {
        // 处理退款
        await this.requestRefund(tenantId, service.order_id, service.reason, 0);
      } else if (service.type === 'EXCHANGE') {
        // 处理换货
        await this.processExchange(tenantId, service.order_id, JSON.parse(service.items));
      }
    }
  }

  /**
   * 处理换货
   */
  private static async processExchange(tenantId: string, orderId: string, items: any[]): Promise<void> {
    logger.info(`[AfterSales] Processing exchange for Order ${orderId}`);

    // 释放旧商品库存
    await this.releaseOrderInventory(tenantId, orderId);

    // 为新商品锁定库存
    for (const item of items) {
      await InventoryService.lockStock(tenantId, item.sku, item.quantity).catch(e => {
        logger.warn(`[AfterSales] Failed to lock stock for exchange: ${e.message}`);
      });
    }

    // 记录换货操作
    await db('cf_exchange_records').insert({
      id: `EX-${Date.now()}`,
      order_id: orderId,
      tenant_id: tenantId,
      items: JSON.stringify(items),
      status: 'PROCESSING',
      created_at: new Date(),
      updated_at: new Date()
    });

    logger.info(`✅ [AfterSales] Processed exchange for Order ${orderId}`);
  }

  /**
   * 同步/抓取外部平台订单
   */
  static async syncPlatformOrder(orderData: Partial<ConsumerOrder>): Promise<string> {
    const { platform, platform_order_id, tenant_id } = orderData;
    
    if (!platform || !platform_order_id || !tenant_id) {
      throw new Error('Missing required order data: platform, platform_order_id, tenant_id');
    }
    
    const existing = await db(this.TABLE_NAME)
      .where({ platform, platform_order_id, tenant_id })
      .first();

    if (existing) {
      logger.info(`[ConsumerOrder] Order ${platform_order_id} already exists, updating status...`);
      await db(this.TABLE_NAME).where({ id: existing.id }).update({
        status: orderData.status || existing.status,
        payment_status: orderData.payment_status || existing.payment_status,
        fulfillment_status: orderData.fulfillment_status || existing.fulfillment_status,
        updated_at: new Date()
      });
      
      // 如果状态发生变化，触发相应的处理
      if (orderData.status === 'PAID' && existing.status !== 'PAID') {
        await this.processOrderSettlement(existing.id);
      }
      
      return existing.id;
    }

    const orderId = `ORD-${Date.now()}`;
    const orderToInsert = {
      ...orderData,
      id: orderId,
      site: orderData.site || 'US',
      shipping_address: typeof orderData.shipping_address === 'object' ? JSON.stringify(orderData.shipping_address) : orderData.shipping_address,
      items: typeof orderData.items === 'object' ? JSON.stringify(orderData.items) : orderData.items,
      status: orderData.status || 'UNPAID',
      payment_status: orderData.payment_status || 'PENDING',
      fulfillment_status: orderData.fulfillment_status || 'PENDING',
      created_at: new Date(),
      updated_at: new Date()
    };
    
    await db(this.TABLE_NAME).insert(orderToInsert);
    logger.info(`[ConsumerOrder] Created new order ${orderId} for platform ${platform}`);

    // 如果订单已支付，触发利润计算与分账 (BIZ_FIN_05)
    if (orderData.status === 'PAID') {
      await this.processOrderSettlement(orderId);
    }

    return orderId;
  }

  /**
   * 创建内部订单
   */
  static async createInternalOrder(tenantId: string, shopId: string, orderData: any): Promise<string> {
    logger.info(`[ConsumerOrder] Creating internal order for Tenant ${tenantId}`);

    const orderId = `ORD-${Date.now()}`;
    const orderToInsert = {
      id: orderId,
      tenant_id: tenantId,
      shop_id: shopId,
      platform: 'INTERNAL',
      site: orderData.site || 'US',
      platform_order_id: `INT-${Date.now()}`,
      customer_name: orderData.customerName || 'Internal Customer',
      customer_email: orderData.customerEmail,
      shipping_address: JSON.stringify(orderData.shippingAddress),
      items: JSON.stringify(orderData.items),
      total_amount: orderData.totalAmount,
      currency: orderData.currency || 'USD',
      status: 'UNPAID',
      payment_status: 'PENDING',
      fulfillment_status: 'PENDING',
      trace_id: `internal-${Date.now()}`,
      created_at: new Date(),
      updated_at: new Date()
    };

    await db(this.TABLE_NAME).insert(orderToInsert);
    logger.info(`[ConsumerOrder] Created internal order ${orderId}`);

    return orderId;
  }

  /**
   * 处理订单支付
   */
  static async processPayment(tenantId: string, orderId: string, paymentInfo: any): Promise<void> {
    logger.info(`[ConsumerOrder] Processing payment for Order ${orderId}`);

    const order = await db(this.TABLE_NAME).where({ id: orderId, tenant_id: tenantId }).first();
    if (!order) throw new Error('Order not found');

    if (order.payment_status === 'COMPLETED') {
      throw new Error('Order is already paid');
    }

    // 更新支付状态
    await db(this.TABLE_NAME).where({ id: orderId }).update({
      payment_status: 'COMPLETED',
      status: 'PAID',
      updated_at: new Date()
    });

    // 记录支付信息
    await db('cf_payments').insert({
      id: `PAY-${Date.now()}`,
      order_id: orderId,
      tenant_id: tenantId,
      amount: order.total_amount,
      currency: order.currency,
      payment_method: paymentInfo.method,
      transaction_id: paymentInfo.transactionId,
      status: 'COMPLETED',
      created_at: new Date(),
      updated_at: new Date()
    });

    // 触发订单结算
    await this.processOrderSettlement(orderId);
    logger.info(`✅ [ConsumerOrder] Payment processed for Order ${orderId}`);
  }

  /**
   * [BIZ_FIN_05] 订单结算与自动分账
   * @description 计算净利润并根据租户规则分配资金
   */
  private static async processOrderSettlement(orderId: string) {
    const order = await db(this.TABLE_NAME).where({ id: orderId }).first();
    if (!order) return;

    logger.info(`[ConsumerOrder] Starting settlement for Order: ${orderId}`);

    // 1. 获取利润分析 (PricingService)
    const items = typeof order.items === 'string' ? JSON.parse(order.items) : order.items;
    let totalCost = 0;
    
    // 简单模拟成本计算 (实际应从库存或 PO 获取)
    for (const item of items) {
      totalCost += (item.costPrice || (item.price * 0.4)) * item.quantity;
    }

    const netProfit = order.total_amount - totalCost;
    
    // 2. 记录利润快照
    const profitSnapshot = {
      revenue: order.total_amount,
      cost: totalCost,
      net_profit: netProfit,
      margin: (netProfit / order.total_amount).toFixed(4),
      settled_at: new Date()
    };

    await db(this.TABLE_NAME).where({ id: orderId }).update({
      profit_snapshot: JSON.stringify(profitSnapshot)
    });

    // 3. 执行分账 (FinanceService)
    // 示例：Owner 80%, Manager 20%
    await FinanceService.recordTransaction({
      tenantId: order.tenant_id,
      amount: netProfit * 0.8,
      type: 'INCOME',
      category: 'ORDER_PROFIT',
      metadata: { orderId, role: 'OWNER' }
    });

    await FinanceService.recordTransaction({
      tenantId: order.tenant_id,
      amount: netProfit * 0.2,
      type: 'INCOME',
      category: 'COMMISSION',
      metadata: { orderId, role: 'MANAGER' }
    });

    // 4. [BIZ_REP_05] 异步更新报表摘要 (大数据量优化)
    await SummaryAggregationService.updateDailyStats({
      tenantId: order.tenant_id,
      shopId: order.shop_id,
      platform: order.platform,
      site: order.site,
      amount: order.total_amount,
      cost: totalCost,
      profit: netProfit,
      date: new Date().toISOString().split('T')[0]
    });



    logger.info(`✅ [ConsumerOrder] Settlement completed for Order: ${orderId}. Profit: ${netProfit}`);
  }

  /**
   * 获取订单统计数据
   */
  static async getOrderStats(tenantId: string) {
    const stats = await db(this.TABLE_NAME)
      .where({ tenant_id: tenantId })
      .select('status')
      .count('id as count')
      .groupBy('status');

    const totalRevenue = await db(this.TABLE_NAME)
      .where({ tenant_id: tenantId, status: 'PAID' })
      .sum('total_amount as total');

    return {
      status_counts: stats,
      total_revenue: totalRevenue[0]?.total || 0
    };
  }

  /**
   * 查询订单列表
   */
  static async getOrders(tenantId: string, filters: any = {}, page: number = 1, pageSize: number = 20) {
    logger.info(`[ConsumerOrder] Querying orders for Tenant ${tenantId}`);

    let query = db(this.TABLE_NAME).where({ tenant_id: tenantId });

    // 应用过滤条件
    if (filters.status) {
      query = query.where({ status: filters.status });
    }
    if (filters.platform) {
      query = query.where({ platform: filters.platform });
    }
    if (filters.startDate) {
      query = query.where('created_at', '>=', new Date(filters.startDate));
    }
    if (filters.endDate) {
      query = query.where('created_at', '<=', new Date(filters.endDate));
    }
    if (filters.customerName) {
      query = query.where('customer_name', 'like', `%${filters.customerName}%`);
    }

    // 计算总数
    const total = await query.clone().count('id as total').first();

    // 分页查询
    const orders = await query
      .orderBy('created_at', 'desc')
      .limit(pageSize)
      .offset((page - 1) * pageSize);

    return {
      data: orders,
      total: total?.total || 0,
      page,
      pageSize
    };
  }

  /**
   * 获取订单详情
   */
  static async getOrderById(tenantId: string, orderId: string) {
    const order = await db(this.TABLE_NAME)
      .where({ id: orderId, tenant_id: tenantId })
      .first();

    if (!order) throw new Error('Order not found');

    // 解析JSON字段
    if (order.shipping_address) {
      order.shipping_address = typeof order.shipping_address === 'string' ? JSON.parse(order.shipping_address) : order.shipping_address;
    }
    if (order.items) {
      order.items = typeof order.items === 'string' ? JSON.parse(order.items) : order.items;
    }
    if (order.profit_snapshot) {
      order.profit_snapshot = typeof order.profit_snapshot === 'string' ? JSON.parse(order.profit_snapshot) : order.profit_snapshot;
    }

    return order;
  }

  /**
   * 获取详细的订单统计
   */
  static async getDetailedStats(tenantId: string, startDate?: string, endDate?: string) {
    let query = db(this.TABLE_NAME).where({ tenant_id: tenantId });

    if (startDate) {
      query = query.where('created_at', '>=', new Date(startDate));
    }
    if (endDate) {
      query = query.where('created_at', '<=', new Date(endDate));
    }

    // 按平台统计
    const platformStats = await query.clone()
      .select('platform')
      .count('id as count')
      .sum('total_amount as revenue')
      .groupBy('platform');

    // 按状态统计
    const statusStats = await query.clone()
      .select('status')
      .count('id as count')
      .groupBy('status');

    // 总销售额和订单数
    const totalStats = await query.clone()
      .select(
        db.raw('COUNT(id) as total_orders'),
        db.raw('SUM(total_amount) as total_revenue')
      )
      .first();

    return {
      platform_stats: platformStats,
      status_stats: statusStats,
      total_orders: totalStats?.total_orders || 0,
      total_revenue: totalStats?.total_revenue || 0
    };
  }
}
