package com.red.circle.other.app.command.activity.query;

import com.red.circle.other.infra.database.cache.service.other.AgentActivityCacheService;
import com.red.circle.tool.core.date.ZonedDateTimeAsiaRiyadhUtils;
import com.red.circle.tool.core.date.ZonedId;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.ZonedDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.HashMap;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 代理活动 - 倒计时.
 * </p>
 *
 * @author pengshigang
 * @since 2023-05-29
 */
@Component
@RequiredArgsConstructor
public class AgentActivityCountdownQueryExe {

  private final AgentActivityCacheService agentActivityCacheService;

  public Map<String, Long> execute() {

    if (agentActivityCacheService.getWeekCountDown() <= 0) {
      agentActivityCacheService.cacheWeekCountDown(Duration
          .between(ZonedDateTimeAsiaRiyadhUtils.now(),
              nowAsiaRiyadhWeekSunday())
          .toMillis());
    }

    if (agentActivityCacheService.getMonthCountDown() <= 0) {
      agentActivityCacheService.cacheMonthCountDown(Duration
          .between(ZonedDateTimeAsiaRiyadhUtils.now(),
              getLastDayOfMonth())
          .toMillis());
    }

    Map<String, Long> times = new HashMap<>();
    times.put("WEEK", agentActivityCacheService.getWeekCountDown());
    times.put("MONTH", agentActivityCacheService.getMonthCountDown());
    return times;
  }

  /**
   * 获取本周日 ，沙特阿拉伯-Riyadh 时区 .
   */
  public static ZonedDateTime nowAsiaRiyadhWeekSunday() {

    return nowAsiaRiyadh().with(DayOfWeek.SUNDAY)
        .withHour(23)
        .withMinute(59)
        .withSecond(59)
        .withNano(999999999);
  }

  /**
   * 获取当前月最后一天.
   */
  public static ZonedDateTime getLastDayOfMonth() {

    return nowAsiaRiyadh().with(TemporalAdjusters.lastDayOfMonth())
        .withHour(23)
        .withMinute(59)
        .withSecond(59)
        .withNano(999999999);
  }


  /**
   * 当前时间，沙特阿拉伯-Riyadh 时区.
   *
   * @return ignore
   */
  public static ZonedDateTime nowAsiaRiyadh() {
    return ZonedDateTime.now(ZonedId.ASIA_RIYADH.getZonedId());
  }
}
