package com.erp.logistics.mapper;

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

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

/**
 * 运单状态Mapper
 */
@Mapper
public interface WaybillStatusMapper extends BaseMapper<WaybillStatus> {

    /**
     * 查询待同步运单（超过指定分钟未更新且need_sync=1）
     */
    @Select("SELECT * FROM logistics_waybill_status " +
            "WHERE deleted = 0 AND need_sync = 1 AND sync_status IN (0, 3) " +
            "AND sync_retry_count < #{maxRetry} " +
            "AND (last_trace_time IS NULL OR last_trace_time < #{thresholdTime}) " +
            "ORDER BY updated_at ASC LIMIT #{limit}")
    List<WaybillStatus> selectPendingSync(
            @Param("maxRetry") Integer maxRetry,
            @Param("thresholdTime") LocalDateTime thresholdTime,
            @Param("limit") Integer limit
    );

    /**
     * 按物流商查询待同步运单
     */
    @Select("SELECT * FROM logistics_waybill_status " +
            "WHERE deleted = 0 AND need_sync = 1 AND sync_status IN (0, 3) " +
            "AND carrier = #{carrier} " +
            "AND sync_retry_count < #{maxRetry} " +
            "ORDER BY updated_at ASC LIMIT #{limit}")
    List<WaybillStatus> selectPendingSyncByCarrier(
            @Param("carrier") String carrier,
            @Param("maxRetry") Integer maxRetry,
            @Param("limit") Integer limit
    );

    /**
     * 更新同步状态
     */
    @Update("UPDATE logistics_waybill_status SET sync_status = #{syncStatus}, " +
            "sync_retry_count = #{retryCount}, sync_fail_reason = #{failReason}, " +
            "updated_at = NOW() WHERE id = #{id}")
    int updateSyncStatus(
            @Param("id") Long id,
            @Param("syncStatus") Integer syncStatus,
            @Param("retryCount") Integer retryCount,
            @Param("failReason") String failReason
    );

    /**
     * 根据运单号查询
     */
    @Select("SELECT * FROM logistics_waybill_status WHERE waybill_no = #{waybillNo} AND deleted = 0 LIMIT 1")
    WaybillStatus selectByWaybillNo(@Param("waybillNo") String waybillNo);
}
