package net.northking.cctp.executePlan.consumer;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import net.northking.cctp.executePlan.constants.PlanConstant;
import net.northking.cctp.executePlan.constants.RabbitConstant;
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.db.service.AtuPlanTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class TaskExecHeartbeatConsumer {

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

    @Autowired
    private AmqpAdmin amqpAdmin;

    @Autowired
    private AtuPlanTaskService planTaskService;

    @Autowired
    private AtuPlanSceneCaseTaskService planSceneCaseTaskService;

    @PostConstruct
    public void init(){
        // 初始化队列并绑定到交换机
        Queue queue = new Queue(RabbitConstant.TASK_EXEC_HEARTBEAT_QUEUE);
        amqpAdmin.declareQueue(queue);
    }

    /**
     * 计划任务心跳
     * @param message 对象消息
     */
    @RabbitListener(queues = RabbitConstant.TASK_EXEC_HEARTBEAT_QUEUE)
    public void receive(Message message){
        try {
            logger.info("计划任务心跳 ==> " + new String(message.getBody()));
            Map<String, String> taskMap = JSONUtil.toBean(new String(message.getBody()), Map.class);
            taskMap.forEach(this::handleTaskHeartbeat);
        }catch (Exception e){
            logger.error("任务生成失败", e);
        }
    }

    private void handleTaskHeartbeat(String taskId, String taskType){
        AtuPlanTask planTask = new AtuPlanTask();
        planTask.setId(taskId);
        planTask.setLastHeartbeatTime(new Date());
        if (PlanConstant.SCRIPT_TYPE_SCENE.equals(taskType)){
            // 场景任务
            AtuPlanSceneCaseTask sceneCaseTask = planSceneCaseTaskService.findByPrimaryKey(taskId);
            sceneCaseTask.setLastHeartbeatTime(new Date());
            planSceneCaseTaskService.updateByPrimaryKey(sceneCaseTask);
            // 更新场景节点对应的任务心跳
            planTask.setId(sceneCaseTask.getTaskId());
        }
        // 普通任务
        planTaskService.updateByPrimaryKey(planTask);
    }
}
