package cn.ibizlab.core.extensions.util;

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.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Slf4j
@Component
public class ResultsMQMsgConsumeListener implements MessageListenerConcurrently {

    @Value("${rocketmq.producer.resultsTopic:DSTRESULTSMSG}")
    private String resultsTopic;

    @Autowired(required = false)
    @Lazy
    private ExecResultRepository execResultRepository;
    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        if (CollectionUtils.isEmpty(list)) {
            log.info("MQ接收消息为空，直接返回成功");
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
        //System.out.println(System.currentTimeMillis());
        MessageExt messageExt = list.get(0);
        log.info("MQ接收到的消息为：" + messageExt.toString());
        try {
            String topic = messageExt.getTopic();
            String tags = messageExt.getTags();
            String body = new String(messageExt.getBody(), "utf-8");

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

        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
}
