/**
 * 物流定时任务初始化API路由
 * 作者: 阿瑞
 * 功能: 初始化物流查询定时任务
 * 版本: 1.0.0
 */

import { NextRequest, NextResponse } from 'next/server';
import * as nodeCron from 'node-cron';
import { RequestWithDB, connectTeamDB } from '@/lib/db';
import { querySFExpress } from '@/utils/querySFExpress';
import { RowDataPacket, Connection } from 'mysql2/promise';

// 存储正在运行的cron任务
const runningCronTasks: Record<string, nodeCron.ScheduledTask> = {};

// 存储任务状态
const cronTaskStatus: Record<string, {
  lastRunTime: string | null;
  nextScheduledTime: string | null;
  currentStatus: 'idle' | 'running' | 'completed' | 'failed';
  runCount: number;
}> = {};

/**
 * 查询需要更新的物流记录
 */
async function fetchPendingLogistics(db: Connection, teamCode: string) {
  try {
    // 查询满足条件的物流记录：顺丰快递、可查询的、状态不是已签收
    const [records] = await db.query(`
      SELECT 
        id, 
        tracking_number, 
        customer_tail_number,
        company,
        status
      FROM 
        logistics_records
      WHERE 
        company = '顺丰速运' 
        AND is_queryable = 1
        AND (status IS NULL OR status != '已签收')
      LIMIT 100
    `) as [RowDataPacket[], unknown];

    return records;
  } catch (error) {
    console.error(`[${teamCode}] 查询待更新物流记录失败:`, error);
    return [];
  }
}

/**
 * 更新物流记录状态
 */
async function updateLogisticsStatus(db: Connection, record: Record<string, unknown>, sfResponse: Record<string, unknown>, teamCode: string) {
  try {
    // 解析API返回的物流信息
    const resultData = typeof sfResponse.apiResultData === 'string' 
      ? JSON.parse(sfResponse.apiResultData) 
      : sfResponse.apiResultData;
      
    // 获取路由信息（兼容新旧格式）  
    const routeInfo = resultData?.msgData?.routeResps?.[0] || {};
    
    // 提取状态信息
    let status = null;
    let details = null;
    
    // 处理有路由数据的情况
    if (routeInfo.routes && Array.isArray(routeInfo.routes) && routeInfo.routes.length > 0) {
      // 保存完整的物流详情
      details = JSON.stringify(routeInfo);
      
      // 分析最新的物流状态
      const latestRoute = routeInfo.routes[0];
      const content = latestRoute.remark || latestRoute.content || '';
      
      // 根据描述内容识别状态
      if (content.includes('已签收') || content.includes('签收')) {
        status = '已签收';
      } else if (content.includes('派送') || content.includes('派件')) {
        status = '派送中';
      } else if (content.includes('运输') || content.includes('发往')) {
        status = '运输中';
      } else if (content.includes('已揽收') || content.includes('揽件') || content.includes('已收取')) {
        status = '已揽件';
      } else {
        status = '已填单';
      }
    }
    
    // 更新数据库记录
    if (status || details) {
      console.log(`[${teamCode}] 更新物流状态: ID=${record.id}, 状态=${status}`);
      
      const updateFields = [];
      const updateValues = [];
      
      if (status) {
        updateFields.push('status = ?');
        updateValues.push(status);
      }
      
      if (details) {
        updateFields.push('details = ?');
        updateValues.push(details);
      }
      
      if (updateFields.length > 0) {
        updateFields.push('updated_at = CURRENT_TIMESTAMP');
        
        const updateQuery = `
          UPDATE logistics_records
          SET ${updateFields.join(', ')}
          WHERE id = ?
        `;
        
        await db.query(updateQuery, [...updateValues, record.id]);
        return true;
      }
    }
    
    return false;
  } catch (error) {
    console.error(`[${teamCode}] 更新物流记录状态失败:`, error);
    return false;
  }
}

/**
 * 执行物流记录更新
 */
async function executeUpdate(teamCode: string) {
  console.log(`[${teamCode}] 开始自动查询物流记录...`);
  
  // 更新状态
  cronTaskStatus[teamCode] = {
    ...cronTaskStatus[teamCode] || {},
    currentStatus: 'running',
    lastRunTime: new Date().toISOString()
  };
  
  let successCount = 0;
  let errorCount = 0;
  
  try {
    // 使用connectTeamDB创建带连接的请求
    // 创建正确的请求对象，确保包含团队标识
    const url = new URL(`http://localhost/api/cron/init`);
    url.searchParams.set('teamId', teamCode);
    
    const headers = new Headers();
    headers.set('x-team-id', teamCode);
    
    const request = new NextRequest(url, {
      method: 'GET',
      headers
    });
    
    return await connectTeamDB(async (req: RequestWithDB) => {
      const db = req.db;
      
      // 查询需要更新的物流记录
      const records = await fetchPendingLogistics(db, teamCode);
      console.log(`[${teamCode}] 找到 ${records.length} 条需更新的物流记录`);
      
      // 逐个更新物流记录
      for (const record of records) {
        try {
          const trackingNumber = record.tracking_number;
          const phoneLast4Digits = record.customer_tail_number;
          
          // 跳过无效记录
          if (!trackingNumber || !phoneLast4Digits) {
            errorCount++;
            continue;
          }
          
          // 调用顺丰API查询物流
          console.log(`[${teamCode}] 查询物流: ${trackingNumber}, 手机尾号: ${phoneLast4Digits}`);
          const sfResponse = await querySFExpress(trackingNumber, phoneLast4Digits);
          
          // 处理API错误
          if (sfResponse.apiResultCode !== '0000' && sfResponse.apiResultCode !== 'S0000') {
            console.error(`[${teamCode}] 物流API错误: ${sfResponse.apiErrorMsg}`);
            errorCount++;
            continue;
          }
          
          // 更新物流状态
          const updated = await updateLogisticsStatus(db, record, sfResponse, teamCode);
          if (updated) {
            successCount++;
          }
        } catch (error) {
          console.error(`[${teamCode}] 处理物流记录失败:`, error);
          errorCount++;
        }
      }
      
      console.log(`[${teamCode}] 物流记录更新完成: 成功=${successCount}, 失败=${errorCount}`);
      
      // 更新任务状态
      cronTaskStatus[teamCode] = {
        ...cronTaskStatus[teamCode],
        currentStatus: 'completed',
        runCount: (cronTaskStatus[teamCode]?.runCount || 0) + 1
      };
      
      return NextResponse.json({
        success: true,
        message: '物流记录查询完成',
        results: {
          successCount,
          errorCount,
          totalProcessed: records.length
        }
      });
    })(request);
  } catch (error) {
    console.error(`[${teamCode}] 执行物流更新失败:`, error);
    
    // 更新任务状态为失败
    cronTaskStatus[teamCode] = {
      ...cronTaskStatus[teamCode],
      currentStatus: 'failed'
    };
    
    return NextResponse.json(
      { success: false, error: '执行物流更新失败' },
      { status: 500 }
    );
  }
}

