package com.bizzan.bitrade.service;

import com.bizzan.bitrade.dao.ExperienceGiftRiskAlertDao;
import com.bizzan.bitrade.entity.ExperienceGiftRiskAlert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
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 ExperienceGiftRiskAlertService {

    @Autowired
    private ExperienceGiftRiskAlertDao alertDao;

    // ----------------------------------------------------------------
    // 分页查询
    // ----------------------------------------------------------------

    public Page<Map> pageQuery(Long memberId, String startTime, String endTime,
                               Integer status, int pageNo, int pageSize) {
        return alertDao.pageQuery(memberId, startTime, endTime, status, pageNo, pageSize);
    }

    // ----------------------------------------------------------------
    // 取消操作
    // ----------------------------------------------------------------

    @Transactional(rollbackFor = Exception.class)
    public boolean cancel(Long id, Long operatorId) {
        return alertDao.cancelById(id, operatorId, new Date()) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    public int cancelAll(Long operatorId) {
        return alertDao.cancelAll(operatorId, new Date());
    }

    // ----------------------------------------------------------------
    // 定时扫描：生成预警记录
    // ----------------------------------------------------------------

    /**
     * 检查最近 4 小时内满足以下任一条件的用户，生成预警记录：
     *   a) 4h 内领取体验金数量 ≥ 5
     *   b) 4h 内体验金平仓收益 ≥ 100U
     */
    @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> rows = alertDao.findRiskStats(startStr);

        int count = 0;
        for (Map 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 (alertDao.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);
            alertDao.save(alert);
            count++;
            log.info("体验金风控：新增预警 memberId={} receiptCount={} profitAmount={}", memberId, receiptCount, profitAmount);
        }
        return count;
    }
}
