/**
 * 物流记录API路由
 * 作者: 阿瑞
 * 功能: 提供物流记录的查询和创建接口
 * 版本: 1.0.0
 */

import { NextRequest, NextResponse } from 'next/server';
import { RowDataPacket, ResultSetHeader } from 'mysql2/promise';
import { RequestWithDB, connectTeamDB } from '@/lib/db';
import { RecordType } from '@/models/team/types/ILogisticsRecord';

/**
 * 物流记录请求参数接口
 */
interface LogisticsRequestParams {
  salesRecordId: number;
  trackingNumber: string;
  company: string;
  customerTailNumber: string;
  isQueryable: boolean;
  products: {
    productId: number;
    quantity: number;
  }[];
}

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

/**
 * 物流产品数据接口
 */
interface LogisticsProduct extends RowDataPacket {
  id: number;
  logistics_id: number;
  product_id: number;
  quantity: number;
  created_at: string;
}

/**
 * 创建物流记录
 */
const createLogisticsRecord = async (req: RequestWithDB, params?: Record<string, unknown>) => {
  try {
    // 正确处理动态路由参数
    const teamCode = params?.teamCode as string;
    
    if (!teamCode) {
      return NextResponse.json(
        { error: '缺少团队代码参数' },
        { status: 400 }
      );
    }

    // 解析请求数据
    const requestData: LogisticsRequestParams = await req.json();
    const {
      salesRecordId,
      trackingNumber,
      company,
      customerTailNumber,
      isQueryable,
      products
    } = requestData;

    // 数据验证
    if (!salesRecordId) {
      return NextResponse.json(
        { error: '销售记录ID不能为空' },
        { status: 400 }
      );
    }

    if (!trackingNumber) {
      return NextResponse.json(
        { error: '物流单号不能为空' },
        { status: 400 }
      );
    }

    if (!company) {
      return NextResponse.json(
        { error: '物流公司不能为空' },
        { status: 400 }
      );
    }

    if (!customerTailNumber) {
      return NextResponse.json(
        { error: '客户手机尾号不能为空' },
        { status: 400 }
      );
    }

    if (!products || !Array.isArray(products) || products.length === 0) {
      return NextResponse.json(
        { error: '发货产品不能为空' },
        { status: 400 }
      );
    }

    // 获取数据库连接
    const connection = req.db;

    // 检查销售记录是否存在
    const [salesRecords] = await connection.query<RowDataPacket[]>(
      'SELECT id, order_status FROM sales_records WHERE id = ?',
      [salesRecordId]
    );

    if (salesRecords.length === 0) {
      return NextResponse.json(
        { error: '销售记录不存在' },
        { status: 404 }
      );
    }

    // 检查销售记录是否已有物流记录
    const [existingLogistics] = await connection.query<LogisticsRecord[]>(
      `SELECT id FROM logistics_records 
       WHERE record_id = ? AND record_type = ?`,
      [salesRecordId, RecordType.SALES_RECORD]
    );

    let logisticsId: number;
    let isUpdate = false;

    if (existingLogistics.length > 0) {
      // 更新现有物流记录
      isUpdate = true;
      logisticsId = existingLogistics[0].id;
      
      await connection.query(
        `UPDATE logistics_records 
         SET tracking_number = ?, 
             is_queryable = ?, 
             customer_tail_number = ?, 
             company = ?, 
             updated_at = CURRENT_TIMESTAMP
         WHERE id = ?`,
        [
          trackingNumber,
          isQueryable,
          customerTailNumber,
          company,
          logisticsId
        ]
      );
      
      // 删除旧的产品关联
      await connection.query(
        `DELETE FROM logistics_products WHERE logistics_id = ?`,
        [logisticsId]
      );

      // 更新记录时不改变订单状态
    } else {
      // 创建新物流记录
      const [logisticsResult] = await connection.query<ResultSetHeader>(
        `INSERT INTO logistics_records 
          (tracking_number, is_queryable, customer_tail_number, company, status, record_id, record_type) 
         VALUES (?, ?, ?, ?, ?, ?, ?)`,
        [
          trackingNumber,
          isQueryable,
          customerTailNumber,
          company,
          '已填单',  // 初始状态改为已填单
          salesRecordId,
          RecordType.SALES_RECORD
        ]
      );

      logisticsId = logisticsResult.insertId;

      // 更新销售记录的订单状态（仅对新记录）
      // 确保初始状态为"已填单"
      await connection.query(
        `UPDATE sales_records 
         SET order_status = 
           CASE 
             WHEN order_status IS NULL THEN JSON_ARRAY('已填单') 
             ELSE order_status
           END
         WHERE id = ?`,
        [salesRecordId]
      );
    }

    // 批量插入物流产品关联记录
    if (products.length > 0) {
      const logisticsProductValues = products.map(product => [
        logisticsId,
        product.productId,
        product.quantity
      ]);

      await connection.query(
        `INSERT INTO logistics_products (logistics_id, product_id, quantity) VALUES ?`,
        [logisticsProductValues]
      );
    }

    // 查询更新后的物流记录详情
    const [logisticsRecords] = await connection.query<LogisticsRecord[]>(
      `SELECT * FROM logistics_records WHERE id = ?`,
      [logisticsId]
    );

    const createdLogistics = logisticsRecords[0];

    // 查询关联的产品信息
    const [logisticsProducts] = await connection.query<LogisticsProduct[]>(
      `SELECT 
        lp.id, lp.logistics_id, lp.product_id, lp.quantity, lp.created_at,
        p.name as product_name, p.code as product_code, p.image
       FROM logistics_products lp
       JOIN products p ON lp.product_id = p.id
       WHERE lp.logistics_id = ?`,
      [logisticsId]
    );

    return NextResponse.json({
      success: true,
      message: isUpdate ? '物流记录更新成功' : '物流记录创建成功',
      data: {
        ...createdLogistics,
        products: logisticsProducts
      }
    });

  } catch (error) {
    console.error('创建物流记录失败:', error);
    return NextResponse.json(
      { error: '创建物流记录失败', details: (error as Error).message },
      { status: 500 }
    );
  }
};

