import { PlatformAdapterFactory } from './adapters/PlatformAdapterFactory';
import { IPlatformAdapter } from './adapters/IPlatformAdapter';
import { StoreBindingDto } from '../../api/dto/StoreBindingDto';
import db from '../../config/database';
import { v4 as uuidv4 } from 'uuid';
import { logger } from '../../utils/logger';

export interface Store {
  id: string;
  merchantId: string;
  tenant_id: string;
  shop_id: string;
  platform: string;
  name: string;
  platformShopId: string;
  status: string;
  createdAt: Date;
  updatedAt: Date;
}

const STORES_TABLE = 'cf_stores';

export class OperationAgentService {
  private platformAdapterFactory: PlatformAdapterFactory;

  constructor(platformAdapterFactory: PlatformAdapterFactory) {
    this.platformAdapterFactory = platformAdapterFactory;
  }

  /**
   * 绑定店铺
   * @param dto 店铺绑定信息
   * @returns 绑定结果
   */
  async bindStore(dto: StoreBindingDto): Promise<Store> {
    logger.info(`开始绑定店铺: ${dto.platform} - ${dto.platformShopId}`);

    // 检查店铺是否已存在
    const existingStore = await db(STORES_TABLE)
      .where({
        merchantId: dto.merchantId,
        platform: dto.platform,
        platformShopId: dto.platformShopId
      })
      .first();

    if (existingStore) {
      logger.warn(`店铺已存在: ${dto.platform} - ${dto.platformShopId}`);
      return existingStore;
    }

    // 创建新店铺记录
    const storeId = uuidv4();
    const now = new Date();
    
    const store = {
      id: storeId,
      merchantId: dto.merchantId,
      tenant_id: dto.merchantId, // 暂时使用merchantId作为tenant_id
      shop_id: storeId,
      platform: dto.platform,
      name: dto.name,
      store_name: dto.name,
      description: dto.description || '',
      platformShopId: dto.platformShopId,
      status: 'PENDING',
      created_at: now,
      updated_at: now
    };

    try {
      // 保存店铺记录
      await db(STORES_TABLE).insert(store);
      
      // 获取平台适配器
      const adapter = this.platformAdapterFactory.createAdapter(dto.platform);
      
      // 执行授权
      await adapter.authorize(dto.authInfo);
      
      // 同步店铺信息
      const shopInfo = await adapter.getShopInfo();
      
      // 更新店铺信息
      await db(STORES_TABLE)
        .where({ id: storeId })
        .update({
          name: shopInfo.name,
          store_name: shopInfo.name,
          description: shopInfo.description,
          status: 'ACTIVE',
          updated_at: new Date()
        });
      
      logger.info(`店铺绑定成功: ${dto.platform} - ${dto.platformShopId}`);
      
      // 获取更新后的店铺信息
      const updatedStore = await db(STORES_TABLE).where({ id: storeId }).first();
      return updatedStore;
    } catch (error: any) {
      logger.error(`店铺绑定失败: ${error.message}`, error.stack);
      
      // 更新店铺状态为失败
      await db(STORES_TABLE)
        .where({ id: storeId })
        .update({
          status: 'INACTIVE',
          updated_at: new Date()
        });
      
      throw error;
    }
  }

  /**
   * 同步店铺商品
   * @param storeId 店铺ID
   * @returns 同步结果
   */
  async syncProducts(storeId: string): Promise<{ success: boolean; count: number }> {
    logger.info(`开始同步店铺商品: ${storeId}`);

    const store = await db(STORES_TABLE).where({ id: storeId }).first();
    if (!store) {
      throw new Error('店铺不存在');
    }

    if (store.status !== 'ACTIVE') {
      throw new Error('店铺状态异常，无法同步商品');
    }

    try {
      const adapter = this.platformAdapterFactory.createAdapter(store.platform);
      const products = await adapter.getProducts();
      
      // 处理商品同步逻辑
      for (const product of products) {
        // 检查商品是否已存在
        const existingProduct = await db('cf_product')
          .where({
            platform: store.platform,
            product_id: product.id
          })
          .first();
        
        const now = new Date();
        const productData = {
          tenant_id: store.tenant_id,
          shop_id: storeId,
          platform: store.platform,
          product_id: product.id,
          title: product.name,
          description: product.description,
          category: product.categories && product.categories.length > 0 ? product.categories[0] : 'Other',
          brand: 'Unknown',
          price: product.price,
          cost_price: 0,
          stock: product.stock,
          sku: product.sku,
          attributes: JSON.stringify(product.attributes || {}),
          images: JSON.stringify(product.images || []),
          status: 'ACTIVE',
          updated_by: 'system',
          updated_at: now
        };
        
        if (existingProduct) {
          // 更新现有商品
          await db('cf_product')
            .where({ id: existingProduct.id })
            .update(productData);
        } else {
          // 创建新商品
          await db('cf_product').insert({
            ...productData,
            id: uuidv4(),
            created_by: 'system',
            created_at: now
          });
        }
      }
      
      logger.info(`商品同步完成: ${storeId}, 同步商品数: ${products.length}`);
      
      return {
        success: true,
        count: products.length
      };
    } catch (error: any) {
      logger.error(`商品同步失败: ${error.message}`, error.stack);
      throw error;
    }
  }

