package com.ruoyi.cai.job;

import com.ruoyi.cai.service.DayIncomeStatisticsService;
import com.ruoyi.cai.service.RankService;
import com.ruoyi.cai.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;

@Component
@Slf4j
public class RankJob {

    @Autowired
    private RankService rankService;
    @Autowired
    private DayIncomeStatisticsService dayIncomeStatisticsService;

    @Scheduled(cron = "0 1 0 * * ? ")
    public void persistentDb() {
        LocalDate date = LocalDateTime.now().plusDays(-1).toLocalDate();
        try {
            rankService.saveDayRank(date,1);
        } catch (Exception e) {
            log.error("保存魅力 日榜失败", e);
        }
        try {
            rankService.saveDayRank(date,2);
        } catch (Exception e) {
            log.error("保存邀请 日榜失败", e);
        }
        DayOfWeek week = date.getDayOfWeek();
        if (week.getValue() == 1) { // 昨天是周一 做一下持久化
            try {
                rankService.saveWeekRank(date,1);
            } catch (Exception e) {
                log.error("保存魅力 周榜失败", e);
            }
            try {
                rankService.saveWeekRank(date,2);
            } catch (Exception e) {
                log.error("保存邀请 周榜失败", e);
            }
        }
        int month = date.getDayOfMonth();
        if (month == 1) { // 昨天是1号
            try {
                rankService.saveMonthRank(date,1);
            } catch (Exception e) {
                log.error("保存魅力 月榜失败", e);
            }
            try {

                rankService.saveMonthRank(date,2);
            } catch (Exception e) {
                log.error("保存邀请 月榜失败", e);
            }
        }
        try {
            dayIncomeStatisticsService.refreshByDate(date);
        }catch (Exception e){
            log.error("更新昨日收益统计失败!",e);
        }

        try {
            userService.refreshByAge();
        }catch (Exception e){
            log.error("刷新用户年龄失败!",e);
        }
    }

    @Autowired
    private UserService userService;

}
