package com.tuoheng.admin.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.entity.Inspection;
import com.tuoheng.admin.enums.InspectionStatusEnum;
import com.tuoheng.admin.enums.InspectionTypeEnum;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.admin.service.third.airport.AirportService;
import com.tuoheng.common.core.utils.StringUtils;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * 定时扫描，然后飞行
 */
@Component
@Slf4j
public class AirportTask {

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private AirportService airportService;

    @XxlJob("telecomumaleAirportTaskHandler")
    public void airportTaskHandler() {
        // 查询当前时间正负1分钟的时间跨度，xxljob执行频率为1分钟1次
        long start = new Date().getTime() - 1 * 60000L;
        long end = new Date().getTime() + 1 * 60000L;
        Date startTime = new Date(start);
        Date endTime = new Date(end);

        log.info("执行定时执行飞行任务：" + LocalDateTime.now());
        List<Inspection> inspectionList = inspectionMapper.selectList(new LambdaQueryWrapper<Inspection>()
                .eq(Inspection::getMark, MarkEnum.VALID.getCode())
                .between(Inspection::getInspectionTime, startTime, endTime)
                //查询巡检方式为机场的任务
                .eq(Inspection::getInspectionType, InspectionTypeEnum.AIRPORT.getCode())
                //查询未执行任务
                .eq(Inspection::getExecutionStatus, 1)
                //任务待飞行
                .eq(Inspection::getStatus, InspectionStatusEnum.WAIT_FLIGHT.getCode()));
        log.info("执行定时执行飞行任务：机场任务数" + inspectionList.size());
        if (StringUtils.isEmpty(inspectionList)) {
            return;
        }
        for (Inspection inspection : inspectionList) {
            log.info("执行定时执行飞行任务开始: inspectionId:{}", inspection.getId());
            airportService.executeTask("", inspection);
            log.info("执行定时执行飞行任务结束: inspectionId:{}");
        }
    }

}
