import { Logger } from '../utils/Logger';

export interface LogisticsInfo {
  orderId: string;
  trackingNumber: string;
  platform: string;
  tenantId: string;
  shopId: string;
  traceId: string;
}

export interface LogisticsStatus {
  status: 'PENDING' | 'IN_TRANSIT' | 'DELIVERED' | 'FAILED';
  trackingNumber: string;
  carrier: string;
  events: LogisticsEvent[];
  lastUpdated: string;
}

export interface LogisticsEvent {
  timestamp: string;
  location: string;
  description: string;
  status: string;
}

export interface SyncResult {
  success: boolean;
  orderId: string;
  trackingNumber: string;
  status: LogisticsStatus | null;
  error: string | null;
}

export class LogisticsSyncService {
  private logger = new Logger('LogisticsSyncService');
  private syncTasks: Map<string, NodeJS.Timeout> = new Map();

  async syncLogisticsStatus(logisticsInfo: LogisticsInfo): Promise<SyncResult> {
    try {
      this.logger.info(`开始同步物流状态: ${logisticsInfo.trackingNumber}`, {
        orderId: logisticsInfo.orderId,
        platform: logisticsInfo.platform,
        traceId: logisticsInfo.traceId
      });

      const status = await this.fetchLogisticsStatus(logisticsInfo);
      
      await this.reportStatus(logisticsInfo, status);

      return {
        success: true,
        orderId: logisticsInfo.orderId,
        trackingNumber: logisticsInfo.trackingNumber,
        status,
        error: null
      };
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '未知错误';
      this.logger.error(`物流状态同步失败: ${errorMessage}`, {
        orderId: logisticsInfo.orderId,
        trackingNumber: logisticsInfo.trackingNumber,
        traceId: logisticsInfo.traceId
      });

      return {
        success: false,
        orderId: logisticsInfo.orderId,
        trackingNumber: logisticsInfo.trackingNumber,
        status: null,
        error: errorMessage
      };
    }
  }

  async startPeriodicSync(logisticsInfo: LogisticsInfo, intervalMs: number = 3600000): Promise<string> {
    const taskId = `${logisticsInfo.orderId}_${logisticsInfo.trackingNumber}`;
    
    if (this.syncTasks.has(taskId)) {
      this.stopSync(taskId);
    }

    const timeout = setInterval(async () => {
      await this.syncLogisticsStatus(logisticsInfo);
    }, intervalMs);

    this.syncTasks.set(taskId, timeout);
    this.logger.info(`启动周期性物流同步任务: ${taskId}`, {
      intervalMs,
      traceId: logisticsInfo.traceId
    });

    return taskId;
  }

  stopSync(taskId: string): void {
    const timeout = this.syncTasks.get(taskId);
    if (timeout) {
      clearInterval(timeout);
      this.syncTasks.delete(taskId);
      this.logger.info(`停止物流同步任务: ${taskId}`);
    }
  }

  private async fetchLogisticsStatus(logisticsInfo: LogisticsInfo): Promise<LogisticsStatus> {
    switch (logisticsInfo.platform.toLowerCase()) {
      case 'tiktok':
        return await this.fetchTikTokLogistics(logisticsInfo);
      case 'temu':
        return await this.fetchTemuLogistics(logisticsInfo);
      case '1688':
        return await this.fetch1688Logistics(logisticsInfo);
      default:
        throw new Error(`不支持的平台: ${logisticsInfo.platform}`);
    }
  }

  private async fetchTikTokLogistics(logisticsInfo: LogisticsInfo): Promise<LogisticsStatus> {
    this.logger.debug('查询TikTok物流状态', {
      trackingNumber: logisticsInfo.trackingNumber,
      traceId: logisticsInfo.traceId
    });

    return {
      status: 'IN_TRANSIT',
      trackingNumber: logisticsInfo.trackingNumber,
      carrier: 'TikTok Logistics',
      events: [
        {
          timestamp: new Date().toISOString(),
          location: '仓库',
          description: '包裹已发出',
          status: 'SHIPPED'
        },
        {
          timestamp: new Date(Date.now() - 86400000).toISOString(),
          location: '分拣中心',
          description: '包裹已到达分拣中心',
          status: 'IN_TRANSIT'
        }
      ],
      lastUpdated: new Date().toISOString()
    };
  }

  private async fetchTemuLogistics(logisticsInfo: LogisticsInfo): Promise<LogisticsStatus> {
    this.logger.debug('查询Temu物流状态', {
      trackingNumber: logisticsInfo.trackingNumber,
      traceId: logisticsInfo.traceId
    });

    return {
      status: 'IN_TRANSIT',
      trackingNumber: logisticsInfo.trackingNumber,
      carrier: 'Temu Shipping',
      events: [
        {
          timestamp: new Date().toISOString(),
          location: '国际物流中心',
          description: '包裹正在国际运输中',
          status: 'IN_TRANSIT'
        },
        {
          timestamp: new Date(Date.now() - 172800000).toISOString(),
          location: '发货仓库',
          description: '包裹已发货',
          status: 'SHIPPED'
        }
      ],
      lastUpdated: new Date().toISOString()
    };
  }

  private async fetch1688Logistics(logisticsInfo: LogisticsInfo): Promise<LogisticsStatus> {
    this.logger.debug('查询1688物流状态', {
      trackingNumber: logisticsInfo.trackingNumber,
      traceId: logisticsInfo.traceId
    });

    return {
      status: 'DELIVERED',
      trackingNumber: logisticsInfo.trackingNumber,
      carrier: '1688 Express',
      events: [
        {
          timestamp: new Date().toISOString(),
          location: '目的地',
          description: '包裹已签收',
          status: 'DELIVERED'
        },
        {
          timestamp: new Date(Date.now() - 86400000).toISOString(),
          location: '当地配送中心',
          description: '包裹正在派送中',
          status: 'OUT_FOR_DELIVERY'
        },
        {
          timestamp: new Date(Date.now() - 172800000).toISOString(),
          location: '发货地',
          description: '包裹已发出',
          status: 'SHIPPED'
        }
      ],
      lastUpdated: new Date().toISOString()
    };
  }

  private async reportStatus(logisticsInfo: LogisticsInfo, status: LogisticsStatus): Promise<void> {
    try {
      const reportData = {
        orderId: logisticsInfo.orderId,
        trackingNumber: logisticsInfo.trackingNumber,
        platform: logisticsInfo.platform,
        status,
        tenantId: logisticsInfo.tenantId,
        shopId: logisticsInfo.shopId,
        traceId: logisticsInfo.traceId,
        timestamp: new Date().toISOString()
      };

      const response = await fetch('http://localhost:3000/api/logistics/status', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(reportData)
      });

      if (!response.ok) {
        throw new Error(`上报物流状态失败: ${response.statusText}`);
      }

      this.logger.info('物流状态上报成功', {
        orderId: logisticsInfo.orderId,
        traceId: logisticsInfo.traceId
      });
    } catch (error) {
      this.logger.error('物流状态上报失败', {
        error: error instanceof Error ? error.message : '未知错误',
        orderId: logisticsInfo.orderId,
        traceId: logisticsInfo.traceId
      });
    }
  }

  getActiveSyncTasks(): string[] {
    return Array.from(this.syncTasks.keys());
  }

  clearAllTasks(): void {
    this.syncTasks.forEach((timeout, taskId) => {
      clearInterval(timeout);
    });
    this.syncTasks.clear();
    this.logger.info('已清除所有物流同步任务');
  }
}
