package com.bcxin.autodownloadupload.scheduling;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.bcxin.autodownloadupload.configs.PullConfig;
import com.bcxin.autodownloadupload.dtos.ChangeLogsRequestDto;
import com.bcxin.autodownloadupload.entity.PullRecord;
import com.bcxin.autodownloadupload.service.PullDataService;
import com.bcxin.autodownloadupload.service.PullRecordService;
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.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * description: 定时拉取数据调度任务
 * author: linchunpeng
 * date:  2023-04-17 16:02
 */
@Slf4j
@Component
public class PullDataTask {

    @Autowired
    private PullDataService pullDataService;
    @Autowired
    private PullRecordService pullRecordService;

    @Autowired
    private PullConfig pullConfig;

    /**
     * description: 定时拉取数据调度任务
     * author: linchunpeng
     * date:  2023-04-17 16:03
     */
    @Scheduled(cron = "${pull-config.scheduled.cron}")
    public void pullDataTask() {
        log.info("===================================定时拉取数据调度任务===================================");
        Date now = new Date();
        List<String> regionCodes = new ArrayList<>();
        for (String regionCode : pullConfig.getChangeLogsRequestDto().getRegionCodes().split(",")) {
            //判断是否前一天已经自动摆渡完成
            PullRecord lastRecord = pullRecordService.getLastRecord(regionCode);
            Date todayZero = DateUtil.beginOfDay(now);
            long fiveHour = 5 * 60 * 60 * 1000;
            if (lastRecord == null || todayZero.getTime() - lastRecord.getEndTime().getTime() > fiveHour) {
                //5小时以外，需要生成每天包
                regionCodes.add(regionCode);
            }
        }
        if (CollectionUtil.isNotEmpty(regionCodes)) {
            ChangeLogsRequestDto changeLogsRequestDto = pullConfig.getChangeLogsRequestDto();
            changeLogsRequestDto.setRegionCodes(String.join(",", regionCodes));
            pullDataService.pullData(changeLogsRequestDto, 0);
        }
        log.info("===================================任务结束===================================");
    }

}
