import db from '../config/database';
import { logger } from '../utils/logger';
import { ConsumerOrder, ConsumerOrderService as ExistingConsumerOrderService } from '../domains/Trade/ConsumerOrderService';
import Redis from 'ioredis';
import { BullMQService } from './BullMQService';

// Redis 客户端
const redis = new Redis({
  host: process.env.REDIS_HOST || 'localhost',
  port: Number(process.env.REDIS_PORT) || 6379,
});

// 订单缓存键前缀
const ORDER_CACHE_PREFIX = 'order:';

/**
 * [ERP_ORD_01] 订单管理服务
 * @description 完整的订单生命周期管理，支持创建、查询、更新、删除等操作
 */
export class OrderService {
  private static readonly TABLE_NAME = 'cf_consumer_orders';

  /**
   * 创建订单
   */
  static async createOrder(orderData: Partial<ConsumerOrder>): Promise<string> {
    const startTime = Date.now();
    
    try {
      const orderId = `ORD-${Date.now()}-${Math.floor(Math.random() * 10000)}`;
      
      const order = {
        ...orderData,
        id: orderId,
        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,
        created_at: new Date(),
        updated_at: new Date(),
      };

      // 插入订单数据 - 使用批量插入优化
      await db(this.TABLE_NAME).insert(order);

      // 缓存订单数据 - 异步执行，不阻塞主流程
      this.cacheOrder(orderId, order).catch(error => {
        logger.warn(`[OrderService] Failed to cache order: ${error.message}`);
      });

      // 发送订单创建事件 - 异步执行，不阻塞主流程
      BullMQService.addJob('order.created', {
        orderId,
        tenantId: orderData.tenant_id,
      }).catch(error => {
        logger.warn(`[OrderService] Failed to add job: ${error.message}`);
      });

      const endTime = Date.now();
      logger.info(`[OrderService] Order created in ${endTime - startTime}ms: ${orderId}`);

      return orderId;
    } catch (error: any) {
      logger.error(`[OrderService] Failed to create order: ${error.message}`);
      throw error;
    }
  }

  /**
   * 获取订单详情
   */
  static async getOrderById(orderId: string, tenantId: string): Promise<ConsumerOrder | null> {
    try {
      // 尝试从缓存获取
      const cachedOrder = await this.getCachedOrder(orderId);
      if (cachedOrder) {
        return cachedOrder;
      }

      // 从数据库获取 - 使用索引优化
      const order = await db(this.TABLE_NAME)
        .where({ id: orderId, tenant_id: tenantId })
        .first();

      if (order) {
        // 转换JSON字段 - 使用并行处理
        const processOrder = async () => {
          if (typeof order.shipping_address === 'string') {
            order.shipping_address = JSON.parse(order.shipping_address);
          }
          if (typeof order.items === 'string') {
            order.items = JSON.parse(order.items);
          }
          if (typeof order.profit_snapshot === 'string') {
            order.profit_snapshot = JSON.parse(order.profit_snapshot);
          }
          return order as ConsumerOrder;
        };

        const processedOrder = await processOrder();

        // 缓存订单数据 - 异步执行，不阻塞主流程
        this.cacheOrder(orderId, processedOrder).catch(error => {
          logger.warn(`[OrderService] Failed to cache order: ${error.message}`);
        });

        return processedOrder;
      }

      return null;
    } catch (error: any) {
      logger.error(`[OrderService] Failed to get order: ${error.message}`);
      throw error;
    }
  }

