package com.haha.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.haha.entity.InviteReward;
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 InviteRewardMapper extends BaseMapper<InviteReward> {

    // 根据邀请记录ID查询奖励记录
    @Select("SELECT * FROM t_invite_reward WHERE record_id = #{recordId} LIMIT 1")
    InviteReward selectByRecordId(@Param("recordId") Long recordId);

    // 根据邀请记录ID和奖励类型查询奖励记录（用于检查是否已发放过被邀请人奖励）
    @Select("SELECT * FROM t_invite_reward WHERE record_id = #{recordId} AND reward_type = #{rewardType} LIMIT 1")
    InviteReward selectByRecordIdAndRewardType(@Param("recordId") Long recordId, @Param("rewardType") Integer rewardType);

    // 更新奖励状态为已发放
    @Update("UPDATE t_invite_reward SET status = 1, user_coupon_id = #{userCouponId}, coupon_code = #{couponCode}, " +
            "distribute_time = NOW(), update_time = NOW() WHERE id = #{id}")
    int updateToDistributed(@Param("id") Long id, @Param("userCouponId") Long userCouponId, @Param("couponCode") String couponCode);

    // 更新奖励状态为发放失败
    @Update("UPDATE t_invite_reward SET status = 2, fail_reason = #{failReason}, retry_count = retry_count + 1, update_time = NOW() WHERE id = #{id}")
    int updateToFailed(@Param("id") Long id, @Param("failReason") String failReason);

    // 更新奖励状态为已补发
    @Update("UPDATE t_invite_reward SET status = 3, user_coupon_id = #{userCouponId}, coupon_code = #{couponCode}, " +
            "operator_id = #{operatorId}, operator_name = #{operatorName}, distribute_time = NOW(), update_time = NOW() WHERE id = #{id}")
    int updateToRetried(@Param("id") Long id, @Param("userCouponId") Long userCouponId,
                        @Param("couponCode") String couponCode, @Param("operatorId") Long operatorId,
                        @Param("operatorName") String operatorName);

    // 查询待重试的失败奖励记录
    @Select("SELECT * FROM t_invite_reward WHERE status = 2 AND retry_count < #{maxRetry} ORDER BY create_time ASC LIMIT #{limit}")
    List<InviteReward> selectFailedRewardsForRetry(@Param("maxRetry") Integer maxRetry, @Param("limit") Integer limit);

    // 统计某活动的奖励发放情况
    @Select("SELECT COUNT(*) as totalCount, " +
            "SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as distributedCount, " +
            "SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) as failedCount " +
            "FROM t_invite_reward WHERE activity_id = #{activityId}")
    Map<String, Object> selectRewardStatistics(@Param("activityId") Long activityId);
}
