package com.datacenter.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.datacenter.entity.ExperienceGiftRiskAlert;
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.util.Date;
import java.util.List;
import java.util.Map;

@Mapper
public interface ExperienceGiftRiskAlertMapper extends BaseMapper<ExperienceGiftRiskAlert> {

    /**
     * 查询指定时间窗口内满足预警条件的用户统计数据：
     *   a) 领取体验金次数 >= 5
     *   b) 体验金平仓收益 >= 100U
     */
    @Select("SELECT r.member_id AS memberId," +
            " COUNT(DISTINCT CASE WHEN r.created_at >= #{startStr} THEN r.id END) AS receiptCount," +
            " COALESCE(SUM(CASE WHEN r.closed_at >= #{startStr} AND r.status = 2 AND r.pnl > 0 THEN r.pnl ELSE 0 END), 0) AS profitAmount" +
            " FROM experience_gift_record r" +
            " WHERE r.created_at >= #{startStr} OR (r.closed_at >= #{startStr} AND r.status = 2)" +
            " GROUP BY r.member_id" +
            " HAVING COUNT(DISTINCT CASE WHEN r.created_at >= #{startStr} THEN r.id END) >= 5" +
            "     OR SUM(CASE WHEN r.closed_at >= #{startStr} AND r.status = 2 AND r.pnl > 0 THEN r.pnl ELSE 0 END) >= 100")
    List<Map<String, Object>> findRiskStats(@Param("startStr") String startStr);

    /** 检查某用户在指定时间之后是否已有指定状态的告警（防重复生成） */
    @Select("SELECT COUNT(1) > 0 FROM experience_gift_risk_alert" +
            " WHERE member_id = #{memberId} AND created_at >= #{createdAt} AND status = #{status}")
    boolean existsByMemberIdAndCreatedAtAfterAndStatus(
            @Param("memberId") Long memberId,
            @Param("createdAt") Date createdAt,
            @Param("status") Integer status);

    /** 取消单条告警 */
    @Update("UPDATE experience_gift_risk_alert SET status = 1, handled_at = #{now}, handled_by = #{operatorId}" +
            " WHERE id = #{id} AND status = 0")
    int cancelById(@Param("id") Long id, @Param("operatorId") Long operatorId, @Param("now") Date now);

    /** 一键取消所有待处理告警 */
    @Update("UPDATE experience_gift_risk_alert SET status = 1, handled_at = #{now}, handled_by = #{operatorId}" +
            " WHERE status = 0")
    int cancelAll(@Param("operatorId") Long operatorId, @Param("now") Date now);
}
