package com.zcxk.charge.xxl.jobs;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zcxk.charge.core.entity.DayReportEntity;
import com.zcxk.charge.xxl.service.MonitorReportService;
import com.zcxk.charge.xxl.service.impl.DataAlarmHourJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @create 2020-05-18 14:07
 */
@Slf4j
@Component
public  class MonitorDataReportByDayJob implements Serializable {

    @Resource
    private DataAlarmHourJobService dataAlarmHourJobService;

    @Autowired
    private MonitorReportService monitorReportService;

    @XxlJob("monitorDataReportByDayJob")
    public ReturnT<String> execute(String string) {
        try {
            log.info("日报报任务开始执行");
            getMonitorDataReportByHour();
            dataAlarmHourJobService.execute();
            log.info("日报任务执行结束");
        } catch (Exception e) {
            e.printStackTrace();
            log.info("日报任务执行异常，{}", e.getMessage());
        }
        return ReturnT.SUCCESS;
    }

    public void getMonitorDataReportByHour(){
        // 取前一个小时的时间
        LocalDateTime dateTime = LocalDateTime.now().plusHours(-1);
        List<DayReportEntity> hourData     = monitorReportService.getMonitorDataGroupByHour(dateTime,null);
        // 取前一个小时的时间(取18点)
        List<DayReportEntity> lastHourData = monitorReportService.getMonitorDataGroupByHour(dateTime.plusHours(-1),null);
        Map<String,DayReportEntity> lastHourDataMap = lastHourData.stream().collect(Collectors.toMap(DayReportEntity::getMapkey, a -> a,(k1, k2)->k1));
        // 保存日报表数据
        monitorReportService.saveReportDataByHour(hourData, lastHourDataMap);
        if (lastHourDataMap.values().size() == 0){
            return;
        }
        // 补充数据
        monitorReportService.replenishHistoryData(dateTime, lastHourDataMap);
    }
}