  /**
   * 同步店铺订单
   * @param storeId 店铺ID
   * @returns 同步结果
   */
  async syncOrders(storeId: string): Promise<{ success: boolean; count: number }> {
    logger.info(`开始同步店铺订单: ${storeId}`);

    const store = await db(STORES_TABLE).where({ id: storeId }).first();
    if (!store) {
      throw new Error('店铺不存在');
    }

    if (store.status !== 'ACTIVE') {
      throw new Error('店铺状态异常，无法同步订单');
    }

    try {
      const adapter = this.platformAdapterFactory.createAdapter(store.platform);
      const orders = await adapter.getOrders();
      
      // 处理订单同步逻辑
      for (const order of orders) {
        // 检查订单是否已存在
        const existingOrder = await db('cf_order')
          .where({
            platform: store.platform,
            platform_order_id: order.id
          })
          .first();
        
        const now = new Date();
        const orderData = {
          tenant_id: store.tenant_id,
          shop_id: storeId,
          platform: store.platform,
          platform_order_id: order.id,
          customer_id: order.customerId || uuidv4(),
          customer_name: order.shippingAddress?.name || 'Unknown',
          customer_email: 'unknown@example.com',
          customer_phone: '000-000-0000',
          shipping_address: JSON.stringify(order.shippingAddress || {}),
          billing_address: JSON.stringify(order.shippingAddress || {}),
          subtotal: order.totalAmount,
          shipping_fee: 0,
          tax: 0,
          total: order.totalAmount,
          currency: 'USD',
          status: order.status || 'PENDING',
          payment_method: order.paymentMethod || 'UNKNOWN',
          tracking_number: '',
          carrier: '',
          estimated_delivery: null,
          actual_delivery: null,
          updated_by: 'system',
          updated_at: now
        };
        
        if (existingOrder) {
          // 更新现有订单
          await db('cf_order')
            .where({ id: existingOrder.id })
            .update(orderData);
        } else {
          // 创建新订单
          const orderId = uuidv4();
          await db('cf_order').insert({
            ...orderData,
            id: orderId,
            created_by: 'system',
            created_at: now
          });
          
          // 同步订单明细
          if (order.items && order.items.length > 0) {
            for (const item of order.items) {
              await db('cf_order_item').insert({
                id: uuidv4(),
                order_id: orderId,
                product_id: item.productId,
                product_sku: item.productId,
                product_name: item.productName || 'Product',
                quantity: item.quantity,
                unit_price: item.unitPrice,
                total_price: item.totalPrice,
                created_by: 'system',
                updated_by: 'system',
                created_at: now,
                updated_at: now
              });
            }
          }
        }
      }
      
      logger.info(`订单同步完成: ${storeId}, 同步订单数: ${orders.length}`);
      
      return {
        success: true,
        count: orders.length
      };
    } catch (error: any) {
      logger.error(`订单同步失败: ${error.message}`, error.stack);
      throw error;
    }
  }

  /**
   * 更新商品价格
   * @param storeId 店铺ID
   * @param productId 商品ID
   * @param price 新价格
   * @returns 更新结果
   */
  async updateProductPrice(storeId: string, productId: string, price: number): Promise<boolean> {
    console.log(`开始更新商品价格: ${storeId} - ${productId} - ${price}`);

    const store = await db(STORES_TABLE).where({ id: storeId }).first();
    if (!store) {
      throw new Error('店铺不存在');
    }

    if (store.status !== 'ACTIVE') {
      throw new Error('店铺状态异常，无法更新商品价格');
    }

    try {
      const adapter = this.platformAdapterFactory.createAdapter(store.platform);
      await adapter.updateProductPrice(productId, price);
      
      console.log(`商品价格更新成功: ${storeId} - ${productId} - ${price}`);
      
      return true;
    } catch (error: any) {
      console.error(`商品价格更新失败: ${error.message}`, error.stack);
      throw error;
    }
  }

  /**
   * 获取店铺列表
   * @param merchantId 商户ID
   * @returns 店铺列表
   */
  async getStores(merchantId: string): Promise<any[]> {
    console.log(`获取商户店铺列表: ${merchantId}`);
    return db(STORES_TABLE).where({ merchantId });
  }

  /**
   * 获取店铺详情
   * @param storeId 店铺ID
   * @returns 店铺详情
   */
  async getStore(storeId: string): Promise<any> {
    console.log(`获取店铺详情: ${storeId}`);
    const store = await db(STORES_TABLE).where({ id: storeId }).first();
    if (!store) {
      throw new Error('店铺不存在');
    }
    return store;
  }

  /**
   * 停用店铺
   * @param storeId 店铺ID
   * @returns 操作结果
   */
  async deactivateStore(storeId: string): Promise<any> {
    console.log(`停用店铺: ${storeId}`);

    const store = await db(STORES_TABLE).where({ id: storeId }).first();
    if (!store) {
      throw new Error('店铺不存在');
    }

    await db(STORES_TABLE)
      .where({ id: storeId })
      .update({
        status: 'INACTIVE',
        updated_at: new Date()
      });
    
    console.log(`店铺已停用: ${storeId}`);
    
    const updatedStore = await db(STORES_TABLE).where({ id: storeId }).first();
    return updatedStore;
  }

  /**
   * 重新激活店铺
   * @param storeId 店铺ID
   * @returns 操作结果
   */
  async reactivateStore(storeId: string): Promise<any> {
    console.log(`重新激活店铺: ${storeId}`);

    const store = await db(STORES_TABLE).where({ id: storeId }).first();
    if (!store) {
      throw new Error('店铺不存在');
    }

    await db(STORES_TABLE)
      .where({ id: storeId })
      .update({
        status: 'ACTIVE',
        updated_at: new Date()
      });
    
    console.log(`店铺已重新激活: ${storeId}`);
    
    const updatedStore = await db(STORES_TABLE).where({ id: storeId }).first();
    return updatedStore;
  }
}