/**
 * 获取物流记录列表
 */
const getLogisticsRecords = async (req: RequestWithDB, params?: Record<string, unknown>) => {
  try {
    // 正确处理动态路由参数
    const teamCode = params?.teamCode as string;
    
    if (!teamCode) {
      return NextResponse.json(
        { error: '缺少团队代码参数' },
        { status: 400 }
      );
    }

    // 获取查询参数
    const url = new URL(req.url);
    const page = parseInt(url.searchParams.get('page') || '1');
    const pageSize = parseInt(url.searchParams.get('pageSize') || '10');
    const recordId = url.searchParams.get('recordId') || '';
    const recordType = url.searchParams.get('recordType') || '';
    const trackingNumber = url.searchParams.get('trackingNumber') || '';
    
    // 计算偏移量
    const offset = (page - 1) * pageSize;

    // 构建查询条件
    const conditions = [];
    const queryParams = [];
    
    if (recordId) {
      conditions.push('lr.record_id = ?');
      queryParams.push(recordId);
    }
    
    if (recordType) {
      conditions.push('lr.record_type = ?');
      queryParams.push(recordType);
    }
    
    if (trackingNumber) {
      conditions.push('lr.tracking_number LIKE ?');
      queryParams.push(`%${trackingNumber}%`);
    }
    
    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
    
    // 使用数据库连接
    const connection = req.db;
    
    // 查询总数
    const countSql = `
      SELECT COUNT(*) as total 
      FROM logistics_records lr
      ${whereClause}
    `;
    const [totalRows] = await connection.query<RowDataPacket[]>(countSql, queryParams);
    
    const total = totalRows[0].total as number;
    
    // 查询分页数据
    const querySql = `
      SELECT 
        lr.id, lr.tracking_number, lr.is_queryable, lr.customer_tail_number,
        lr.company, lr.status, lr.record_id, lr.record_type,
        lr.created_at, lr.updated_at
      FROM logistics_records lr
      ${whereClause}
      ORDER BY lr.created_at DESC
      LIMIT ? OFFSET ?
    `;
    
    // 添加分页参数
    const paginatedParams = [...queryParams, pageSize, offset];
    
    const [rows] = await connection.query<LogisticsRecord[]>(querySql, paginatedParams);
    
    // 查询每条物流记录关联的产品
    const logisticsRecords = rows;
    
    if (logisticsRecords.length > 0) {
      for (let i = 0; i < logisticsRecords.length; i++) {
        const record = logisticsRecords[i];
        
        // 查询关联产品
        const [productRows] = await connection.query<LogisticsProduct[]>(`
          SELECT 
            lp.id, lp.logistics_id, lp.product_id, lp.quantity, lp.created_at,
            p.name as product_name, p.code as product_code, p.image
          FROM logistics_products lp
          JOIN products p ON lp.product_id = p.id
          WHERE lp.logistics_id = ?
        `, [record.id]);
        
        record.products = productRows;
      }
    }
    
    return NextResponse.json({
      total,
      records: logisticsRecords
    });
    
  } catch (error) {
    console.error('获取物流记录列表失败:', error);
    return NextResponse.json(
      { error: '获取物流记录列表失败', details: (error as Error).message },
      { status: 500 }
    );
  }
};

