package com.tuoheng.admin.task;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.admin.entity.Inspection;
import com.tuoheng.admin.entity.InspectionHistory;
import com.tuoheng.admin.enums.AirPortTaskStatusEnum;
import com.tuoheng.admin.enums.InspectionExecutionStatusEnum;
import com.tuoheng.admin.enums.InspectionStatusEnum;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.mapper.InspectionHistoryMapper;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.common.BaseEntity;
import com.tuoheng.common.core.utils.DateUtils;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import net.sf.saxon.functions.Current;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Component
public class InspectionTimeOutTask {

    @Resource
    private InspectionMapper inspectionMapper;

    @Resource
    private InspectionHistoryMapper inspectionHistoryMapper;

    @XxlJob("inspectionTimeOutTaskHandler")
    public void inspectionExecuteHandler() {
        log.info("=================================开始执行超时任务定时器任务调度=================================");
        Date startTime;
        String taskBeginTime = null;
        try {
            SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
            startTime = new Date(System.currentTimeMillis());
            taskBeginTime = DateUtils.addDateTimeToStr(startTime, 0, -1, 0, 0);
        } catch (Exception e) {
            log.error("获取开始时间异常：{}", e);
        }

        //以现在时间为节点 查询一小时之前的所有机场里的状态为 准备中，飞行中的已开始执行的任务
        List<Inspection> newInspections = inspectionMapper.selectList(Wrappers.<Inspection>lambdaQuery()
                .in(Inspection::getStatus, InspectionStatusEnum.PREPARING.getCode(), InspectionStatusEnum.IN_FLIGHT.getCode())
                .eq(Inspection::getInspectionType, AirPortTaskStatusEnum.FLIGHT.getCode())
                .eq(Inspection::getExecutionStatus, InspectionExecutionStatusEnum.EXECUTED.getCode())
                .le(Inspection::getExecutionStartTime, taskBeginTime)
                .eq(BaseEntity::getMark, MarkEnum.VALID.getCode()));
        log.info("执行定时执行飞行任务：机场任务数" + newInspections.size());

        for (Inspection inspection : newInspections) {
            inspection.setStatus(InspectionStatusEnum.FLIGHT_FAILED.getCode());
            inspectionMapper.updateById(inspection);
            log.info("修改结果: 任务状态为" + inspection.getStatus());
            this.insertInspectionHistory(inspection);
        }
        log.info("=================================结束执行超时任务定时器任务调度=================================");
    }

    /**
     * 保存到历史记录表
     * @param inspection
     */
    private void insertInspectionHistory(Inspection inspection) {
        InspectionHistory inspectionHistory = new InspectionHistory();
        inspectionHistory.setTenantId(inspection.getTenantId());
        inspectionHistory.setInspectionId(inspection.getId());
        inspectionHistory.setHistoryName("任务执行超过一小时  默认失败");
        inspectionHistory.setCreateUser(inspection.getCreateUser());
        inspectionHistory.setCreateTime(DateUtils.now());
        Integer count = inspectionHistoryMapper.insert(inspectionHistory);
        if (count <= 0) {
            log.info("超时任务保存到历史记录表中失败，inspectionId:{}", inspection.getId());
        }
    }

}
