package cn.ibizlab.core.message;

import cn.ibizlab.core.extensions.cql.ExecResultRepository;
import cn.ibizlab.core.extensions.domain.ResultsMQMsg;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Slf4j
@Component
@ConditionalOnExpression("'${rocketmq.consumer.namesrvAddr:}'!='' && ${rocketmq.consumer.enabled:false}")
@RocketMQMessageListener(nameServer = "${rocketmq.consumer.namesrvAddr:}",
        topic = "${rocketmq.producer.resultsTopic:DSTRESULTSMSG}",
        selectorExpression="*",
        consumerGroup = "${rocketmq.consumer.resultsGroupName:resultsCG}",
        consumeThreadMax = 20,
        consumeMode = ConsumeMode.CONCURRENTLY
)
public class ResultMQMsgListener implements RocketMQListener<MessageExt> {

    @Autowired(required = false)
    @Lazy
    private ExecResultRepository execResultRepository;


    @Override
    public void onMessage(MessageExt messageExt) {

        try {
            log.info("MQ消息topic={}, tags={}, 消息内容={}", messageExt.getTopic(), messageExt.getTags(), messageExt.getMsgId());
            String body = new String(messageExt.getBody(), "utf-8");
            String tags = messageExt.getTags();

            ResultsMQMsg resultsMQMsg = JSON.parseObject(body, new TypeReference<ResultsMQMsg>() {});
            if(!StringUtils.isEmpty(resultsMQMsg.getKeyValueField()))
                execResultRepository.saveResultsMQMsg(resultsMQMsg);
        } catch (Exception e) {
            log.error("获取MQ消息内容异常{}",e);
        }
    }

}