/**
 * 获取单个物流记录详情
 */
const getLogisticsRecord = async (req: RequestWithDB, params?: Record<string, unknown>) => {
  try {
    // 正确处理动态路由参数
    const teamCode = params?.teamCode as string;
    const logisticsId = params?.logisticsId as string;
    
    if (!teamCode || !logisticsId) {
      return NextResponse.json(
        { error: '缺少必要参数' },
        { status: 400 }
      );
    }

    // 使用数据库连接
    const connection = req.db;
    
    // 查询物流记录
    const [logisticsRecords] = await connection.query<LogisticsRecord[]>(
      `SELECT * FROM logistics_records WHERE id = ?`,
      [logisticsId]
    );
    
    if (logisticsRecords.length === 0) {
      return NextResponse.json(
        { error: '物流记录不存在' },
        { status: 404 }
      );
    }
    
    const logisticsRecord = logisticsRecords[0];
    
    // 查询关联产品
    const [productRows] = await connection.query<LogisticsProduct[]>(`
      SELECT 
        lp.id, lp.logistics_id, lp.product_id, lp.quantity, lp.created_at,
        p.name as product_name, p.code as product_code, p.image
      FROM logistics_products lp
      JOIN products p ON lp.product_id = p.id
      WHERE lp.logistics_id = ?
    `, [logisticsId]);
    
    logisticsRecord.products = productRows;
    
    return NextResponse.json({
      record: logisticsRecord
    });
    
  } catch (error) {
    console.error('获取物流记录详情失败:', error);
    return NextResponse.json(
      { error: '获取物流记录详情失败', details: (error as Error).message },
      { status: 500 }
    );
  }
};

/**
 * 处理GET请求 - 获取物流记录列表
 */
export async function GET(request: NextRequest) {
  try {
    // 从URL路径中提取团队代码
    const pathname = request.nextUrl.pathname;
    const teamCode = pathname.split('/')[3]; // /api/team/[teamCode]/...
    
    // 检查是否请求单个物流记录
    if (pathname.includes('/logistics/')) {
      const pathParts = pathname.split('/');
      const logisticsId = pathParts[pathParts.length - 1];
      
      if (logisticsId && /^\d+$/.test(logisticsId)) {
        return connectTeamDB((dbReq: RequestWithDB) => {
          return getLogisticsRecord(dbReq, { 
            teamCode, 
            logisticsId 
          });
        })(request);
      }
    }
    
    // 否则返回物流记录列表
    return connectTeamDB((dbReq: RequestWithDB) => {
      return getLogisticsRecords(dbReq, { teamCode });
    })(request);
  } catch (error) {
    console.error('处理GET请求失败:', error);
    return NextResponse.json(
      { error: '处理请求失败', details: (error as 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 createLogisticsRecord(dbReq, { teamCode });
    })(request);
  } catch (error) {
    console.error('处理POST请求失败:', error);
    return NextResponse.json(
      { error: '处理请求失败', details: (error as Error).message },
      { status: 500 }
    );
  }
} 