package cn.ibizlab.core.extensions.util;

import cn.ibizlab.core.extensions.domain.EngineMQMsg;
import cn.ibizlab.core.extensions.service.RuleEngineExService;
import cn.ibizlab.util.security.SpringContextHolder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 通用MQ订阅消息处理
 */
@Slf4j
public class GeneralConsumeMsgListenerProcessor implements MessageListenerOrderly {

    private static RuleEngineExService ruleEngineExService = SpringContextHolder.getApplicationContext().getBean(RuleEngineExService.class);
    private String key = "";//标记消费者,与需要操作的规则引擎id相等

    @Override
    public  ConsumeOrderlyStatus consumeMessage(List<MessageExt> list, ConsumeOrderlyContext consumeOrderlyContext) {
        if (CollectionUtils.isEmpty(list)) {
            log.info("MQ接收消息为空，直接返回成功");
            return ConsumeOrderlyStatus.SUCCESS;
        }
        MessageExt messageExt = list.get(0);
        try {
            String topic = messageExt.getTopic();
            String tags = messageExt.getTags();
            String body = new String(messageExt.getBody(), "utf-8");
            if(!StringUtils.isEmpty(body)) {
                EngineMQMsg engineMQMsg = JSON.parseObject(body, new TypeReference<EngineMQMsg>() {
                });
                engineMQMsg.setEngineId(key);
                log.info("MQ接收到的消息为：topic={}, tags={}, 消息内容={}", topic, tags, body);
                ruleEngineExService.processData(engineMQMsg);
            }
            log.info("MQ消息消费成功");
        } catch (Exception e) {
            log.error("获取MQ消息内容异常{}", e);
        }
        return ConsumeOrderlyStatus.SUCCESS;
    }

    public GeneralConsumeMsgListenerProcessor(String key) {
        this.key = key;
    }

}