  /**
   * 更新订单
   */
  static async updateOrder(orderId: string, tenantId: string, updates: Partial<ConsumerOrder>): Promise<void> {
    try {
      // 构建更新数据
      const updateData: any = {
        ...updates,
        updated_at: new Date(),
      };

      // 处理JSON字段
      if (updateData.shipping_address && typeof updateData.shipping_address === 'object') {
        updateData.shipping_address = JSON.stringify(updateData.shipping_address);
      }
      if (updateData.items && typeof updateData.items === 'object') {
        updateData.items = JSON.stringify(updateData.items);
      }
      if (updateData.profit_snapshot && typeof updateData.profit_snapshot === 'object') {
        updateData.profit_snapshot = JSON.stringify(updateData.profit_snapshot);
      }

      // 执行更新
      await db(this.TABLE_NAME)
        .where({ id: orderId, tenant_id: tenantId })
        .update(updateData);

      // 清除缓存
      await this.clearOrderCache(orderId);

      // 发送订单更新事件
      await BullMQService.addJob('order.updated', {
        orderId,
        tenantId,
        updates,
      });
    } catch (error: any) {
      logger.error(`[OrderService] Failed to update order: ${error.message}`);
      throw error;
    }
  }

  /**
   * 删除订单
   */
  static async deleteOrder(orderId: string, tenantId: string): Promise<void> {
    try {
      await db(this.TABLE_NAME)
        .where({ id: orderId, tenant_id: tenantId })
        .del();

      // 清除缓存
      await this.clearOrderCache(orderId);

      // 发送订单删除事件
      await BullMQService.addJob('order.deleted', {
        orderId,
        tenantId,
      });
    } catch (error: any) {
      logger.error(`[OrderService] Failed to delete order: ${error.message}`);
      throw error;
    }
  }

  /**
   * 批量获取订单
   */
  static async getOrders(tenantId: string, params: {
    page?: number;
    pageSize?: number;
    status?: string;
    platform?: string;
    startDate?: string;
    endDate?: string;
  }): Promise<{ orders: ConsumerOrder[]; total: number }> {
    try {
      const { page = 1, pageSize = 20, status, platform, startDate, endDate } = params;
      const offset = (page - 1) * pageSize;

      // 构建查询
      let query = db(this.TABLE_NAME).where({ tenant_id: tenantId });

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

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

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

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

      // 获取总数
      const total = await query.count('id as count').first();

      // 获取分页数据
      const orders = await query
        .offset(offset)
        .limit(pageSize)
        .orderBy('created_at', 'desc');

      // 转换JSON字段
      const processedOrders = orders.map(order => {
        if (typeof order.shipping_address === 'string') {
          order.shipping_address = JSON.parse(order.shipping_address);
        }
        if (typeof order.items === 'string') {
          order.items = JSON.parse(order.items);
        }
        if (typeof order.profit_snapshot === 'string') {
          order.profit_snapshot = JSON.parse(order.profit_snapshot);
        }
        return order as ConsumerOrder;
      });

      return {
        orders: processedOrders,
        total: Number(total?.count || 0),
      };
    } catch (error: any) {
      logger.error(`[OrderService] Failed to get orders: ${error.message}`);
      throw error;
    }
  }

  /**
   * 批量操作订单
   */
  static async batchUpdateOrders(tenantId: string, orderIds: string[], updates: Partial<ConsumerOrder>): Promise<{ success: number; failed: number }> {
    let success = 0;
    let failed = 0;

    // 构建更新数据
    const updateData: any = {
      ...updates,
      updated_at: new Date(),
    };

    // 处理JSON字段
    if (updateData.shipping_address && typeof updateData.shipping_address === 'object') {
      updateData.shipping_address = JSON.stringify(updateData.shipping_address);
    }
    if (updateData.items && typeof updateData.items === 'object') {
      updateData.items = JSON.stringify(updateData.items);
    }
    if (updateData.profit_snapshot && typeof updateData.profit_snapshot === 'object') {
      updateData.profit_snapshot = JSON.stringify(updateData.profit_snapshot);
    }

    try {
      // 使用批量更新优化
      const result = await db(this.TABLE_NAME)
        .where('id', 'in', orderIds)
        .where('tenant_id', tenantId)
        .update(updateData);

      success = result;
      failed = orderIds.length - result;

      // 清除缓存 - 异步执行
      for (const orderId of orderIds) {
        this.clearOrderCache(orderId).catch(error => {
          logger.warn(`[OrderService] Failed to clear order cache: ${error.message}`);
        });
      }

      // 发送批量更新事件 - 异步执行
      BullMQService.addJob('order.batch.updated', {
        orderIds,
        tenantId,
        updates,
      }).catch(error => {
        logger.warn(`[OrderService] Failed to add batch update job: ${error.message}`);
      });

    } catch (error) {
      failed = orderIds.length;
      logger.error(`[OrderService] Failed to batch update orders: ${(error as any).message}`);
    }

    return { success, failed };
  }

