/**
 * 物流查询API路由
 * 作者: 阿瑞
 * 功能: 查询物流单号状态
 * 版本: 1.0.0
 */

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

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

/**
 * 查询物流信息处理函数
 */
const queryLogistics = async (req: RequestWithDB, params?: Record<string, unknown>) => {
  try {
    // 获取团队代码
    const teamCode = params?.teamCode as string;
    
    if (!teamCode) {
      return NextResponse.json(
        { error: '缺少团队代码参数' },
        { status: 400 }
      );
    }
    
    // 获取并验证请求参数
    const body = await req.json();
    const { id, trackingNumber, phoneLast4Digits } = body;
    
    if (!id) {
      return NextResponse.json(
        { error: '缺少记录ID' },
        { status: 400 }
      );
    }
    
    if (!trackingNumber) {
      return NextResponse.json(
        { error: '缺少物流单号' },
        { status: 400 }
      );
    }
    
    if (!phoneLast4Digits) {
      return NextResponse.json(
        { error: '缺少手机尾号' },
        { status: 400 }
      );
    }
    
    // 调用顺丰物流查询API
    const sfResult = await querySFExpress(trackingNumber, phoneLast4Digits);
    
    // 记录API调用结果，用于调试
    console.log(`物流查询结果 - 单号: ${trackingNumber}, 状态码: ${sfResult.apiResultCode}`);
    
    if (sfResult.apiResultCode !== '0000' && sfResult.apiResultCode !== 'S0000') {
      // 详细记录错误信息
      console.error(`顺丰API查询失败: ${JSON.stringify({
        id,
        trackingNumber,
        phoneLast4Digits,
        errorCode: sfResult.apiResultCode,
        errorMsg: sfResult.apiErrorMsg,
        originalError: sfResult.error
      }, null, 2)}`);
      
      return NextResponse.json(
        { 
          error: `查询物流失败: ${sfResult.apiErrorMsg}`, 
          details: sfResult,
          params: { 
            id, 
            trackingNumber,
            phoneLast4DigitsMasked: phoneLast4Digits ? `****${phoneLast4Digits.substring(Math.max(0, phoneLast4Digits.length - 4))}` : null
          }
        },
        { status: 500 }
      );
    }
    
    // 解析API返回的物流信息
    // 根据修改后的querySFExpress，结果可能直接是解析后的对象
    const resultData = typeof sfResult.apiResultData === 'string' 
      ? JSON.parse(sfResult.apiResultData) 
      : sfResult.apiResultData;

    // 获取路由信息（兼容新旧格式）
    const routeInfo = resultData?.msgData?.routeResps?.[0] || {};
    
    // 确保有有效的物流路由数据
    if (!routeInfo.routes || !Array.isArray(routeInfo.routes)) {
      console.log('顺丰API没有返回有效的物流路由数据');
    } else {
      console.log(`顺丰API返回了${routeInfo.routes.length}条物流路由记录`);
    }
    
    // 提取状态信息
    let status = null;
    if (routeInfo.routes && routeInfo.routes.length > 0) {
      const latestRoute = routeInfo.routes[0];
      
      // 根据内容识别状态
      const content = latestRoute.remark || '';
      if (content.includes('已签收')) {
        status = '已签收';
      } else if (content.includes('派送中') || content.includes('派件中')) {
        status = '运输中';
      } else if (content.includes('已收取') || content.includes('已揽件')) {
        status = '已揽件';
      }
    }
    
    // 获取数据库连接
    const connection = req.db;
    
    // 更新数据库中的物流记录
    const details = JSON.stringify({
      routes: routeInfo.routes || [],
      routeType: routeInfo.routeType,
      mailNo: routeInfo.mailNo,
      queryTime: new Date().toISOString()
    });
    
    console.log('即将更新物流记录:', {
      id,
      status,
      hasDetails: !!details
    });
    
    await connection.query(
      `UPDATE logistics_records 
       SET status = ?, 
           details = ?, 
           updated_at = CURRENT_TIMESTAMP
       WHERE id = ?`,
      [status, details, id]
    );
    
    // 获取完整的物流记录信息
    const [logisticsRecords] = await connection.query<LogisticsRecord[]>(
      `SELECT * FROM logistics_records WHERE id = ?`,
      [id]
    );
    
    if (logisticsRecords.length === 0) {
      return NextResponse.json(
        { error: '物流记录不存在' },
        { status: 404 }
      );
    }
    
    const logisticsRecord = logisticsRecords[0];
    
    // 不需要查询关联产品，直接返回物流信息即可
    
    // 返回成功响应
    return NextResponse.json({
      success: true,
      message: '查询物流信息成功',
      data: logisticsRecord,
      sfResponse: sfResult
    });
    
  } catch (error) {
    console.error('查询物流API错误:', 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 queryLogistics(dbReq, { teamCode });
    })(request);
  } catch (error) {
    console.error('处理POST请求失败:', error);
    return NextResponse.json(
      { error: '处理请求失败', details: (error as Error).message },
      { status: 500 }
    );
  }
} 