package com.red.circle.console.app.scheduler;

import com.red.circle.component.redis.annotation.TaskCacheLock;
import com.red.circle.console.app.service.app.datav.CountryDashboardDailyMetricService;
import com.red.circle.console.app.service.app.datav.CountryDashboardGameMetricService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 国家数据大屏日预聚合任务.
 */
@Slf4j
@Component
@ConditionalOnProperty(name = "red-circle.country-dashboard.refresh-enabled", havingValue = "true")
@RequiredArgsConstructor
public class CountryDashboardDailyMetricTask {

  private final CountryDashboardDailyMetricService countryDashboardDailyMetricService;
  private final CountryDashboardGameMetricService countryDashboardGameMetricService;

  @Value("${red-circle.country-dashboard.refresh-today-days:1}")
  private int refreshTodayDays;

  @Value("${red-circle.country-dashboard.refresh-recent-days:8}")
  private int refreshRecentDays;

  @Scheduled(cron = "${red-circle.country-dashboard.refresh-today-cron:0 */10 * * * ?}",
      zone = "Asia/Shanghai")
  @TaskCacheLock(key = "COUNTRY_DASHBOARD_DAILY_METRIC_REFRESH_TODAY", expireSecond = 60 * 8)
  public void refreshToday() {
    long start = System.currentTimeMillis();
    countryDashboardDailyMetricService.refreshRecentDays(refreshTodayDays);
    countryDashboardGameMetricService.refreshRecentDays(refreshTodayDays);
    log.info("country dashboard refresh today task finished, days={}, costMs={}",
        refreshTodayDays, System.currentTimeMillis() - start);
  }

  @Scheduled(cron = "${red-circle.country-dashboard.refresh-recent-cron:0 20 0 * * ?}",
      zone = "Asia/Shanghai")
  @TaskCacheLock(key = "COUNTRY_DASHBOARD_DAILY_METRIC_REFRESH_RECENT", expireSecond = 60 * 60)
  public void refreshRecent() {
    long start = System.currentTimeMillis();
    countryDashboardDailyMetricService.refreshRecentDays(refreshRecentDays);
    countryDashboardGameMetricService.refreshRecentDays(refreshRecentDays);
    log.info("country dashboard refresh recent task finished, days={}, costMs={}",
        refreshRecentDays, System.currentTimeMillis() - start);
  }
}
