package com.jiayue.insu.inclientqn.job;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.jiayue.insu.inclientqn.constant.CommonStant;
import com.jiayue.insu.inclientqn.entity.Record;
import com.jiayue.insu.inclientqn.entity.Station;
import com.jiayue.insu.inclientqn.inenum.StatusEnum;
import com.jiayue.insu.inclientqn.service.RecordService;
import com.jiayue.insu.inclientqn.service.SHKJLNCorrforeService;
import com.jiayue.insu.inclientqn.service.StationService;
import com.jiayue.insu.inclientqn.service.client.SHKJCorrforeService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

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

/**
 * @description: 请求一体化 修正数据  飔合科技（辽宁）
 * @author: yuanhao
 * @createDate: 2022/6/17
 * @version: 1.0
 */
public class SHKJLNCorrforeDataJob implements Job {

    @Autowired
    private StationService stationService;
    @Autowired
    private RecordService recordService;
    @Autowired
    private SHKJCorrforeService shkjCorrforeService;

    @Override

    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //查询是否有今天成功记录 （为提高稳定性，该定时任务采取在规定时间段内 重复循环执行的定时策略，故：需要查询是否存在成功记录）
        Record successRecord;
        LocalDateTime localDateTime = LocalDateTimeUtil.beginOfDay(LocalDateTime.now());
        // 查询全部场站信息
        List<Station> stationList = stationService.findAll();
        // 如果场站大于1个，则循环请求飔合科技修正数据
        if (stationList != null && stationList.size() > 1) {
            for (Station station : stationList) {
                // 如果有执行记录，则不再执行
                successRecord = recordService.findTimeAndTypeAndStateAndStationCode(localDateTime, CommonStant.RECORD_TYPE_PULL_CORRECT, StatusEnum.SUCCESS.getCode(), station.getStationCode());
                if (successRecord != null) {
                    return;
                }
                // 飔合科技 下载修正后短期数据
                shkjCorrforeService.downLoadCorrforeData(station);
            }
            // 如果场站大于等于1个，则直接请求飔合科技修正数据
        } else if (stationList != null && stationList.size() == 1) {
            successRecord = recordService.findTimeAndTypeAndState(localDateTime, CommonStant.RECORD_TYPE_PULL_CORRECT, StatusEnum.SUCCESS.getCode());
            // 如果有执行记录，则不再执行
            if (successRecord != null) {
                return;
            }
            // 飔合科技 下载修正后短期数据
            shkjCorrforeService.downLoadCorrforeData(stationList.get(0));
        }

    }
}
