//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.entity.EquipmentIndexVO;
//import com.yeejoin.equip.entity.IndicatorData;
//import com.yeejoin.equip.eqmx.EmqMessageService;
//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.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.kafka.annotation.KafkaListener;
//import org.springframework.kafka.support.Acknowledgment;
//import org.springframework.stereotype.Service;
//
//import javax.annotation.PostConstruct;
//import java.text.SimpleDateFormat;
//import java.util.*;
//import java.util.concurrent.ExecutorService;
//import java.util.concurrent.Executors;
//
///**
// * @author LiuLin
// * @date 2023/6/25
// * @apiNote kafka 消费服务类
// */
//@Slf4j
//@Service
//public class KafkaConsumerService {
//
//    //装备更新最新消息存入influxdb前缀
//    private static final String TRUE = "true";
//    private static final String FALSE = "false";
//    private static final String ES_INDEX_NAME_JX = "jxiop_equipments";
//
//    private static final String MEASUREMENT = "iot_data_";
//    private static final String TOTAL_DATA_ = "total_data_";
//    @Autowired
//    protected KafkaProducerService kafkaProducerService;
//
//    @Autowired
//    private RedisUtils redisUtils;
//
//    @Autowired
//    private ElasticSearchUtil elasticSearchUtil;
//
//    @Autowired
//    private InfluxDbConnection influxDbConnection;
//
//    @Autowired
//    private IndicatorDataMapper indicatorDataMapper;
//    ExecutorService service = Executors.newFixedThreadPool(10);
//
//    @Value("${kafka.alarm.topic}")
//    private String alarmTopic;
//
//    /**
//     * 批量消费kafka消息
//     * Kafka消息转emq
//     *
//     * @param consumerRecords messages
//     * @param ack             ack
//     */
//    @KafkaListener(id = "consumerSingle", topics = "#{'${kafka.topic}'.split(',')}", groupId = "messageConsumerGroup")
//    public void listen1(List<ConsumerRecord<String, String>> consumerRecords, Acknowledgment ack) {
//        try {
//            for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
//                Optional<?> kafkaMessage = Optional.ofNullable(consumerRecord.value());
//                kafkaMessage.ifPresent(o -> this.handleMessage((String) o));
//            }
//        } catch (Exception e) {
//            log.error("kafka失败，当前失败的批次: data:{}", consumerRecords);
//        } finally {
//            ack.acknowledge();
//        }
//    }
//
//    private void handleMessage(String record) {
//        JSONObject jsonObject = JSONObject.parseObject(record);
//        IndicatorData indicatorData = JSON.parseObject(record, 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 "";
//    }
//}
//
//
