package net.northking.cctp.executePlan.job;

import cn.hutool.core.collection.CollUtil;
import net.northking.cctp.executePlan.api.service.AtuPlanSceneCaseTaskApiService;
import net.northking.cctp.executePlan.api.service.AtuPlanTaskApiService;
import net.northking.cctp.executePlan.constants.PlanConstant;
import net.northking.cctp.executePlan.db.entity.AtuPlanSceneCaseTask;
import net.northking.cctp.executePlan.db.entity.AtuPlanTask;
import net.northking.cctp.executePlan.db.service.AtuPlanSceneCaseTaskService;
import net.northking.cctp.executePlan.dto.planTask.AtuPlanTaskExtendDto;
import net.northking.cctp.executePlan.dto.planTask.AtuTaskExecResultDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

@EnableScheduling
@Configuration
public class TaskExecTimeoutJob {

    private final static Logger logger = LoggerFactory.getLogger(TaskExecTimeoutJob.class);

    @Autowired
    private AtuPlanTaskApiService planTaskApiService;

    @Autowired
    private AtuPlanSceneCaseTaskService sceneCaseTaskService;

    @Autowired
    private AtuPlanSceneCaseTaskApiService sceneCaseTaskApiService;

    /**
     * 超时时间，默认3分钟，单位秒
     */
    public static final int TIMEOUT = 3 * 60;

    public static final String ERROR_MSG = "引擎执行任务超时";

    @Scheduled(initialDelay = 10 * 1000,fixedDelay = 60 * 1000)
    private void handleTaskExecTimeout(){
        // 查询正在执行中且心跳时间超过n分钟的任务
        List<AtuPlanTask> taskList = planTaskApiService.queryExecTimeoutTask(TIMEOUT);
        if (CollUtil.isNotEmpty(taskList)){
            logger.debug("超时任务数量：{}", taskList.size());
            for (AtuPlanTask planTask : taskList) {
                planTaskApiService.taskExecFailUpdate(planTask, PlanConstant.TASK_TIMEOUT_STATUS, ERROR_MSG);
            }
        }

        List<AtuPlanSceneCaseTask> sceneCaseTaskList = sceneCaseTaskService.queryExecTimeoutTask(TIMEOUT);
        if (CollUtil.isNotEmpty(sceneCaseTaskList)){
            logger.debug("超时场景节点任务数量：{}", sceneCaseTaskList.size());
            AtuTaskExecResultDto taskExecResult = new AtuTaskExecResultDto();
            taskExecResult.setCaseType(PlanConstant.SCRIPT_TYPE_SCENE);
            taskExecResult.setStatus(PlanConstant.TASK_TIMEOUT_STATUS);
            taskExecResult.setMessage(ERROR_MSG);
            taskExecResult.setCurrentTime(System.currentTimeMillis());

            for (AtuPlanSceneCaseTask sceneCaseTask : sceneCaseTaskList) {
                AtuPlanTaskExtendDto taskExtendDto = planTaskApiService.queryTaskExtendById(sceneCaseTask.getTaskId());
                if (taskExtendDto == null){
                    logger.error("任务[{}]信息不存在", sceneCaseTask.getTaskId());
                    logger.error("删除任务[{}]的节点任务信息", sceneCaseTask.getTaskId());
                    AtuPlanSceneCaseTask delParams = new AtuPlanSceneCaseTask();
                    delParams.setTaskId(sceneCaseTask.getTaskId());
                    sceneCaseTaskService.deleteByExample(delParams);
                    continue;
                }
                taskExecResult.setPlanId(taskExtendDto.getPlanId());
                taskExecResult.setBatchId(taskExtendDto.getBatchId());
                taskExecResult.setCaseId(taskExtendDto.getCaseId());
                taskExecResult.setTaskId(sceneCaseTask.getId());
                AtuPlanTask planTask = new AtuPlanTask();
                BeanUtils.copyProperties(taskExtendDto, planTask);
                // 场景节点执行失败，执行下一节点
                sceneCaseTaskApiService.queryNextNodeInfo(taskExecResult, sceneCaseTask, planTask);
            }
        }
    }
}
