package com.kym.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSON;
import com.kym.entity.RechargePromotion;
import com.kym.mapper.RechargePromotionMapper;
import com.kym.service.RechargePromotionService;
import com.kym.service.mybatisplus.MyBaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author skyline
 * @since 2026-06-03
 */
@Slf4j
@Service
public class RechargePromotionServiceImpl extends MyBaseServiceImpl<RechargePromotionMapper, RechargePromotion> implements RechargePromotionService {

    @Override
    public RechargePromotion getByToken(String token) {
        var promotion = lambdaQuery()
                .eq(RechargePromotion::getToken, token)
                .eq(RechargePromotion::getStatus, RechargePromotion.STATUS_ENABLED)
                .one();
        if (promotion == null) {
            return null;
        }
        var now = LocalDateTime.now();
        if (now.isBefore(promotion.getStartTime()) || now.isAfter(promotion.getEndTime())) {
            return null;
        }
        return promotion;
    }

    @Override
    public boolean checkUserEligible(RechargePromotion promotion, Long userId) {
        if (promotion.getTargetMode() == RechargePromotion.TARGET_ALL) {
            return true;
        }
        if (promotion.getTargetUserIds() == null || promotion.getTargetUserIds().isBlank()) {
            return true;
        }
        try {
            List<Long> userIds = JSON.parseArray(promotion.getTargetUserIds(), Long.class);
            return userIds != null && userIds.contains(userId);
        } catch (Exception e) {
            log.error("解析目标用户ID列表失败: {}", promotion.getTargetUserIds(), e);
            return false;
        }
    }
}
