/**
 * 物流状态批量更新API路由
 * 作者: 阿瑞
 * 功能: 批量更新物流记录状态
 * 版本: 1.0.0
 */

import { NextRequest, NextResponse } from 'next/server';
import { RowDataPacket } from 'mysql2/promise';
import { RequestWithDB, connectTeamDB } from '@/lib/db';
import { querySFExpress } from '@/utils/querySFExpress';

/**
 * 物流记录数据接口
 */
interface LogisticsRecord extends RowDataPacket {
  id: number;
  tracking_number: string;
  is_queryable: boolean;
  customer_tail_number: string;
  company: string;
  status?: string;
  details?: string;
  record_id: number;
  record_type: string;
  created_at: string;
  updated_at: string;
}

/**
 * 批量更新物流状态处理函数
 */
const updateLogisticsStatus = async (req: RequestWithDB, params?: Record<string, unknown>) => {
  try {
    // 获取团队代码
    const teamCode = params?.teamCode as string;
    
    if (!teamCode) {
      return NextResponse.json(
        { error: '缺少团队代码参数' },
        { status: 400 }
      );
    }
    
    // 获取数据库连接
    const connection = req.db;
    
    // 查询需要更新的物流记录（只查询未签收且可查询的记录）
    const [logisticsRecords] = await connection.query<LogisticsRecord[]>(`
      SELECT id, tracking_number, customer_tail_number, status, is_queryable
      FROM logistics_records 
      WHERE 
        is_queryable = 1 
        AND customer_tail_number IS NOT NULL 
        AND tracking_number IS NOT NULL
        AND (status IS NULL OR status != '已签收')
      LIMIT 50
    `);
    
    if (logisticsRecords.length === 0) {
      return NextResponse.json({
        success: true,
        message: '没有需要更新的物流记录',
        updatedCount: 0
      });
    }
    
    // 记录更新结果
    const results = {
      success: 0,
      failed: 0,
      skipped: 0,
      errors: [] as string[]
    };
    
    // 逐条更新物流记录
    for (const record of logisticsRecords) {
      try {
        // 跳过无法查询的记录
        if (!record.is_queryable || !record.tracking_number || !record.customer_tail_number) {
          results.skipped++;
          continue;
        }
        
        // 调用顺丰查询API
        const sfResult = await querySFExpress(record.tracking_number, record.customer_tail_number);
        
        // 记录API调用结果，用于调试
        console.log(`批量更新 - 物流查询结果 - ID: ${record.id}, 单号: ${record.tracking_number}, 状态码: ${sfResult.apiResultCode}`);
        
        if (sfResult.apiResultCode !== '0000' && sfResult.apiResultCode !== 'S0000') {
          // 详细记录错误信息
          console.error(`批量更新 - 顺丰API查询失败: ${JSON.stringify({
            id: record.id,
            trackingNumber: record.tracking_number,
            phoneLast4Digits: record.customer_tail_number,
            errorCode: sfResult.apiResultCode,
            errorMsg: sfResult.apiErrorMsg,
            originalError: sfResult.error
          }, null, 2)}`);
          
          results.failed++;
          results.errors.push(`记录ID ${record.id}: ${sfResult.apiErrorMsg} (错误码: ${sfResult.apiResultCode})`);
          continue;
        }
        
        // 解析API返回的物流信息
        const resultData = typeof sfResult.apiResultData === 'string' 
          ? JSON.parse(sfResult.apiResultData) 
          : sfResult.apiResultData;
          
        // 获取路由信息（兼容新旧格式）  
        const routeInfo = resultData?.msgData?.routeResps?.[0] || {};
        
        // 提取状态信息
        let status = null;
        if (routeInfo.routes && routeInfo.routes.length > 0) {
          const latestRoute = routeInfo.routes[0];
          
          // 根据内容识别状态
          const content = latestRoute.content || '';
          if (content.includes('已签收')) {
            status = '已签收';
          } else if (content.includes('派送中') || content.includes('派件中')) {
            status = '运输中';
          } else if (content.includes('已收取') || content.includes('已揽件')) {
            status = '已揽件';
          }
        }
        
        // 更新数据库中的物流记录
        const details = resultData ? JSON.stringify({
          routes: routeInfo.routes || [],
          routeType: routeInfo.routeType,
          mailNo: routeInfo.mailNo,
          queryTime: new Date().toISOString()
        }) : null;
        
        await connection.query(
          `UPDATE logistics_records 
           SET status = ?, 
               details = ?, 
               updated_at = CURRENT_TIMESTAMP
           WHERE id = ?`,
          [status, details, record.id]
        );
        
        results.success++;
      } catch (error) {
        console.error(`更新物流记录 ${record.id} 失败:`, error);
        results.failed++;
        results.errors.push(`记录ID ${record.id}: ${error instanceof Error ? error.message : String(error)}`);
      }
    }
    
    // 返回更新结果
    return NextResponse.json({
      success: true,
      message: '物流状态更新完成',
      total: logisticsRecords.length,
      results
    });
    
  } catch (error) {
    console.error('批量更新物流状态失败:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : '批量更新物流状态失败' },
      { status: 500 }
    );
  }
};

/**
 * 处理POST请求
 */
export async function POST(request: NextRequest) {
  try {
    // 从URL路径中提取团队代码
    const pathname = request.nextUrl.pathname;
    const teamCode = pathname.split('/')[3]; // /api/team/[teamCode]/...
    
    return connectTeamDB((dbReq: RequestWithDB) => {
      return updateLogisticsStatus(dbReq, { teamCode });
    })(request);
  } catch (error) {
    console.error('处理POST请求失败:', error);
    return NextResponse.json(
      { error: '处理请求失败', details: (error as Error).message },
      { status: 500 }
    );
  }
} 