package com.njzscloud.dispose.finance.quartz;

import com.njzscloud.dispose.finance.service.BillService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * 生成对账单
 * @author ljw
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class GenerateBillQuartz {

    private final BillService billService;

    // @Scheduled(cron = "0 0/1 * * * ?")//每1分钟一次
    @Scheduled(cron = "0 0 1 1 * ?")// 每月1号凌晨1点执行
    public void syncAssetsDiscover() {
        generateBill();
    }

    private void generateBill() {
        log.info("开始执行生成对账单任务...");
        try {
            // 计算上个月的时间范围
            LocalDateTime now = LocalDateTime.now();
            // 上个月1号0点0分0秒
            LocalDateTime lastMonthStart = now.minusMonths(1).withDayOfMonth(1).with(LocalTime.MIN);
            // 上个月月末23点59分59秒
            LocalDateTime lastMonthEnd = now.minusMonths(1).withDayOfMonth(now.minusMonths(1).toLocalDate().lengthOfMonth())
                .with(LocalTime.MAX);

            log.info("统计时间范围：{} ~ {}", lastMonthStart, lastMonthEnd);

            // 生成对账单
            int billCount = billService.generateBill(lastMonthStart, lastMonthEnd);
            log.info("生成对账单任务执行完成，共生成 {} 条对账单", billCount);
        } catch (Exception e) {
            log.error("生成对账单任务执行失败", e);
        }
    }

}
