package com.jiayue.insu.incloud.job.data.pull;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.jiayue.insu.incloud.constants.CommonStant;
import com.jiayue.insu.incloud.constants.enums.StatusEnum;
import com.jiayue.insu.incloud.entity.Record;
import com.jiayue.insu.incloud.entity.Station;
import com.jiayue.insu.incloud.pulldata.PullCorrectDataForLx;
import com.jiayue.insu.incloud.service.RecordService;
import com.jiayue.insu.incloud.service.StationService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

/**
 * 飔合科技 拉取修正数据定时任务
 *
 * @author yh
 * @version 1.0
 * @since 2022/5/22 11:29
 */
@Slf4j
public class LxPullCorrectDataJob implements Job {

    @Autowired
    private PullCorrectDataForLx pullCorrectDataForLx;
    @Autowired
    private StationService stationService;
    @Autowired
    private RecordService recordService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String code = jobExecutionContext.getTrigger().getJobKey().getName();
        // 校验并获取场站信息
        Station station = stationService.checkAndFindStation(code,CommonStant.RECORD_TYPE_PULL_CORRECT);
        //没有成功记录进行业务
        if (station != null) {
            LocalTime noon = LocalTime.NOON;
            LocalDateTime noonToday = LocalDateTime.of(LocalDate.now(),noon);
            // 判断当前时间是否在中午12点之前  =》 12点之前请求一次修正短期，12点之后请求一次修正短期 一天共两次，根据时间来判断
            if (LocalDateTime.now().isBefore(noonToday)){
                //查询是否有今天成功记录 （为提高稳定性，该定时任务采取在规定时间段内 重复循环执行的定时策略，故：需要查询是否存在成功记录）
                Record successRecord = recordService.findTimeAndTypeAndStateAndStation(
                        LocalDateTimeUtil.beginOfDay(LocalDateTime.now()),
                        CommonStant.RECORD_TYPE_PULL_CORRECT,
                        StatusEnum.SUCCESS.getSign(), station.getStationCode());
                // 没有成功记录进行请求业务
                if (successRecord == null){
                    pullCorrectDataForLx.pullDQData(station);
                }
            }else {
                // 12点之后 请求记录应该是2条，小于2条记录继续请求修正数据
                List<Record> recordList = recordService.findTypeAndStateAndStationAndCreatTime(
                        CommonStant.RECORD_TYPE_PULL_CORRECT,
                        StatusEnum.SUCCESS.getSign(), station.getStationCode(),LocalDateTimeUtil.beginOfDay(LocalDateTime.now()));

                if (recordList.size() <= 1) {
                    pullCorrectDataForLx.pullDQData(station);
                }
            }
        }else{
            log.error("========== 一体化定时任务异常:  场站信息为空  {}==========",code);
        }
    }
}
