package com.zcloud.modules.map.controller;

/**
 * @author jinqiang.zhang
 * @version 2023.1
 * @date 2025/4/10 09:26
 */
import com.alibaba.fastjson.JSONObject;
import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.errors.WakeupException;
import org.apache.kafka.common.serialization.StringDeserializer;
import java.time.Duration;
import java.util.*;

public class KafkaConsumerExample {
    private static final String TOPIC = "point_1";
    private static final String BOOTSTRAP_SERVERS = "172.16.11.2:9092";
    private static final String GROUP_ID = "finds1";

    public static void main(String[] args) {
        // 1. 配置消费者属性
        Properties props = new Properties();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS);
        props.put(ConsumerConfig.GROUP_ID_CONFIG, GROUP_ID);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());

        // 可选配置（根据需求调整）
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest"); // 从最早的消息开始消费 earliest
//        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false"); // 禁用自动提交偏移量

        // 2. 创建消费者实例
        try (Consumer<String, String> consumer = new KafkaConsumer<>(props)) {

            // 3. 订阅主题
            consumer.subscribe(Collections.singletonList(TOPIC));

            // 4. 持续轮询消息
            Boolean boo = true;
            Map<String,String> overMap = new HashMap<>();
            Map<String,String> timeMap = new HashMap<>();
            try {
                while (boo) {
                    ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(3000));
                    if(overMap.size()>300){
                        boo=false;
                        continue;
                    }
                    for (ConsumerRecord<String, String> record : records) {
                        // 处理消息逻辑
                        // System.out.printf("Received message: key=%s, value=%s, partition=%d, offset=%d%n",
                        //         record.key(), record.value(), record.partition(), record.offset());
                        // terminalNo 设备id
                        JSONObject json = JSONObject.parseObject(record.value());
                        String terminalInfoStr = json.get("terminalInfo").toString();
                        JSONObject terminalInfoJson = JSONObject.parseObject(terminalInfoStr);
                        String terminalNo = terminalInfoJson.get("terminalNo").toString();
                        String str3 = json.get("serverTime").toString();
                        if(timeMap.containsKey(terminalNo)){
                            Long a = Long.parseLong(timeMap.get(terminalNo));
                            Long b = Long.parseLong(str3);
                            if(a<b){
                                timeMap.put(terminalNo,str3);
                                overMap.put(terminalNo, record.value());
                            }
                        }else {
                            timeMap.put(terminalNo,str3);
                            overMap.put(terminalNo, record.value());
                        }
                        // 业务处理代码写在这里...
                    }
                    // 手动提交偏移量（当ENABLE_AUTO_COMMIT_CONFIG=false时）
//                    consumer.commitSync();
                }
            } catch (WakeupException e) {
                // 忽略异常，正常关闭
            } catch (Exception e) {
                e.printStackTrace();
            }
            // System.out.println("==========================");
            // for (String key : overMap.keySet()) {
            //     System.out.println(key + ":" + overMap.get(key));
            // }
        }
    }
}
