package net.northking.cctp.se.plan;


import cn.hutool.json.JSONUtil;
import net.northking.cctp.se.lifecycle.constant.MQConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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

@Component
public class AtuTaskExecHeartbeatSchedule {

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

    @Autowired
    private RabbitAdmin rabbitAdmin;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 记录正在执行中的任务，key:任务id，value:任务类型
     */
    public static ConcurrentHashMap<String, String> execTaskMap = new ConcurrentHashMap<>();

    @PostConstruct
    public void init(){
        Queue queue = new Queue(MQConstant.TASK_EXEC_HEARTBEAT_QUEUE);
        rabbitAdmin.declareQueue(queue);
    }

    /**
     * 发送任务执行心跳
     */
    @Scheduled(initialDelay = 10 * 1000,fixedDelay = 60 * 1000)
    public void sendTaskExecHeartbeat(){
        if (execTaskMap.size() <= 0){
            logger.debug("无正在执行的任务...");
            return;
        }
        try {
            rabbitTemplate.convertAndSend(MQConstant.TASK_EXEC_HEARTBEAT_QUEUE, JSONUtil.toJsonStr(execTaskMap));
        } catch (Exception e) {
            logger.error("发送任务执行心跳异常");
        }
    }
}
