#ifndef DEVICE_CTRL_JSON_UTIL_H
#define DEVICE_CTRL_JSON_UTIL_H
#include <nlohmann/json.hpp>
#include "common/spdlog/logging.h"

#define JSON_FIELD(field)  try \
{ \
    if (j.contains(#field)) \
    { \
        j.at(#field).get_to(o.field); \
    } \
} catch (const std::exception &e) \
{ \
    LOGGER_ERROR("JSON 解析失败，字段：【{}】，错误：{}", #field, e.what()); \
} \
catch (...) \
{ \
    LOGGER_ERROR("未知异常，JSON 解析失败，字段：【{}】", #field); \
}

#define JSON_FIELD_SPARE(field, spareField)  try \
{ \
    if (j.contains(#field)) \
    { \
        j.at(#field).get_to(o.field); \
    } \
    else if (j.contains(#spareField)) \
    { \
        j.at(#spareField).get_to(o.field); \
    } \
} catch (const std::exception &e) \
{ \
    LOGGER_ERROR("JSON 解析失败，字段：【{}】，错误：{}", #field, e.what()); \
} \
catch (...) \
{ \
    LOGGER_ERROR("未知异常，JSON 解析失败，字段：【{}】", #field); \
}

#define JSON_FIELD_DEFAULT(field, default_val)  try \
{ \
    if (j.contains(#field)) \
    { \
        j.at(#field).get_to(o.field); \
    } \
    else \
    { \
        o.field = default_val; \
    } \
} catch (const std::exception &e) \
{ \
    LOGGER_ERROR("JSON 解析失败，字段：【{}】，错误：{}", #field, e.what()); \
} \
catch (...) \
{ \
    LOGGER_ERROR("未知异常，JSON 解析失败，字段：【{}】", #field); \
}

namespace zsy::JSON
{
    template<typename T>
    std::optional<T> parse(const std::string &str)
    {
        if (!str.empty())
        {
            try
            {
                auto jsonData = nlohmann::json::parse(str);
                return jsonData.get<T>();
            } catch (std::exception &e)
            {
                LOGGER_ERROR("数据解析失败：{}", e.what());
            } catch (...)
            {
                LOGGER_ERROR("数据解析失败，未知异常");
            }
        }
        return std::nullopt;
    }

    template<typename T>
    std::string toJsonStr(T &&obj)
    {
        try
        {
            return nlohmann::json(std::forward<T>(obj)).dump();
        } catch (std::exception &e)
        {
            LOGGER_ERROR("数据序列化失败：{}", e.what());
        } catch (...)
        {
            LOGGER_ERROR("数据序列化失败，未知异常");
        }
        return {};
    }
}
#endif // DEVICE_CTRL_JSON_UTIL_H