package com.tuoheng.admin.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.entity.domain.ThMission;
import com.tuoheng.admin.enums.MarkTypeEnum;
import com.tuoheng.admin.enums.TaskStatusEnum;
import com.tuoheng.admin.enums.UpdateOrCreateEnum;
import com.tuoheng.admin.mapper.ThMissionMapper;
import com.tuoheng.admin.service.IThInspectionService;
import com.tuoheng.common.utils.JsonResult;
import com.tuoheng.common.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.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class ScheduledTask {

    @Autowired
    private ThMissionMapper missionMapper;

    @Autowired
    private IThInspectionService inspectionService;


    private final static SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


//    @Scheduled(fixedRate = 1000)
    @XxlJob("lcAirportTaskHandler")
    public void scheduledTask() {

        log.info("执行定时执行飞行任务：" + LocalDateTime.now());

        List<ThMission> thMissions = missionMapper.selectList(new LambdaQueryWrapper<ThMission>()
                .eq(ThMission::getMark, MarkTypeEnum.VALID.getCode())
                .eq(ThMission::getExecutionStartTime, dateformat.format(new Date()))
                //查询未执行任务
                .eq(ThMission::getExecutionStatus, 1)
                .eq(ThMission::getStatus, TaskStatusEnum.WAIT.getCode()));

        log.info("执行定时执行飞行任务，一秒钟一次");

        if(StringUtils.isNotEmpty(thMissions)){
            for (ThMission thMission : thMissions) {
                log.info("执行定时执行飞行任务:" + thMission.getId());
                JsonResult jsonResult = inspectionService.executeTask(String.valueOf(thMission.getId()), null);
                log.info("执行定时执行飞行任务result:" + jsonResult);

                if(jsonResult.getCode() != 0){
                    ThMission thMissionUpdate = new ThMission(UpdateOrCreateEnum.UPDATE.getCode());
                    thMissionUpdate.setId(thMission.getId());
                    log.error("执行定时执行机场起飞失败" + thMission.getId());
                    thMissionUpdate.setStatus(TaskStatusEnum.FAIL.getCode());
                    missionMapper.updateById(thMissionUpdate);
                }
            }
        }

        log.info("lcAirportTaskHandler执行结束");


    }
}
