package com.jiayue.insu.inclientqn.job;

import cn.hutool.core.date.DateUtil;
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.QNHLEnum;
import com.jiayue.insu.inclientqn.inenum.StatusEnum;
import com.jiayue.insu.inclientqn.service.RecordService;
import com.jiayue.insu.inclientqn.service.StationService;
import com.jiayue.insu.inclientqn.service.client.CorrforeService;
import com.jiayue.insu.inclientqn.util.DateTimeUtils;
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 RepairPlanJob implements Job {

    @Autowired
    private CorrforeService corrforeService;
    @Autowired
    private RecordService recordService;
    @Autowired
    private StationService stationService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        long time = DateTimeUtils.get15min(DateUtil.date().getTime());
        LocalDateTime localDateTime = LocalDateTimeUtil.beginOfDay(LocalDateTime.now());
        Record record;
        // 查询全部场站信息
        List<Station> stationList = stationService.findAll();
        // 如果场站大于1个，则循环下载检修计划数据
        if (stationList != null && stationList.size() > 1) {
            for (Station station : stationList) {
                // 如果有执行记录，则不再执行
                record = recordService.findTimeAndTypeAndContentAndStateAndStationCode(localDateTime, CommonStant.RECORD_TYPE_CORRECT_DATA, QNHLEnum.DATA_REPAPLAN_TYPE.getCode(), StatusEnum.SUCCESS.getSign(),station.getStationCode());
                if (record != null) {
                    return;
                }
                // 下载并生成检修计划数据
                corrforeService.downLoadRepairPlan(time,station);
            }
            // 如果场站等于1个，则直接下载检修计划数据
        } else if (stationList != null && stationList.size() == 1) {
            record = recordService.findTimeAndTypeAndContentAndState(localDateTime, CommonStant.RECORD_TYPE_CORRECT_DATA, QNHLEnum.DATA_REPAPLAN_TYPE.getCode(), StatusEnum.SUCCESS.getSign());
            // 如果有执行记录，则不再执行
            if (record != null) {
                return;
            }
            // 下载并生成检修计划数据
            corrforeService.downLoadRepairPlan(time,stationList.get(0));
        }

    }
}
