package com.ruoyi.dj.mqtt.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.dj.mqtt.error.ErrorCodeMap;

import java.util.Map;

/**
 * @auther 周志雄
 * @date 2024/7/9 16:01
 */
public class HandleResultUtil {
    public static AjaxResult handleResult(String json, Map<String, Object> data, String message) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // 将字符串解析为 JSON 对象
            ObjectNode jsonNode = null;
            jsonNode = (ObjectNode) objectMapper.readTree(json);
            JsonNode resultNode = jsonNode.path("data").path("result");
            Integer result = Integer.valueOf(resultNode.asText());
            // 根据 result 值判断是否成功
            if (result != 0) {
                // 官方的 Bug、网络异常，连接断开、其实是正常的
                if (result == 514303) {
                    return AjaxResult.success().put("data", data);
                }
                String errorMessage = ErrorCodeMap.errorCodeMap.getOrDefault(result, "未知错误");
                return AjaxResult.error(errorMessage);
            } else {
                return AjaxResult.success(message).put("data", data);
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
