package com.usky.demo.service.rocketmq.influxdb;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.usky.common.core.util.JsonUtils;
import com.usky.demo.service.rocketmq.MqttStrategy;
import com.usky.demo.service.utils.TsdbUtils;
import com.usky.demo.service.vo.MQDataVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service("influx")
public class influxdb implements MqttStrategy {
    @Autowired
    private TsdbUtils influxDBUtils;

    /**
     * 设备数据存influxdb时序数据库
     * @param
     */
    @Override
    public String disposeMessage(MQDataVO mqBaseVO) {
        Map<String, String> tags = new HashMap<>();
        Map<String, Object> fields = new HashMap<>();
        Map<String, String> realtags = new HashMap<>();
        Map<String, Object> realfields = new HashMap<>();
        Map map_data = JsonUtils.fromJson(mqBaseVO.getData().toString(),Map.class);
        System.out.println("test11111");
        String deviceUUId = map_data.get("deviceUUId").toString();
        String productCode = map_data.get("productCode").toString().toLowerCase();
        Long timestamp = Long.valueOf(map_data.get("timestamp").toString());
        String tableName = deviceUUId;
        System.out.println("test22222");

        Object tg = JSONObject.toJSONString(map_data.get("tags"));
        JSONObject tag = JSON.parseObject(tg.toString());
        for (String entry : tag.keySet()){
            tags.put(entry.toLowerCase(),tag.get(entry).toString());
        }
        System.out.println("test33333"+tg.toString());

        Object met = JSONObject.toJSONString(map_data.get("metrics"));
        JSONObject metrics = JSON.parseObject(met.toString());
        for(String entry : metrics.keySet()){
            fields.put(entry.toLowerCase(),metrics.get(entry));
            realfields.put(entry.toLowerCase(),Float.valueOf(metrics.get(entry).toString()));
        }
        System.out.println("test44444"+met.toString());

        influxDBUtils.insertOne1(tableName,tags,fields,timestamp);

        //创建设备实时数据表，用于保存每个设备最新一条数据记录
        String realtimeTableName = "datarealtime";
        long realtimestamp = 1744164000001L;
        realtags.put("device_uuid",deviceUUId);
        realfields.put("realtime", (map_data.get("timestamp").toString()));
        realfields.put("device_uuid",deviceUUId);
        realfields.put("device_id",tags.get("device_id"));
        influxDBUtils.insertOne1(realtimeTableName,realtags,realfields,realtimestamp);
        return "";
    }
}
