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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.core.util.JsonUtils;
import com.usky.transfer.domain.*;
import com.usky.transfer.service.*;
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.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

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

    public String disposeMessage(MqttBaseVO mqttBaseVO) {
        try {
            String[] topics = mqttBaseVO.getTopic().toString().split("/");
            String topic_deviceUUID = topics[3];
            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("productCode").toString().toLowerCase();

            long timestamp = Long.valueOf(map_data.get("timestamp").toString());
            String deviceUuid = map_data.get("deviceUuid").toString();

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

            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(deviceUuid);
            deviceDataWriteVO.setProductCode(productCode);
            deviceDataWriteVO.setTimestamp(timestamp);
            deviceDataWriteVO.setTags(tags);
            deviceDataWriteVO.setMetrics(metrics);

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

        return null;
    }


}
