package com.kym.admin.jobs;

import com.kym.service.DailyStatService;
import com.kym.service.MonthStatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 数据统计定时任务
 */
@Component
@Slf4j
public class StatJob {

    private final DailyStatService dailyStatService;
    private final MonthStatService monthStatService;

    public StatJob(DailyStatService dailyStatService, MonthStatService monthStatService) {
        this.dailyStatService = dailyStatService;
        this.monthStatService = monthStatService;
    }

    /**
     * 统计前一天的日数据
     * 每天凌晨03:00执行一次
     */
    @Async("AsyncExecutor")
    @Scheduled(cron = "0 0 3 * * ?")
    public void generateDailyStat() {
        log.info("执行站点日统计定时任务-开始");
        var yesterday = LocalDate.now().minusDays(1).format(DateTimeFormatter.ISO_LOCAL_DATE);
        dailyStatService.syncDailyStat(yesterday);
        log.info("执行站点日统计定时任务-结束");
    }

    /**
     * 月统计，每月5日下午15:00启动，统计上月数据
     */
    @Async("AsyncExecutor")
    @Scheduled(cron = "0 0 15 5 * ?")
    public void generateMonthStat() {
        log.info("执行站点月统计定时任务-开始");
        var statMonth = LocalDate.now().minusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM"));
        monthStatService.syncMonthlyStat(statMonth);
        log.info("执行站点月统计定时任务-结束");
    }
}
