package com.muyu.event.service.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.muyu.demos.model.Result;
import com.muyu.event.common.VehicleEvent;
import com.muyu.event.mapper.EventMapper;
import com.muyu.event.service.EventService;
import com.muyu.mqtt.dao.MessageData;
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.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * EventServiceImpl
 *
 * @author Yangle
 * Date 2024/6/17 19:57
 */
@Service
@Log4j2
public class EventServiceImpl implements EventService {
    @Autowired
    private EventMapper eventMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public List<VehicleEvent> getCarEventList(VehicleEvent vehicleEvent) {
        return eventMapper.getCarEventList(vehicleEvent);
    }

    @Override
    public Result<MessageData> selectEvent(VehicleEvent vehicleEvent) {
        if (vehicleEvent.getEvent() != null) {

            if (vehicleEvent.getEvent() != null) {

                if (vehicleEvent.getEvent().contains("1")) {
                    KafkaConsumer<String, String> consumer = getStringStringKafkaConsumer();
                    // 订阅主题
                    consumer.subscribe(Collections.singletonList("test1"));
                    // 创建新线程来处理消息
                    new Thread(() -> {
                        while (true) {
                            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
                            for (ConsumerRecord<String, String> record : records) {
                                // 处理消息
                                String message = record.value();
                                MessageData messageData = JSON.parseObject(message, MessageData.class);
                                // 将毫秒级时间戳转换为LocalDateTime
                                LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(messageData.getTimestamp())), ZoneId.systemDefault());

                                // 格式化输出日期时间
                                String formattedTime = dateTime.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒"));

                                if (messageData.getVehicleStatus().equals("0")){
                                    if (localCache.getIfPresent(messageData.getVin())==null){
                                        if (redisTemplate.hasKey(messageData.getVin())){
                                            redisTemplate.opsForValue().set(messageData.getVin(),"vin:"+messageData.getVin()+",故障名称:"+messageData.getVehicleStatus()+",时间:"+formattedTime,10, TimeUnit.MINUTES);
                                            log.info("该车没有存到缓存中");
                                        }
                                        localCache.put(messageData.getVin(),"vin:"+messageData.getVin()+",故障名称:GZ001"+",时间:"+formattedTime);
                                        log.info("该车没有存到缓存中");
                                    }
                                }else {
                                    redisTemplate.delete(messageData.getVin());
                                    localCache.invalidate(messageData.getVin());
                                    log.info("该车故障已修复");
//                                    rabbitTemplate.send(messageData.getVin(),);
                                }

                            }
                        }
                    }).start();
                }
                if (vehicleEvent.getEvent().contains("2")) {
                    if(vehicleEvent.getStates()){
                        if (redisTemplate.hasKey(vehicleEvent.getVin())){
                            KafkaConsumer<String, String> consumer = getStringStringKafkaConsumer();
                            // 订阅主题
                            consumer.subscribe(Collections.singletonList("test1"));
                            // 创建新线程来处理消息
                            new Thread(() -> {
                                while (true) {
                                    // 发送拉取请求
                                    ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100)); // 设置拉取超时时间为100毫秒
                                    // 处理消息
                                    for (ConsumerRecord<String, String> record : records) {
                                        redisTemplate.opsForValue().set(vehicleEvent.getVin(),record.value());
                                        System.out.println("Received message: " + record.value());
                                        // 在这里添加消息处理逻辑
                                    }
                                }
                            }).start();
                        }

                    }
                    return Result.success();
                }
                if (vehicleEvent.getEvent().contains("3")) {

                }
            }

        }
            return Result.error("车辆没有绑定事件");
    }

    /**
     * 本地缓存
     */
    Cache<String, String> localCache = Caffeine.newBuilder()
            .initialCapacity(5)
            .maximumSize(10)
            //过期时间3秒钟
            .expireAfterWrite(3, TimeUnit.HOURS)
            .build();
    /**
     * kafka消费者
     * @return
     */
    private static KafkaConsumer<String, String> getStringStringKafkaConsumer() {
        Properties props = new Properties();
        props.put("bootstrap.servers", "localhost:9092"); // Kafka服务器地址
        props.put("group.id", "Partitions"); // 消费者组ID
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); // 键反序列化器
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); // 值反序列化器
        // 创建Kafka消费者实例
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
        return consumer;
    }

    @Override
    public void eventAddRedis(VehicleEvent vehicleEvent) {
        redisTemplate.opsForValue().set(vehicleEvent.getVin(),"");
    }

    @Override
    public Result getMaximumCoordinate(String vin) {
       //获取本地缓存
        String ifPresent = localCache.getIfPresent(vin);
        return Result.error(ifPresent);
    }

    @Override
    public List<VehicleEvent> selectVehicleEvent() {
        return  eventMapper.selectVehicleEvent();
    }


//    //创建分区
//    NewTopic newTopic = new NewTopic(topic, 8, (short) 1);
//        kafkaAdmin.createOrModifyTopics(newTopic);
//    ProducerRecord<String, String> producerRecord = new ProducerRecord<>(topic, main.getVin(), JSON.toJSONString(main));
//    // 发送消息
//        kafkaTemplate.send(producerRecord);
}
