package com.haha.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.haha.entity.InviteRecord;
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.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Mapper
public interface InviteRecordMapper extends BaseMapper<InviteRecord> {

    // 根据被邀请人ID查询是否已被邀请过
    @Select("SELECT * FROM t_invite_record WHERE invitee_user_id = #{inviteeUserId} AND deleted = 0 LIMIT 1")
    InviteRecord selectByInviteeUserId(@Param("inviteeUserId") Long inviteeUserId);

    // 根据邀请码查询记录
    @Select("SELECT * FROM t_invite_record WHERE invite_code = #{inviteCode} AND deleted = 0 LIMIT 1")
    InviteRecord selectByInviteCode(@Param("inviteCode") String inviteCode);

    // 更新记录状态为已激活
    @Update("UPDATE t_invite_record SET status = 1, activate_time = NOW(), update_time = NOW() WHERE id = #{id}")
    int updateToActivated(@Param("id") Long id);

    // 更新记录状态为已奖励
    @Update("UPDATE t_invite_record SET status = 2, update_time = NOW() WHERE id = #{id}")
    int updateToRewarded(@Param("id") Long id);

    // 统计某用户今日邀请数量
    @Select("SELECT COUNT(*) FROM t_invite_record WHERE inviter_user_id = #{inviterUserId} AND activity_id = #{activityId} " +
            "AND DATE(invite_time) = #{today} AND deleted = 0")
    int countTodayInvites(@Param("inviterUserId") Long inviterUserId,
                          @Param("activityId") Long activityId,
                          @Param("today") LocalDate today);

    // 统计某用户在活动中总邀请数量
    @Select("SELECT COUNT(*) FROM t_invite_record WHERE inviter_user_id = #{inviterUserId} AND activity_id = #{activityId} AND deleted = 0")
    int countTotalInvitesByUser(@Param("inviterUserId") Long inviterUserId, @Param("activityId") Long activityId);

    // 查询某用户的所有邀请记录（分页）
    @Select("SELECT * FROM t_invite_record WHERE inviter_user_id = #{inviterUserId} AND activity_id = #{activityId} AND deleted = 0 " +
            "ORDER BY invite_time DESC LIMIT #{offset}, #{pageSize}")
    List<InviteRecord> selectByInviterUserId(@Param("inviterUserId") Long inviterUserId,
                                              @Param("activityId") Long activityId,
                                              @Param("offset") Integer offset,
                                              @Param("pageSize") Integer pageSize);

    // 查询Top邀请达人
    @Select("SELECT inviter_user_id, COUNT(*) as invite_count FROM t_invite_record " +
            "WHERE activity_id = #{activityId} AND status >= 1 AND deleted = 0 " +
            "GROUP BY inviter_user_id ORDER BY invite_count DESC LIMIT #{limit}")
    List<Map<String, Object>> selectTopInviters(@Param("activityId") Long activityId, @Param("limit") Integer limit);
}
