package cn.com.taiji.beidou.track.consumer;

import cn.com.taiji.beidou.track.entity.BeidouTrackEntity;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @author liangjf
 */
@Component
@Slf4j
@ConditionalOnProperty(name = "taiji.kafka.consumer.beidou.enable",havingValue = "true")
public class BeidouShipTrackConsumer {

    @Resource
    private KafkaTemplate kafkaTemplate;
    @Value("${taiji.kafka.productor.beidou.topic}")
    private String kafkaTopic;

    @KafkaListener(
            containerFactory = "kafkaContainerFactory",
            topics = {"${taiji.kafka.consumer.beidou.topic}"}
    )
    public void dynamicTrack(List<ConsumerRecord<?, ?>> records, Acknowledgment ack) {
        for (ConsumerRecord<?, ?> record : records) {
            Optional message = Optional.ofNullable(record.value());
            Object msg = message.get();
            BeidouTrackEntity entity = JSONObject.parseObject(msg.toString(), BeidouTrackEntity.class);
            String data = JSONObject.toJSONString(entity);
            kafkaTemplate.send(kafkaTopic, entity.getDeviceId(),data);
        }
        ack.acknowledge();
    }
}
