package org.ts.ddcs.kafka;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;

import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;
import org.ts.ddcs.common.util.BytesHelp;
import org.ts.ddcs.dataStream.DataStreamAdapter;
import org.ts.ddcs.dataStream.DataStreamManageHolder;


/**
 * 消息处理器
 *
 * @author
 */
@Slf4j
@Component
public class MessageHandler {

    @KafkaListener(groupId = "${spring.kafka.consumer.group-id}", topics = "${spring.mq-topic.ywxt-rtu-datagram-down}", containerFactory = "ackContainerFactory")
    public void ywxtRtuStatus(ConsumerRecord record, Acknowledgment acknowledgment) {
        try {
            String message = (String) record.value();
            JSONObject dto = JSON.parseObject(message, JSONObject.class);
            String rtuCode = dto.getString("rtuCode");
            String datagram = dto.getString("datagram");
            DataStreamAdapter dataStreamAdapter = DataStreamManageHolder.newInstance().dataStreamManager.getAdapter(rtuCode);
            if (null != dataStreamAdapter) {
                dataStreamAdapter.output(BytesHelp.hexStr2Bytes(datagram));
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            // 手动提交 offset
            acknowledgment.acknowledge();
        }
    }

}
