package com.gxwebsoft.glt.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gxwebsoft.glt.entity.GltUserTicketRelease;
import com.gxwebsoft.glt.param.GltUserTicketReleaseParam;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Param;

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

/**
 * 水票释放Mapper
 *
 * @author 科技小王子
 * @since 2026-02-03 18:55:55
 */
public interface GltUserTicketReleaseMapper extends BaseMapper<GltUserTicketRelease> {

    /**
     * 分页查询
     *
     * @param page  分页对象
     * @param param 查询参数
     * @return List<GltUserTicketRelease>
     */
    List<GltUserTicketRelease> selectPageRel(@Param("page") IPage<GltUserTicketRelease> page,
                             @Param("param") GltUserTicketReleaseParam param);

    /**
     * 查询全部
     *
     * @param param 查询参数
     * @return List<User>
     */
    List<GltUserTicketRelease> selectListRel(@Param("param") GltUserTicketReleaseParam param);

    /**
     * 查询当月待释放水票数据
     * @param limitNum 查询数量
     * @return List<User>
     */
    List<GltUserTicketRelease> getThisMonthReleaseList(@Param("limitNum") Integer limitNum);

    /**
     * 查询待释放且到期的记录（加行锁，防止多实例重复处理）
     *
     * status: 0=待释放, 1=已释放, 2=释放失败(数据异常)
     */
    @Select("""
        SELECT *
        FROM glt_user_ticket_release
        WHERE status = 0
          AND deleted = 0
          AND release_time <= #{now}
        ORDER BY release_time ASC, id ASC
        LIMIT #{limit}
        FOR UPDATE
        """)
    List<GltUserTicketRelease> selectDueForUpdate(@Param("now") LocalDateTime now,
                                                  @Param("limit") int limit);

    /**
     * 更新释放记录状态
     */
    @Update("""
        UPDATE glt_user_ticket_release
        SET status = #{status},
            update_time = #{now}
        WHERE id = #{id}
          AND deleted = 0
          AND status = 0
        """)
    int updateStatus(@Param("id") Long id,
                     @Param("status") Integer status,
                     @Param("now") LocalDateTime now);

}
