package com.red.circle.other.infra.database.cache.service.other.impl;

import com.red.circle.component.redis.service.RedisService;
import com.red.circle.other.infra.database.cache.key.CumulativeRechargeKey;
import com.red.circle.other.infra.database.cache.service.other.CumulativeRechargeCacheService;
import com.red.circle.tool.core.date.ZonedDateTimeAsiaRiyadhUtils;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 累计充值.
 *
 * @author pengshigang on 2022/3/29
 */
@Service
@RequiredArgsConstructor
public class CumulativeRechargeCacheServiceImpl implements CumulativeRechargeCacheService {

  private final RedisService redisService;

  @Override
  public void incrTodayRechargeScore(Long userId, Double rechargeScore) {

    String key = CumulativeRechargeKey.CUMULATIVE_RECHARGE_LOTTERY.getKey(userId);
    String time = ZonedDateTimeAsiaRiyadhUtils.nowDateToInt().toString();

    redisService.zsetIncrementScore(key, time, rechargeScore);
    redisService.expire(key, 2, TimeUnit.DAYS);
  }

  @Override
  public void decrTodayRechargeScore(Long userId, Double rechargeScore) {

    String key = CumulativeRechargeKey.CUMULATIVE_RECHARGE_LOTTERY.getKey(userId);
    String time = ZonedDateTimeAsiaRiyadhUtils.nowDateToInt().toString();

    redisService.zsetIncrementScore(key, time, -rechargeScore);
    redisService.expire(key, 2, TimeUnit.DAYS);
  }

  @Override
  public Double getTodayRechargeScore(Long userId) {
    String key = CumulativeRechargeKey.CUMULATIVE_RECHARGE_LOTTERY.getKey(userId);
    String time = ZonedDateTimeAsiaRiyadhUtils.nowDateToInt().toString();
    return redisService.zsetGetScore(key, time);
  }

  @Override
  public Boolean checkTodayAwarded(Long userId, Long level) {

    String key = userId + "_" + level + "_" + ZonedDateTimeAsiaRiyadhUtils.nowDateToInt();

    return StringUtils.isNotBlank(redisService
        .getString(CumulativeRechargeKey.CUMULATIVE_RECHARGE_LOTTERY.getKey(key)));
  }

  @Override
  public Boolean markTodayAwarded(Long userId, Long level) {

    String key = userId + "_" + level + "_" + ZonedDateTimeAsiaRiyadhUtils.nowDateToInt();

    return redisService.setIfAbsent(CumulativeRechargeKey.CUMULATIVE_RECHARGE_LOTTERY
        .getKey(key), 1, 2, TimeUnit.DAYS);
  }


}
