package com.muyu.processing.consumer;

import cn.hutool.core.thread.ThreadUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.muyu.processing.basic.EventPublisher;
import com.muyu.processing.utils.CacheUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * kafka消费者
 * @Author：杨鹏
 * @Package：com.muyu.processing.consumer
 * @Project：car-cloud-server
 * @name：KafkaConsumerService
 * @Date：2024/9/28 22:08
 */
@Log4j2
@Component
public class KafkaConsumerService implements InitializingBean {

    /**
     * 订阅的Topic
     */
    private static final String TIPSY = "tipsy";

    @Resource
    private KafkaConsumer kafkaConsumer;

    @Resource
    private CacheUtil cacheUtil;

    @Resource
    private EventPublisher eventPublisher;

    /**
     * 线程池
     */
    private final ExecutorService executorService = Executors.newFixedThreadPool(10);

    @Override
    public void afterPropertiesSet() throws Exception {

        Thread thread = new Thread(() -> {
            log.info("启动线程监听Topic: {}", TIPSY);
            // 延迟1秒
            ThreadUtil.sleep(1000);
            // 订阅主题
            Collection<String> topics = Lists.newArrayList(TIPSY);
            kafkaConsumer.subscribe(topics);
            while (true) {
                // 轮询消费消息
                ConsumerRecords<String, String> consumerRecords = kafkaConsumer.poll(Duration.ofMillis(1000));
                consumerRecords.forEach(record -> executorService.execute(() -> publish(record)));
            }
        });
        thread.start();

    }

    private  void publish(ConsumerRecord consumerRecord) {
        //从ConsumerRecord中获取消费数据
        String originalMsg = (String) consumerRecord.value();
        log.info("从Kafka中消费的原始数据: " + originalMsg);
        //把消费数据转换为JSON对象
        JSONObject jsonObject = JSON.parseObject(originalMsg);
        // 发布事件
        eventPublisher.eventPublish(jsonObject);
    }

}