  /**
   * 订单状态流转
   */
  static async transitionOrderStatus(tenantId: string, orderId: string, nextStatus: ConsumerOrder['status'], reason?: string): Promise<void> {
    try {
      // 使用现有的ConsumerOrderService来处理状态流转
      await ExistingConsumerOrderService.transitionStatus(tenantId, orderId, nextStatus, reason);
      
      // 清除缓存
      await this.clearOrderCache(orderId);
      
      // 发送状态变更事件
      await BullMQService.addJob('order.status.changed', {
        orderId,
        tenantId,
        oldStatus: (await this.getOrderById(orderId, tenantId))?.status,
        newStatus: nextStatus,
        reason,
      });
    } catch (error: any) {
      logger.error(`[OrderService] Failed to transition order status: ${error.message}`);
      throw error;
    }
  }

  /**
   * 批量审核订单
   */
  static async batchAuditOrders(tenantId: string, orderIds: string[]): Promise<{ success: number; failed: number }> {
    return await ExistingConsumerOrderService.batchAudit(tenantId, orderIds);
  }

  /**
   * 批量发货
   */
  static async batchShipOrders(tenantId: string, orderIds: string[]): Promise<{ success: number; failed: number }> {
    return await ExistingConsumerOrderService.batchShip(tenantId, orderIds);
  }

  /**
   * 标记订单为异常
   */
  static async markOrderAsException(tenantId: string, orderId: string, reason: string): Promise<void> {
    await ExistingConsumerOrderService.markAsException(tenantId, orderId, reason);
    await this.clearOrderCache(orderId);
  }

  /**
   * 自动改派订单
   */
  static async autoRerouteOrder(tenantId: string, orderId: string): Promise<void> {
    await ExistingConsumerOrderService.autoReroute(tenantId, orderId);
    await this.clearOrderCache(orderId);
  }

  /**
   * 重试异常订单
   */
  static async retryExceptionOrder(tenantId: string, orderId: string): Promise<void> {
    await ExistingConsumerOrderService.retryException(tenantId, orderId);
    await this.clearOrderCache(orderId);
  }

  /**
   * 取消订单
   */
  static async cancelOrder(tenantId: string, orderId: string, reason: string): Promise<void> {
    await ExistingConsumerOrderService.cancelOrder(tenantId, orderId, reason);
    await this.clearOrderCache(orderId);
  }

  /**
   * 申请退款
   */
  static async requestRefund(tenantId: string, orderId: string, reason: string, amount: number): Promise<string> {
    const refundId = await ExistingConsumerOrderService.requestRefund(tenantId, orderId, reason, amount);
    await this.clearOrderCache(orderId);
    return refundId;
  }

  /**
   * 审批退款
   */
  static async approveRefund(tenantId: string, refundId: string, approved: boolean, note?: string): Promise<void> {
    await ExistingConsumerOrderService.approveRefund(tenantId, refundId, approved, note);
  }

  /**
   * 申请售后
   */
  static async requestAfterSales(tenantId: string, orderId: string, type: 'REFUND' | 'EXCHANGE' | 'REPAIR', reason: string, items: any[]): Promise<string> {
    const serviceId = await ExistingConsumerOrderService.requestAfterSales(tenantId, orderId, type, reason, items);
    await this.clearOrderCache(orderId);
    return serviceId;
  }

  /**
   * 处理售后申请
   */
  static async processAfterSales(tenantId: string, serviceId: string, action: 'APPROVE' | 'REJECT', note?: string): Promise<void> {
    await ExistingConsumerOrderService.processAfterSales(tenantId, serviceId, action, note);
  }

