package cn.ibizlab.core.util.job;

import cn.ibizlab.core.rule.domain.RuleEngine;
import cn.ibizlab.core.util.config.RocktcermqCustmerRunner;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @author 无名小卒
 * @data 2022/8/22
 */
@Component
@Slf4j
@Async("asyncExecutor")
public class TopicListenter {
    @Value("${rocketmq.consumer.namesrvAddr:}")
    private String namesrvAddr;

    public void updruleEngine(RuleEngine ruleEngine) {
        log.info("更新规则引擎订阅频道收到消息：引擎id:{},引擎名:{}", ruleEngine.getEngineId(), ruleEngine.getEngineName());
        Map<String, DefaultMQPushConsumer> dataMap = RocktcermqCustmerRunner.getDataMap();
        if (StringUtils.isEmpty(ruleEngine.getEngineId())) {//创建规则引擎主题
            RocktcermqCustmerRunner.addtopic(ruleEngine, namesrvAddr);
        } else {
            if (dataMap.containsKey(ruleEngine.getEngineId())) {//更新规则引擎主题
                dataMap.get(ruleEngine.getEngineId()).shutdown();
                log.info("引擎id:{},引擎名:{}被关闭！", ruleEngine.getEngineId(), ruleEngine.getEngineName());
                dataMap.remove(ruleEngine.getEngineId());
            }
            RocktcermqCustmerRunner.addtopic(ruleEngine, namesrvAddr);//创建规则引擎主题
        }
    }

    public void delEngine(String key) {
        log.info("删除规则引擎订阅频道收到消息：引擎id{}", key);
        Map<String, DefaultMQPushConsumer> dataMap = RocktcermqCustmerRunner.getDataMap();
        if (dataMap.containsKey(key)) {
            DefaultMQPushConsumer defaultMQPushConsumer = dataMap.get(key);
            defaultMQPushConsumer.shutdown();
            log.info("引擎id:{}被关闭！", key);
            dataMap.remove(key);//删除相应监听的主题
        }
    }


}
