//package com.yeejoin.equip.kafka;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.yeejoin.amos.component.influxdb.InfluxDbConnection;
//import com.yeejoin.equip.config.KafkaConsumerConfig;
//import com.yeejoin.equip.entity.EquipmentIndexVO;
//import com.yeejoin.equip.entity.IndicatorData;
//import com.yeejoin.equip.mapper.tdengine.IndicatorDataMapper;
//import com.yeejoin.equip.utils.ElasticSearchUtil;
//import com.yeejoin.equip.utils.RedisUtils;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.ObjectUtils;
//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.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.boot.CommandLineRunner;
//import org.springframework.stereotype.Component;
//import java.text.SimpleDateFormat;
//import java.time.Duration;
//import java.util.*;
//import java.util.concurrent.*;
//import java.util.concurrent.atomic.AtomicLong;
//
///**
// * @author LiuLin
// * @date 2023年08月01日 17:27
// */
//@Slf4j
//@Component
//public class KafkaConsumerWithThread implements CommandLineRunner {
//    final private static AtomicLong sendThreadPoolCounter = new AtomicLong(0);
//    final public static ExecutorService pooledExecutor =
//            Executors.newFixedThreadPool(60 + Runtime.getRuntime().availableProcessors(),
//                    createThreadFactory());
//    //iot转发实时消息存入influxdb前缀
//    private static final String MEASUREMENT = "iot_data_";
//    private static final String TOTAL_DATA_ = "total_data_";
//    private static final String ES_INDEX_NAME_JX = "jxiop_equipments";
//    //装备更新最新消息存入influxdb前缀
//    private static final String TRUE = "true";
//    private static final String FALSE = "false";
//    @Autowired
//    protected KafkaProducerService kafkaProducerService;
//    @Autowired
//    private KafkaConsumerConfig consumerConfig;
//    @Autowired
//    private InfluxDbConnection influxDbConnection;
//    @Autowired
//    private RedisUtils redisUtils;
//    @Autowired
//    private IndicatorDataMapper indicatorDataMapper;
//
//    @Value("${kafka.alarm.topic}")
//    private String alarmTopic;
//
//    @Value("${kafka.topic}")
//    private String topic;
//
//    @Autowired
//    private ElasticSearchUtil elasticSearchUtil;
//
//    private static ThreadFactory createThreadFactory() {
//        return runnable -> {
//            Thread thread = new Thread(runnable);
//            thread.setName(String.format("kafka-consumer-iot-pool-%d", KafkaConsumerWithThread.sendThreadPoolCounter.getAndIncrement()));
//            return thread;
//        };
//    }
//
//    @Override
//    public void run(String... args) {
//        Thread thread = new Thread(new KafkaConsumerThread(consumerConfig.consumerConfigs(), topic));
//        thread.start();
//    }
//
//    private void processRecord(ConsumerRecord<String, String> record) {
//        JSONObject jsonObject = JSONObject.parseObject(record.value());
//        IndicatorData indicatorData = JSON.parseObject(record.value(), IndicatorData.class);
//        String dataType = jsonObject.getString("dataType");
//        String indexAddress = jsonObject.getString("address");
//        String gatewayId = jsonObject.getString("gatewayId");
//        String value = jsonObject.getString("value");
//        String key = indexAddress + "_" + gatewayId;
//        String signalType = jsonObject.getString("signalType");
//        log.info("接收Kafka消息! address: {}, gatewayId: {},value:{}", indexAddress, gatewayId,value);
//        try {
//            if (redisUtils.hasKey(key)) {
//                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                EquipmentIndexVO equipmentSpeIndex = JSONObject.parseObject(redisUtils.get(key), EquipmentIndexVO.class);
//                String valueLabel = valueTranslate(value, equipmentSpeIndex.getValueEnum());
//
//                //更新数据入ES库
//                Map<String, Object> paramJson = new HashMap<>();
//                if (!Arrays.asList(TRUE, FALSE).contains(value)) {
//                    paramJson.put("valueF", Float.parseFloat(value));
//                }
//                paramJson.put("value", value);
//                paramJson.put("valueLabel", valueLabel.isEmpty() ? value : valueLabel);
//                paramJson.put("createdTime", new Date());
//                paramJson.put("unit", equipmentSpeIndex.getUnitName());
//                elasticSearchUtil.updateData(ES_INDEX_NAME_JX, key, JSON.toJSONString(paramJson));
//
//                Map<String, String> tagsMap = new HashMap<>();
//                Map<String, Object> fieldsMap = new HashMap<>();
//                tagsMap.put("equipmentsIdx", key);
//                fieldsMap.put("address", indexAddress);
//                fieldsMap.put("gatewayId", gatewayId);
//                fieldsMap.put("dataType", dataType);
//                fieldsMap.put("isAlarm", String.valueOf(equipmentSpeIndex.getIsAlarm()));
//                fieldsMap.put("equipmentSpecificName", equipmentSpeIndex.getEquipmentSpecificName());
//
//                fieldsMap.put("value", value);
//                fieldsMap.put("valueLabel", valueLabel.isEmpty() ? value : valueLabel);
//                fieldsMap.put("equipmentIndexName", equipmentSpeIndex.getEquipmentIndexName());
//                fieldsMap.put("unit", equipmentSpeIndex.getUnitName());
//                fieldsMap.put("createdTime", simpleDateFormat.format(new Date()));
//
//                indicatorData.setIsAlarm(String.valueOf(equipmentSpeIndex.getIsAlarm()));
//                indicatorData.setEquipmentIndexName(equipmentSpeIndex.getEquipmentIndexName());
//                indicatorData.setEquipmentSpecificName(equipmentSpeIndex.getEquipmentSpecificName());
//                indicatorData.setUnit(equipmentSpeIndex.getUnitName());
//                indicatorData.setEquipmentsIdx(key);
//                indicatorData.setValueLabel(valueLabel.isEmpty() ? value : valueLabel);
//
//                //变位存入influxdb
//                if ("transformation".equalsIgnoreCase(signalType)) {
//                    influxDbConnection.insert(MEASUREMENT + gatewayId, tagsMap, fieldsMap);
//                    indicatorDataMapper.insert(indicatorData);
//                    log.info("TDEngine入库成功，{},value:{}",indicatorData.getEquipmentsIdx(),indicatorData.getValue());
//                } else {
//                    influxDbConnection.insert(TOTAL_DATA_ + indicatorData.getGatewayId(), tagsMap, fieldsMap);
//                    log.info("总召入库，key:{}",indicatorData.getEquipmentsIdx());
//                }
//
//                if (0 != equipmentSpeIndex.getIsAlarm()) {
//                    fieldsMap.putAll(tagsMap);
//                    kafkaProducerService.sendMessageAsync(alarmTopic, JSON.toJSONString(fieldsMap));
//                    log.info("===========发送告警信息，key:{}",indicatorData.getEquipmentsIdx());
//                }
//            }
//        } catch (Exception e) {
//            log.error("Iot透传消息解析入库失败" + e.getMessage(), e);
//        }
//    }
//
//    private String valueTranslate(String value, String enumStr) {
//        if (ObjectUtils.isEmpty(enumStr)) {
//            return "";
//        }
//        try {
//            JSONArray jsonArray = JSONArray.parseArray(enumStr);
//            for (int i = 0; i < jsonArray.size(); i++) {
//                JSONObject jsonObject = jsonArray.getJSONObject(i);
//                if (jsonObject.get("key").equals(value)) {
//                    return jsonObject.getString("label");
//                }
//            }
//        } catch (Exception e) {
//            log.error("告警枚举转换异常" + e.getMessage(), e);
//        }
//        return "";
//    }
//
//    public class KafkaConsumerThread implements Runnable {
//        private final KafkaConsumer<String, String> kafkaConsumer;
//
//        public KafkaConsumerThread(Properties props, String topic) {
//            this.kafkaConsumer = new KafkaConsumer<>(props);
//            this.kafkaConsumer.subscribe(Collections.singletonList(topic));
//        }
//
//        @Override
//        public void run() {
//            while (true) {
//                ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(500));
//                for (ConsumerRecord<String, String> record : records) {
//                    pooledExecutor.submit(() -> {
//                        processRecord(record);
//                    });
//                }
//            }
//        }
//    }
//}
