package com.datacenter.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.datacenter.entity.ExperienceGiftRiskAlert;
import com.datacenter.mapper.ExperienceGiftRiskAlertMapper;
import com.datacenter.service.ExperienceGiftRiskAlertService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ExperienceGiftRiskAlertServiceImpl
        extends ServiceImpl<ExperienceGiftRiskAlertMapper, ExperienceGiftRiskAlert>
        implements ExperienceGiftRiskAlertService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int checkAndGenerateAlerts() {
        Date now = new Date();
        Date fourHoursAgo = new Date(now.getTime() - 4L * 60 * 60 * 1000);
        String startStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(fourHoursAgo);

        List<Map<String, Object>> rows = baseMapper.findRiskStats(startStr);

        int count = 0;
        for (Map<String, Object> row : rows) {
            Long memberId = ((Number) row.get("memberId")).longValue();
            int receiptCount = ((Number) row.get("receiptCount")).intValue();
            BigDecimal profitAmount = new BigDecimal(row.get("profitAmount").toString());

            // 同一用户在同一 4h 窗口内已有告警则跳过
            if (baseMapper.existsByMemberIdAndCreatedAtAfterAndStatus(memberId, fourHoursAgo, 0)) {
                log.debug("体验金风控：用户 {} 本周期已有告警，跳过", memberId);
                continue;
            }

            ExperienceGiftRiskAlert alert = new ExperienceGiftRiskAlert();
            alert.setMemberId(memberId);
            alert.setReceiptCount(receiptCount);
            alert.setProfitAmount(profitAmount);
            alert.setStatus(0);
            alert.setCreatedAt(now);
            save(alert);
            count++;
            log.info("体验金风控：新增预警 memberId={} receiptCount={} profitAmount={}", memberId, receiptCount, profitAmount);
        }
        return count;
    }
}
