package com.fs.erp.mapper;

import com.fs.erp.domain.FsJstCodPush;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import java.util.List;

@Mapper
public interface FsJstCodPushMapper {

    /**
     * 根据ID查询记录
     */
    @Select("SELECT * FROM fs_jst_cod_push WHERE id = #{id}")
    FsJstCodPush selectById(@Param("id") Long id);

    /**
     * 根据订单ID查询记录
     */
    @Select("SELECT * FROM fs_jst_cod_push WHERE order_id = #{orderId}")
    List<FsJstCodPush> selectByOrderId(@Param("orderId") String orderId);

    /**
     * 根据售后ID查询记录
     */
    @Select("SELECT * FROM fs_jst_cod_push WHERE after_sale_id = #{afterSaleId}")
    List<FsJstCodPush> selectByAfterSaleId(@Param("afterSaleId") String afterSaleId);

    /**
     * 查询待处理的任务
     */
    @Select("SELECT * FROM fs_jst_cod_push WHERE task_status = 0 ORDER BY id ASC LIMIT #{limit}")
    List<FsJstCodPush> selectPendingTasks(@Param("limit") int limit);


    /**
     * 查询待处理的数据
     * @return List<FsJstCodPush>
     */
    @Select("SELECT * from fs_jst_cod_push where task_status = 0 OR (task_status = 2 AND retry_count < 3) ")
    List<FsJstCodPush> queryPenddingData();
    /**
     * 插入新记录
     */
    @Insert("INSERT INTO fs_jst_cod_push(order_id, after_sale_id, type, task_status, params) " +
            "VALUES(#{orderId}, #{afterSaleId}, #{type}, #{taskStatus}, #{params})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(FsJstCodPush record);

    /**
     * 更新任务状态
     */
    @Update("UPDATE fs_jst_cod_push SET task_status = #{taskStatus}, retry_count = #{retryCount}, " +
            "last_execute_time = NOW(), result = #{result}, error_message = #{errorMessage} " +
            "WHERE id = #{id}")
    int updateTaskStatus(FsJstCodPush record);

    /**
     * 根据ID更新记录
     */
    @Update("<script>" +
            "UPDATE fs_jst_cod_push " +
            "<set>" +
            "  <if test='orderId != null'>order_id = #{orderId},</if>" +
            "  <if test='afterSaleId != null'>after_sale_id = #{afterSaleId},</if>" +
            "  <if test='type != null'>type = #{type},</if>" +
            "  <if test='taskStatus != null'>task_status = #{taskStatus},</if>" +
            "  <if test='retryCount != null'>retry_count = #{retryCount},</if>" +
            "  <if test='lastExecuteTime != null'>last_execute_time = #{lastExecuteTime},</if>" +
            "  <if test='params != null'>params = #{params},</if>" +
            "  <if test='result != null'>result = #{result},</if>" +
            "  <if test='errorMessage != null'>error_message = #{errorMessage},</if>" +
            "</set>" +
            "WHERE id = #{id}" +
            "</script>")
    int updateById(FsJstCodPush record);
}
