package com.haha.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.haha.entity.InviteActivity;
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;
import java.util.Map;

@Mapper
public interface InviteActivityMapper extends BaseMapper<InviteActivity> {

    // 查询所有未删除的邀请活动
    @Select("SELECT * FROM t_invite_activity WHERE deleted = 0 ORDER BY create_time DESC")
    List<InviteActivity> selectAll();

    // 查询进行中的邀请活动
    @Select("SELECT * FROM t_invite_activity WHERE status = 2 AND deleted = 0 AND start_time <= #{now} AND end_time >= #{now}")
    List<InviteActivity> selectOngoing(@Param("now") LocalDateTime now);

    // 更新活动状态
    @Update("UPDATE t_invite_activity SET status = #{status}, update_time = NOW() WHERE id = #{id}")
    int updateStatus(@Param("id") Long id, @Param("status") Integer status);

    // 更新统计数据（总邀请数+1）
    @Update("UPDATE t_invite_activity SET total_invite_count = total_invite_count + 1, update_time = NOW() WHERE id = #{id}")
    int incrementTotalInviteCount(@Param("id") Long id);

    // 更新统计数据（有效邀请数+1）
    @Update("UPDATE t_invite_activity SET valid_invite_count = valid_invite_count + 1, update_time = NOW() WHERE id = #{id}")
    int incrementValidInviteCount(@Param("id") Long id);

    // 更新统计数据（奖励发放数+1）
    @Update("UPDATE t_invite_activity SET reward_count = reward_count + 1, update_time = NOW() WHERE id = #{id}")
    int incrementRewardCount(@Param("id") Long id);

    // 统计查询：按活动ID统计各项指标
    @Select("SELECT " +
            "COUNT(*) as totalInvite, " +
            "SUM(CASE WHEN status >= 1 THEN 1 ELSE 0 END) as validInvite, " +
            "SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) as rewardedCount, " +
            "SUM(CASE WHEN invite_time >= #{startDate} AND invite_time <= #{endDate} THEN 1 ELSE 0 END) as todayInvite " +
            "FROM t_invite_record WHERE activity_id = #{activityId}")
    Map<String, Object> selectStatisticsByActivityId(@Param("activityId") Long activityId,
                                                      @Param("startDate") LocalDateTime startDate,
                                                      @Param("endDate") LocalDateTime endDate);
}
