package com.usky.transfer.service.mqtt.datacollector;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.usky.common.core.util.JsonUtils;
import com.usky.transfer.domain.DeviceDataWriteVO;
import com.usky.transfer.service.QueryInfluxdbDataService;
import com.usky.transfer.service.mqtt.MqttStrategy;
import com.usky.transfer.service.rocketmq.MyProducer;
import com.usky.transfer.service.vo.MqttBaseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zyj
 * @date 2022/12/6 15:07
 */
@Slf4j
@Service("dataCollector")
public class DataCollector implements MqttStrategy {
    @Resource
    private MyProducer myProducer;
    @Autowired
    private QueryInfluxdbDataService queryInfluxdbDataService;

    public String disposeMessage(MqttBaseVO mqttBaseVO) {
        try {
            Map<String, String> tags = new HashMap<>();
            Map<String, Object> fields = new HashMap<>();
            Map map_data = JsonUtils.fromJson(mqttBaseVO.getData().toString(), Map.class);
            String productCode = map_data.get("product_id").toString().toLowerCase();
            long timestamp = Long.valueOf(map_data.get("timestamp").toString())*1000L+1L;
            String deviceId = map_data.get("device_id").toString();

            tags.put("device_id",deviceId);
            log.info("disposeMessage "+deviceId+" start111");

            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));
            }

            DeviceDataWriteVO deviceDataWriteVO = new DeviceDataWriteVO();
            deviceDataWriteVO.setDeviceUUId("");
            deviceDataWriteVO.setProductCode(productCode);
            deviceDataWriteVO.setTimestamp(timestamp);
            deviceDataWriteVO.setTags(tags);
            deviceDataWriteVO.setMetrics(metrics);

            queryInfluxdbDataService.sendDeviceDataToMQ(deviceDataWriteVO);
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        return null;
    }


}
