package com.erp.logistics.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.erp.logistics.entity.LogisticsTrace;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 物流轨迹Mapper
 */
@Mapper
public interface LogisticsTraceMapper extends BaseMapper<LogisticsTrace> {

    /**
     * 根据运单号查询轨迹（按时间升序）
     */
    @Select("SELECT * FROM logistics_trace WHERE waybill_no = #{waybillNo} AND deleted = 0 ORDER BY trace_time ASC")
    List<LogisticsTrace> selectByWaybillNoOrderByTime(@Param("waybillNo") String waybillNo);

    /**
     * 检查轨迹是否已存在（用于去重）
     */
    @Select("SELECT COUNT(*) FROM logistics_trace WHERE waybill_no = #{waybillNo} " +
            "AND trace_time = #{traceTime} AND location = #{location} AND deleted = 0")
    int countExist(@Param("waybillNo") String waybillNo,
                   @Param("traceTime") LocalDateTime traceTime,
                   @Param("location") String location);

    /**
     * 查询某时间范围内的轨迹
     */
    @Select("SELECT * FROM logistics_trace WHERE waybill_no = #{waybillNo} " +
            "AND trace_time BETWEEN #{startTime} AND #{endTime} AND deleted = 0 " +
            "ORDER BY trace_time ASC")
    List<LogisticsTrace> selectByTimeRange(
            @Param("waybillNo") String waybillNo,
            @Param("startTime") LocalDateTime startTime,
            @Param("endTime") LocalDateTime endTime
    );
}
