package cn.ibizlab.core.util.config;

import cn.ibizlab.core.extensions.util.GeneralConsumeMsgListenerProcessor;
import cn.ibizlab.core.rule.domain.RuleEngine;
import cn.ibizlab.core.rule.mapper.RuleEngineMapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static cn.ibizlab.core.enums.RuleEnginerParamEnum.*;

@Slf4j
//@Component
//@ConditionalOnExpression("${rocketmq.consumer.enabled:false}")
public class RocktcermqCustmerRunner implements ApplicationRunner {
    @Autowired
    private RuleEngineMapper ruleEngineMapper;

    @Value("${rocketmq.consumer.namesrvAddr:}")
    private String namesrvAddr;
    //mq消费者
    private static Map<String, DefaultMQPushConsumer> dataMap = new ConcurrentHashMap();

    @Override
    public void run(ApplicationArguments args) {
        List<RuleEngine> ruleEngines = ruleEngineMapper.selectList(new LambdaQueryWrapper<RuleEngine>()
                .select(RuleEngine::getEngineId, RuleEngine::getExtParams));
        if (!StringUtils.isEmpty(ruleEngines)) {
            for (int i = 0, len = ruleEngines.size(); i < len; i++) {
                addtopic(ruleEngines.get(i), namesrvAddr);
            }
        }
    }

    /**
     * 添加规则引擎
     *
     * @param ruleEngine
     * @param namesrvAddr
     */
    public static void addtopic(RuleEngine ruleEngine, String namesrvAddr) {
        Map map = getParamMap(ruleEngine.getExtParams());
        DefaultMQPushConsumer consumer = null;
        if (AUTO_CREATE.getValue().equals(map.get(AUTO_CREATE.getProperty()))
                && !StringUtils.isEmpty(map.get(TOPIC.getProperty()))
                && !StringUtils.isEmpty(map.get(GROUP.getProperty()))) {
            if (!StringUtils.isEmpty(dataMap.get(ruleEngine.getEngineId()))) {
                log.warn("ruleEngineConsumer 不能重复创建 EngineId={}, groupName={}, topics={}, namesrvAddr={}", ruleEngine.getEngineId(), map.get(GROUP.getProperty()), ruleEngine.getModelId(), namesrvAddr);
                return;
            }
            try {
                log.info("ruleEngineConsumer 正在创建---------------------------------------");
                consumer = new DefaultMQPushConsumer((String) map.get(GROUP.getProperty()));
                consumer.setNamesrvAddr(namesrvAddr);
                consumer.setConsumeThreadMin(1);
                consumer.setConsumeThreadMax(1);
                consumer.setConsumeMessageBatchMaxSize(1);
                // 设置监听
                GeneralConsumeMsgListenerProcessor messageListener = new GeneralConsumeMsgListenerProcessor(ruleEngine.getEngineId());
                consumer.registerMessageListener(messageListener);
                consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
                consumer.setInstanceName("dstMQMsgConsumer");
                dataMap.put(ruleEngine.getEngineId(), consumer);
                consumer.subscribe((String) map.get(TOPIC.getProperty()), "*");
                consumer.start();
                log.info("ruleEngineConsumer 创建成功 EngineId={} groupName={}, topics={}, namesrvAddr={}",ruleEngine.getEngineId(), map.get(GROUP.getProperty()),map.get(TOPIC.getProperty()), namesrvAddr);
            } catch (MQClientException e) {
                e.printStackTrace();
                log.error("ruleEngineConsumer 创建失败!");
            }
        }
    }

    /**
     * 获取参数map
     *
     * @param extParams
     * @return
     */
    public static Map getParamMap(String extParams) {
        JSONArray objects = JSON.parseArray(extParams);
        HashMap map = new HashMap();
        if (!CollectionUtils.isEmpty(objects)) {
            for (int j = 0, len1 = objects.size(); j < len1; j++) {
                map.put(objects.getJSONObject(j).getString(ELEMENT_NAME.getProperty()), objects.getJSONObject(j).getString(ELEMENT_NAME.getValue()));
            }
        }
        return map;
    }

    public static Map<String, DefaultMQPushConsumer> getDataMap() {
        return dataMap;
    }

}