/**
 * 启动定时更新任务
 */
function startCronTask(teamCode: string) {
  // 检查是否已存在任务
  if (runningCronTasks[teamCode]) {
    console.log(`[${teamCode}] 物流定时任务已在运行中`);
    return false;
  }
  
  console.log(`[${teamCode}] 启动物流定时任务`);
  
  try {
    // 创建定时任务 - 每2小时执行一次
    runningCronTasks[teamCode] = nodeCron.schedule('0 */2 * * *', async () => {
      await executeUpdate(teamCode);
    });
    
    // 计算下次执行时间
    const now = new Date();
    const currentHour = now.getHours();
    const nextHour = currentHour + (currentHour % 2 === 0 ? 2 : 1);
    const nextRunDate = new Date(now);
    nextRunDate.setHours(nextHour, 0, 0, 0);
    
    // 初始化任务状态
    cronTaskStatus[teamCode] = {
      lastRunTime: null,
      nextScheduledTime: nextRunDate.toISOString(),
      currentStatus: 'idle',
      runCount: 0
    };
    
    console.log(`[${teamCode}] 物流定时任务已启动，下次执行时间: ${nextRunDate.toISOString()}`);
    return true;
  } catch (error) {
    console.error(`[${teamCode}] 启动物流定时任务失败:`, error);
    return false;
  }
}

/**
 * GET 路由处理函数 - 获取任务状态或初始化任务
 */
export async function GET(request: NextRequest) {
  try {
    // 从查询参数中获取团队代码
    const { searchParams } = new URL(request.url);
    const teamCode = searchParams.get('teamCode');
    
    if (!teamCode) {
      return NextResponse.json(
        { success: false, error: '缺少团队代码参数' },
        { status: 400 }
      );
    }
    
    // 将teamCode添加到请求头和查询参数，用于数据库连接
    const headers = new Headers(request.headers);
    headers.set('x-team-id', teamCode);
    
    // 克隆请求并添加团队标识
    const url = new URL(request.url);
    url.searchParams.set('teamId', teamCode);
    
    // 检查是否需要初始化
    const shouldInit = searchParams.get('init') === 'true';
    const runNow = searchParams.get('runNow') === 'true';
    
    // 根据参数决定启动还是获取状态
    if (shouldInit) {
      const initialized = startCronTask(teamCode);
      
      if (initialized) {
        // 如果需要立即执行一次
        if (runNow) {
          // 直接使用executeUpdate函数
          await executeUpdate(teamCode);
        }
        
        return NextResponse.json({
          success: true,
          message: '物流定时任务已初始化',
          status: cronTaskStatus[teamCode]
        });
      } else {
        return NextResponse.json({
          success: true,
          message: '物流定时任务已在运行中',
          status: cronTaskStatus[teamCode]
        });
      }
    }
    
    // 返回任务状态
    return NextResponse.json({
      success: true,
      taskExists: !!runningCronTasks[teamCode],
      status: cronTaskStatus[teamCode] || {
        lastRunTime: null,
        nextScheduledTime: null,
        currentStatus: 'idle',
        runCount: 0
      }
    });
  } catch (error) {
    console.error('物流定时任务初始化/查询失败:', error);
    return NextResponse.json(
      { success: false, error: '物流定时任务初始化/查询失败' },
      { status: 500 }
    );
  }
}

/**
 * POST 路由处理函数 - 手动触发更新
 */
export async function POST(request: NextRequest) {
  try {
    // 从查询参数中获取团队代码
    const { searchParams } = new URL(request.url);
    const teamCode = searchParams.get('teamCode');
    
    if (!teamCode) {
      return NextResponse.json(
        { success: false, error: '缺少团队代码参数' },
        { status: 400 }
      );
    }
    
    // 将teamCode添加到请求头和查询参数，用于数据库连接
    const headers = new Headers(request.headers);
    headers.set('x-team-id', teamCode);
    
    // 克隆请求并添加团队标识
    const url = new URL(request.url);
    url.searchParams.set('teamId', teamCode);
    
    // 确保任务已初始化
    if (!runningCronTasks[teamCode]) {
      startCronTask(teamCode);
    }
    
    // 立即执行更新
    return await executeUpdate(teamCode);
    
  } catch (error) {
    console.error('手动触发物流更新失败:', error);
    return NextResponse.json(
      { success: false, error: '手动触发物流更新失败' },
      { status: 500 }
    );
  }
} 