  /**
   * 完成订单
   */
  static async completeOrder(tenantId: string, orderId: string): Promise<void> {
    await ExistingConsumerOrderService.completeOrder(tenantId, orderId);
    await this.clearOrderCache(orderId);
  }

  /**
   * 缓存订单数据
   */
  private static async cacheOrder(orderId: string, order: any): Promise<void> {
    try {
      const cacheKey = `${ORDER_CACHE_PREFIX}${orderId}`;
      await redis.setex(cacheKey, 3600, JSON.stringify(order));
    } catch (error) {
      logger.warn(`[OrderService] Failed to cache order: ${(error as any).message}`);
    }
  }

  /**
   * 获取缓存的订单数据
   */
  private static async getCachedOrder(orderId: string): Promise<ConsumerOrder | null> {
    try {
      const cacheKey = `${ORDER_CACHE_PREFIX}${orderId}`;
      const cachedData = await redis.get(cacheKey);
      if (cachedData) {
        return JSON.parse(cachedData) as ConsumerOrder;
      }
      return null;
    } catch (error) {
      logger.warn(`[OrderService] Failed to get cached order: ${(error as any).message}`);
      return null;
    }
  }

  /**
   * 清除订单缓存
   */
  private static async clearOrderCache(orderId: string): Promise<void> {
    try {
      const cacheKey = `${ORDER_CACHE_PREFIX}${orderId}`;
      await redis.del(cacheKey);
    } catch (error) {
      logger.warn(`[OrderService] Failed to clear order cache: ${(error as any).message}`);
    }
  }

  /**
   * 将各平台原始 Payload 映射为系统统一模型
   */
  static mapPlatformPayloadToOrder(platform: string, payload: any, tenantId: string, shopId: string): Partial<ConsumerOrder> | null {
    const upperPlatform = platform.toUpperCase();

    switch (upperPlatform) {
      case 'SHOPIFY':
        return {
          tenant_id: tenantId,
          shop_id: shopId,
          platform: 'SHOPIFY',
          platform_order_id: String(payload.id || payload.name),
          customer_name: payload.customer?.first_name ? `${payload.customer.first_name} ${payload.customer.last_name}` : 'Unknown',
          customer_email: payload.customer?.email,
          shipping_address: payload.shipping_address,
          items: payload.line_items?.map((item: any) => ({
            skuId: item.sku,
            title: item.title,
            price: Number(item.price),
            quantity: item.quantity,
            costPrice: item.cost_price || 0
          })),
          total_amount: Number(payload.total_price),
          currency: payload.currency || 'USD',
          status: this.mapShopifyStatus(payload.financial_status, payload.fulfillment_status),
          payment_status: payload.financial_status === 'paid' ? 'COMPLETED' : 'PENDING',
          fulfillment_status: payload.fulfillment_status === 'fulfilled' ? 'SHIPPED' : 'PENDING',
          trace_id: `webhook-${Date.now()}`
        };

      case 'AMAZON':
        // 模拟 Amazon SP-API 结构
        return {
          tenant_id: tenantId,
          shop_id: shopId,
          platform: 'AMAZON',
          platform_order_id: payload.AmazonOrderId,
          customer_name: payload.BuyerInfo?.BuyerName || 'Amazon Customer',
          customer_email: payload.BuyerInfo?.BuyerEmail,
          shipping_address: payload.ShippingAddress,
          items: payload.OrderItems?.map((item: any) => ({
            skuId: item.SellerSKU,
            title: item.Title,
            price: Number(item.ItemPrice?.Amount || 0),
            quantity: item.QuantityOrdered,
            costPrice: 0
          })),
          total_amount: Number(payload.OrderTotal?.Amount || 0),
          currency: payload.OrderTotal?.CurrencyCode || 'USD',
          status: payload.OrderStatus === 'Shipped' ? 'SHIPPED' : 'PAID',
          payment_status: 'COMPLETED',
          fulfillment_status: payload.OrderStatus === 'Shipped' ? 'SHIPPED' : 'PENDING',
          trace_id: `webhook-${Date.now()}`
        };

      case 'TIKTOK':
        // 模拟 TikTok Shop API 结构
        return {
          tenant_id: tenantId,
          shop_id: shopId,
          platform: 'TIKTOK',
          platform_order_id: payload.order_id,
          customer_name: payload.recipient_address?.name || 'TikTok Customer',
          shipping_address: payload.recipient_address,
          items: payload.item_list?.map((item: any) => ({
            skuId: item.sku_id,
            title: item.product_name,
            price: Number(item.sku_sale_price),
            quantity: 1,
            costPrice: 0
          })),
          total_amount: Number(payload.total_amount),
          currency: payload.currency || 'USD',
          status: payload.order_status === 100 ? 'PAID' : 'UNPAID',
          payment_status: payload.order_status >= 100 ? 'COMPLETED' : 'PENDING',
          fulfillment_status: 'PENDING',
          trace_id: `webhook-${Date.now()}`
        };

      default:
        return null;
    }
  }

