import db from '../config/database';
import { v4 as uuidv4 } from 'uuid';

export interface LogisticsResource {
  id: string;
  tenantId: string;
  shopId: string;
  providerName: string;
  serviceType: 'EXPRESS' | 'STANDARD' | 'ECONOMY' | 'SAME_DAY' | 'INTERNATIONAL';
  coverageArea: string;
  apiEndpoint: string;
  apiKey: string;
  status: 'ACTIVE' | 'INACTIVE' | 'PENDING';
  rating: number;
  costPerKg: number;
  costPerPackage: number;
  estimatedDeliveryTime: string;
  trackingUrlTemplate: string;
  createdAt: Date;
  updatedAt: Date;
}

export interface LogisticsRate {
  id: string;
  tenantId: string;
  logisticsResourceId: string;
  origin: string;
  destination: string;
  weight: number;
  dimensions: string;
  rate: number;
  currency: string;
  estimatedDays: number;
  createdAt: Date;
}

export interface LogisticsTracking {
  id: string;
  tenantId: string;
  shopId: string;
  orderId: string;
  logisticsResourceId: string;
  trackingNumber: string;
  status: 'PENDING' | 'IN_TRANSIT' | 'DELIVERED' | 'FAILED';
  lastUpdate: Date;
  trackingHistory: string;
  createdAt: Date;
  updatedAt: Date;
}

export class LogisticsResourceModel {
  private static readonly TABLE_RESOURCE = 'cf_logistics_resources';
  private static readonly TABLE_RATE = 'cf_logistics_rates';
  private static readonly TABLE_TRACKING = 'cf_logistics_tracking';

  // ==================== 物流资源管理 ====================

  static async createResource(resourceData: Partial<LogisticsResource>): Promise<LogisticsResource> {
    const id = uuidv4();
    await db(this.TABLE_RESOURCE).insert({
      id,
      ...resourceData,
      created_at: new Date(),
      updated_at: new Date()
    });
    return (await this.getResourceById(id))!;
  }

  static async getResourceById(id: string): Promise<LogisticsResource | null> {
    return await db(this.TABLE_RESOURCE).where({ id }).first();
  }

  static async getResourcesByServiceType(serviceType: string): Promise<LogisticsResource[]> {
    return await db(this.TABLE_RESOURCE)
      .where({ serviceType })
      .where({ status: 'ACTIVE' })
      .orderBy('rating', 'desc');
  }

  static async updateResource(id: string, resourceData: Partial<LogisticsResource>): Promise<LogisticsResource | null> {
    await db(this.TABLE_RESOURCE).where({ id }).update({
      ...resourceData,
      updated_at: new Date()
    });
    return await this.getResourceById(id);
  }

  static async deleteResource(id: string): Promise<boolean> {
    const result = await db(this.TABLE_RESOURCE).where({ id }).delete();
    return result > 0;
  }

  // ==================== 物流费率管理 ====================

  static async createRate(rateData: Partial<LogisticsRate>): Promise<LogisticsRate> {
    const id = uuidv4();
    await db(this.TABLE_RATE).insert({
      id,
      ...rateData,
      created_at: new Date()
    });
    return (await this.getRateById(id))!;
  }

  static async getRateById(id: string): Promise<LogisticsRate | null> {
    return await db(this.TABLE_RATE).where({ id }).first();
  }

  static async getRatesByResource(resourceId: string): Promise<LogisticsRate[]> {
    return await db(this.TABLE_RATE)
      .where({ logisticsResourceId: resourceId })
      .orderBy('createdAt', 'desc');
  }

  static async calculateRate(resourceId: string, origin: string, destination: string, weight: number, dimensions: string): Promise<LogisticsRate | null> {
    // 这里可以实现具体的费率计算逻辑
    // 例如：基于距离、重量、尺寸等因素计算运费
    const resource = await this.getResourceById(resourceId);
    if (!resource) return null;

    // 简单的费率计算
    const baseRate = resource.costPerPackage + (weight * resource.costPerKg);
    const estimatedDays = 2; // 模拟估算天数

    return await this.createRate({
      logisticsResourceId: resourceId,
      origin,
      destination,
      weight,
      dimensions,
      rate: baseRate,
      currency: 'CNY',
      estimatedDays
    });
  }

  // ==================== 物流追踪 ====================

  static async createTracking(trackingData: Partial<LogisticsTracking>): Promise<LogisticsTracking> {
    const id = uuidv4();
    await db(this.TABLE_TRACKING).insert({
      id,
      ...trackingData,
      created_at: new Date(),
      updated_at: new Date()
    });
    return (await this.getTrackingById(id))!;
  }

  static async getTrackingById(id: string): Promise<LogisticsTracking | null> {
    return await db(this.TABLE_TRACKING).where({ id }).first();
  }

  static async getTrackingByOrder(orderId: string): Promise<LogisticsTracking | null> {
    return await db(this.TABLE_TRACKING).where({ orderId }).first();
  }

  static async getTrackingByNumber(trackingNumber: string): Promise<LogisticsTracking | null> {
    return await db(this.TABLE_TRACKING).where({ trackingNumber }).first();
  }

  static async updateTrackingStatus(id: string, status: 'PENDING' | 'IN_TRANSIT' | 'DELIVERED' | 'FAILED', trackingHistory?: string): Promise<LogisticsTracking | null> {
    const updateData: any = {
      status,
      lastUpdate: new Date(),
      updated_at: new Date()
    };

    if (trackingHistory) {
      updateData.trackingHistory = trackingHistory;
    }

    await db(this.TABLE_TRACKING).where({ id }).update(updateData);
    return await this.getTrackingById(id);
  }

  // ==================== 物流资源匹配 ====================

  static async findSuitableLogistics(origin: string, destination: string, weight: number, serviceType?: string): Promise<LogisticsResource[]> {
    let query = db(this.TABLE_RESOURCE).where({ status: 'ACTIVE' });

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

    // 这里可以添加更多的匹配逻辑
    // 例如：基于覆盖区域、重量限制等

    return await query.orderBy('rating', 'desc');
  }
}
