package com.xueyi.system.emcs.service;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xueyi.common.mqtt.service.MqttMessageHandler;
import com.xueyi.common.redis.service.RedisService;
import com.xueyi.common.web.utils.DateUtils;
import com.xueyi.system.emcs.domain.dto.RedisBaseDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author yk
 * @description
 * @date 2023-05-10 19:08
 */
@Service
public class HeartBeatMessageHandler implements MqttMessageHandler {

    @Autowired
    private RedisService redis;

    private  final static String HEART_MQTT_PREFIX = "digital-man";
    private  final static Integer REDIS_LIST_SIZE = 60;

    @Autowired
    private BaseRedisListDataCache baseRedisListDataCache;
    @Override
    public void handleMessage(String topic, String message) throws Exception{
        System.err.println("HeartBeatMessageHandler: " + message);

        JSONObject heartBeatObj = JSONObject.parseObject(message);
        String devId = heartBeatObj.getString("devId");
        String timestamp = heartBeatObj.getString("timestamp");
        String network = heartBeatObj.getString("wifi_rssi");
        String cpu_max = heartBeatObj.getString("cpuinfo_max_freq");
        String cpu_scaling = heartBeatObj.getString("scaling_cur_freq");
        String cpu = Double.valueOf(cpu_scaling) / Double.valueOf(cpu_max) * 100 + "";
        String memory_cur = heartBeatObj.getString("memory_total");
//        String memoryTotal = heartBeatObj.getString("MemTotal").substring(0,heartBeatObj.getString("MemTotal").length() - 2);
        String memoryTotal = heartBeatObj.getString("memory_total");
        Double memoryFree = Double.valueOf(heartBeatObj.getString("memory_free"));
        String memory = (Double.valueOf(memoryTotal) - memoryFree) / Double.valueOf(memoryTotal)  * 100 + "";
        String occurTime = "";

        occurTime = DateUtils.formatDate(DateUtils.parseLongToDate(timestamp),"HH:mm");


        if (StringUtils.isNotEmpty(devId)) {
            if (StringUtils.isNotEmpty(network)){
                baseRedisListDataCache.init (REDIS_LIST_SIZE).addToList(HEART_MQTT_PREFIX+":"+devId+":network", new RedisBaseDto(occurTime, network));
            }
            if (StringUtils.isNotEmpty(cpu)) {
                baseRedisListDataCache.init(REDIS_LIST_SIZE).addToList(HEART_MQTT_PREFIX + ":" + devId + ":cpu", new RedisBaseDto(occurTime, cpu));
            }
            if (StringUtils.isNotEmpty(memory)) {
                baseRedisListDataCache.init(REDIS_LIST_SIZE).addToList(HEART_MQTT_PREFIX + ":" + devId + ":memory", new RedisBaseDto(occurTime, memory));
            }
        }
        System.err.println(heartBeatObj.toJSONString());
    }
}