  /**
   * 映射Shopify订单状态
   */
  private static mapShopifyStatus(financial: string, fulfillment: string): 'UNPAID' | 'PAID' | 'SHIPPED' | 'DELIVERED' {
    if (fulfillment === 'fulfilled') return 'SHIPPED';
    if (financial === 'paid') return 'PAID';
    return 'UNPAID';
  }

  /**
   * 初始化订单相关表
   */
  static async initTables(): Promise<void> {
    // 初始化主订单表
    await ExistingConsumerOrderService.initTable();

    // 初始化退款表
    const hasRefundTable = await db.schema.hasTable('cf_refunds');
    if (!hasRefundTable) {
      logger.info('📦 Creating cf_refunds table...');
      await db.schema.createTable('cf_refunds', (table) => {
        table.string('id', 64).primary();
        table.string('order_id', 64).notNullable();
        table.string('tenant_id', 64).notNullable();
        table.decimal('amount', 15, 2).notNullable();
        table.string('reason', 255).notNullable();
        table.string('status', 32).defaultTo('PENDING');
        table.string('note', 255);
        table.timestamps(true, true);

        table.index(['tenant_id', 'order_id'], 'idx_refund_tenant_order');
        table.index(['status'], 'idx_refund_status');
      });
      logger.info('✅ Table cf_refunds created');
    }

    // 初始化售后表
    const hasAfterSalesTable = await db.schema.hasTable('cf_after_sales');
    if (!hasAfterSalesTable) {
      logger.info('📦 Creating cf_after_sales table...');
      await db.schema.createTable('cf_after_sales', (table) => {
        table.string('id', 64).primary();
        table.string('order_id', 64).notNullable();
        table.string('tenant_id', 64).notNullable();
        table.string('type', 32).notNullable();
        table.string('reason', 255).notNullable();
        table.json('items');
        table.string('status', 32).defaultTo('PENDING');
        table.string('note', 255);
        table.timestamps(true, true);

        table.index(['tenant_id', 'order_id'], 'idx_after_sales_tenant_order');
        table.index(['status'], 'idx_after_sales_status');
      });
      logger.info('✅ Table cf_after_sales created');
    }

    // 初始化换货记录表
    const hasExchangeTable = await db.schema.hasTable('cf_exchange_records');
    if (!hasExchangeTable) {
      logger.info('📦 Creating cf_exchange_records table...');
      await db.schema.createTable('cf_exchange_records', (table) => {
        table.string('id', 64).primary();
        table.string('order_id', 64).notNullable();
        table.string('tenant_id', 64).notNullable();
        table.json('items');
        table.string('status', 32).defaultTo('PROCESSING');
        table.timestamps(true, true);

        table.index(['tenant_id', 'order_id'], 'idx_exchange_tenant_order');
      });
      logger.info('✅ Table cf_exchange_records created');
    }
  }
}