#include "ConfigManager.h"
#include "Globals.h"
#include "LoggerHelper.h"

#include <QApplication>
#include <QCoreApplication>
#include <QMutex>
#include <QTime>
#include <QDebug>
#include <QMutexLocker>

#include <QJsonDocument>
#include <QJsonArray>

#include <QFile>

ConfigManager* cfgManage = nullptr;
ConfigManager *ConfigManager::instance()
{
    static QMutex mutex;
    if (!cfgManage) {
        QMutexLocker locker(&mutex);
        if (!cfgManage) {
            cfgManage = new ConfigManager();
        }
    }

    return cfgManage;
}

ConfigManager::ConfigManager(QObject *parent)
    : QObject{parent}
{
    initConfigObject();
    m_tcu_cfg_watcher = new QFileSystemWatcher(this);
    connect(m_tcu_cfg_watcher, &QFileSystemWatcher::fileChanged,
            this, &ConfigManager::slotTcuConfigFileChanged);
}

uint8_t ConfigManager::loadTcuConfigFile(const QString &path)
{
    if (QFile::exists(path)) {
        m_tcu_cfg_watcher->addPath(path); // 开始监视文件
        if (reloadConfig(TCU_CONFIG, path)) {
            tcuCfgFromJson();
        } else {
            return INIT_CONFIG_LOAD_ERROR;
        }
    } else {
        return INIT_CONFIG_LOAD_ERROR;
    }

    return INIT_OK;
}

uint8_t ConfigManager::loadAuthorizationList(const QString &path)
{
    if (QFile::exists(path)) {
        if (reloadConfig(AUTHORIZATION, path)) {
            authorizationFromJson();
        } else {
            return INIT_CONFIG_LOAD_ERROR;
        }
    } else {
        return INIT_CONFIG_LOAD_ERROR;
    }

    return INIT_OK;
}

uint8_t ConfigManager::loadChargingProfiles(const QString &path)
{
    if (QFile::exists(path)) {
        if (reloadConfig(CHARGING_PROFILE, path)) {
            chargingCfgFromJson();
        } else {
            return INIT_CONFIG_LOAD_ERROR;
        }
    } else {
        return INIT_CONFIG_LOAD_ERROR;
    }
    return INIT_OK;
}

uint8_t ConfigManager::loadConfigKey(const QString &path)
{
    if (QFile::exists(path)) {
        if (reloadConfig(CONFIG_KEY, path)) {
            configKeyFromJson();
        } else {
            return INIT_CONFIG_LOAD_ERROR;
        }
    } else {
        return INIT_CONFIG_LOAD_ERROR;
    }
    return INIT_OK;
}

// 从文件中加载充电记录
uint8_t ConfigManager::loadOffileChargingRecords(const QString &path)
{
    // 如果文件存在
    if (QFile::exists(path)) {
        // 重新加载配置
        if (reloadConfig(CHARGING, path)) {
            // 从JSON中加载充电记录
            chargingRecordsFromJson();
        } else {
            // 加载配置失败
            return INIT_CONFIG_LOAD_ERROR;
        }
    } else {
        // 文件不存在
        return INIT_CONFIG_LOAD_ERROR;
    }
    // 加载成功
    return INIT_OK;
}

// 加载CCU配置文件
uint8_t ConfigManager::loadCcuConfigFile(const QString &path)
{
    // 如果文件存在
    if (QFile::exists(path)) {
        // 重新加载配置
        if (reloadConfig(CCU_CONFIG, path)) {
            // 从JSON中获取配置
            ccuCfgFromJson();
        } else {
            // 加载配置失败
            return INIT_CONFIG_LOAD_ERROR;
        }
    } else {
        // 文件不存在
        return INIT_CONFIG_LOAD_ERROR;
    }
    // 加载成功
    return INIT_OK;
}

// 获取TCP服务器配置信息
tcp_server_cfg_info_t ConfigManager::getTcpServerCfg()
{
    // 返回TCP服务器配置信息
    return m_tcu_cfg.tcp_server_cfg;
}

// 获取TcuGui日志路径
QString ConfigManager::getTcuGuiLogPath()
{
    // 返回TcuGui配置中的日志路径
    return m_tcu_cfg.tcu_message_log_path;
}

// 获取当前配置的语言
int ConfigManager::getLanguage()
{
    // 返回当前配置的语言
    return m_tcu_cfg.language;
}

// 设置语言
void ConfigManager::setLanguage(int language)
{
    // 将传入的语言参数赋值给m_tcu_cfg中的language成员变量
    m_tcu_cfg.language = language;
}

// 获取管理员配置
admin_cfg_info_t ConfigManager::getAdminConfig()
{
    // 返回管理员配置
    return m_tcu_cfg.admin_cfg;
}

// 设置管理员配置
void ConfigManager::setAdminConfig(const admin_cfg_info_t &admin_cfg)
{
    // 将传入的管理员配置赋值给m_tcu_cfg中的admin_cfg
    m_tcu_cfg.admin_cfg = admin_cfg;
}

void ConfigManager::initConfigObject()
{
    // 初始化TCU_CONFIG配置对象
    m_cfg_object[TCU_CONFIG] = QJsonObject();
    // 初始化CCU_CONFIG配置对象
    m_cfg_object[CCU_CONFIG] = QJsonObject();
    // 初始化AUTHORIZATION配置对象
    m_cfg_object[AUTHORIZATION] = QJsonObject();
    // 初始化CHARGING_PROFILE配置对象
    m_cfg_object[CHARGING_PROFILE] = QJsonObject();
    // 初始化CONFIG_KEY配置对象
    m_cfg_object[CONFIG_KEY] = QJsonObject();
    // 初始化CHARGING配置对象
    m_cfg_object[CHARGING] = QJsonObject();
}

bool ConfigManager::reloadConfig(setting_index_enum type, const QString &path)
{
    // 记录开始加载配置文件
    LoggerHelper::intance()->info(QString("Start loading the configuration file : %1").arg(getTypeString(type)));
    QFile file(path);
    // 打开配置文件
    if (!file.open(QIODevice::ReadOnly)) {
        // 打开失败，记录错误信息
        LoggerHelper::intance()->error("Failed to open config file : " + path);
        return false;
    }

    // 解析配置文件
    QByteArray data = file.readAll();
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(data, &error);
    // 解析失败，记录错误信息
    if (error.error != QJsonParseError::NoError) {
        LoggerHelper::intance()->error("JSON parse error:" + error.errorString());
        file.close();
        return false;
    } else {
        // 解析成功，记录成功信息
        LoggerHelper::intance()->info(QString("%1 Config file load success!").arg(getTypeString(type)));
    }

    // 将解析后的配置文件存入m_cfg_object
    m_cfg_object[type] = doc.object();
    file.close();

    return true;
}

void ConfigManager::tcuCfgFromJson()
{
    // 如果配置对象为空，则返回
    if(m_cfg_object.isEmpty()) return;
    // 如果配置对象不包含TCU_CONFIG，则返回
    if(!m_cfg_object.contains(TCU_CONFIG)) return;

    // 获取TCU_CONFIG的值
    auto tcu_cfg = m_cfg_object[TCU_CONFIG];
    // 如果TCU_CONFIG的值为空，则返回
    if (tcu_cfg.isEmpty()) return;

    // 获取TCP_SERVER的值
    QJsonObject tcp_server = tcu_cfg.value(CONFIG_KEY_TCP_SERVER).toObject();
    // 如果TCP_SERVER的值不为空，则设置TCP_SERVER的配置
    if(!tcp_server.isEmpty()) {
        m_tcu_cfg.tcp_server_cfg.address = tcp_server.value("address").toString("127.0.0.1");
        m_tcu_cfg.tcp_server_cfg.port = tcp_server.value("port").toInt(5154);
    }

    // 获取LOGIN的值
    QJsonObject login_cfg = tcu_cfg.value(CONFIG_KEY_LOGIN).toObject();
    // 如果LOGIN的值不为空，则设置LOGIN的配置
    if(!login_cfg.isEmpty()) {
        m_tcu_cfg.admin_cfg.username = login_cfg.value("username").toString("");
        m_tcu_cfg.admin_cfg.password = login_cfg.value("password").toString("");
    }

    // 设置语言、时区、TCU消息日志路径和CCU消息日志路径
    m_tcu_cfg.language = tcu_cfg.value("language").toInt(2);
    m_tcu_cfg.time_zone = tcu_cfg.value("time_zone").toInt(0);
    m_tcu_cfg.tcu_message_log_path = tcu_cfg.value("tcu_message_log_path").toString("./message.log");
    m_tcu_cfg.ccu_message_log_path = tcu_cfg.value("ccu_message_log_path").toString("");

    //
    auto charge_strect = tcu_cfg.value(CONFIG_KEY_CHARGING_STRECT).toObject();
    if (!charge_strect.isEmpty()) {
        m_tcu_cfg.charge_layout_strect.row_strect = jsonToIntList(charge_strect.value("row_strect"));
        m_tcu_cfg.charge_layout_strect.column_strect = jsonToIntList(charge_strect.value("column_strect"));
        m_tcu_cfg.charge_layout_strect.once_row_strect = jsonToIntList(charge_strect.value("once_row_strect"));
        m_tcu_cfg.charge_layout_strect.once_column_strect = jsonToIntList(charge_strect.value("once_column_strect"));
    }

    //
    auto soc_strect = tcu_cfg.value(CONFIG_KEY_SOC_STRECT).toObject();
    if (!soc_strect.isEmpty()) {
        m_tcu_cfg.soc_layout_strect.row_strect = jsonToIntList(soc_strect.value("row_strect"));
        m_tcu_cfg.soc_layout_strect.column_strect = jsonToIntList(soc_strect.value("column_strect"));
        m_tcu_cfg.soc_layout_strect.once_row_strect = jsonToIntList(soc_strect.value("once_row_strect"));
        m_tcu_cfg.soc_layout_strect.once_column_strect = jsonToIntList(soc_strect.value("once_column_strect"));
    }

    //
    auto finish_strect = tcu_cfg.value(CONFIG_KEY_FINISH_STRECT).toObject();
    if (!finish_strect.isEmpty()) {
        m_tcu_cfg.finish_layout_strect.row_strect = jsonToIntList(finish_strect.value("row_strect"));
        m_tcu_cfg.finish_layout_strect.column_strect = jsonToIntList(finish_strect.value("column_strect"));
        m_tcu_cfg.finish_layout_strect.once_row_strect = jsonToIntList(finish_strect.value("once_row_strect"));
        m_tcu_cfg.finish_layout_strect.once_column_strect = jsonToIntList(finish_strect.value("once_column_strect"));
    }

    // 将TCU配置保存到全局变量中
    GLOBALS->setValue(GLOBALS_TCU_CFG, QVariant::fromValue(m_tcu_cfg));
}

bool ConfigManager::tcuCfgToJson()
{
    return true;
}

void ConfigManager::ccuCfgFromJson()
{
    if(m_cfg_object.isEmpty()) return;
    if(!m_cfg_object.contains(CCU_CONFIG)) return;

    auto ccu_cfg = m_cfg_object[CCU_CONFIG];
    if (ccu_cfg.isEmpty()) return;

    m_ccu_cfg.CCU_SN = ccu_cfg.value("CCU_SN").toString("");
    m_ccu_cfg.TCU_ID = ccu_cfg.value("TCU_ID").toInt();
    m_ccu_cfg.GUN_numb = ccu_cfg.value("GUN_numb").toInt();
    m_ccu_cfg.GUNA_type = ccu_cfg.value("GUNA_type").toString("");
    m_ccu_cfg.GUNB_type = ccu_cfg.value("GUNB_type").toString("");
    m_ccu_cfg.GUNA_maxI = ccu_cfg.value("GUNA_maxI").toInt();
    m_ccu_cfg.GUNB_maxI = ccu_cfg.value("GUNB_maxI").toInt();

    // pcuhw config
    if (ccu_cfg.contains("pcuhw")) {
        m_ccu_cfg.pcuhw = jsonToPcuhw(ccu_cfg.value("pcuhw").toObject());
        m_ccu_cfg.pcuhw.enable_pcuhw = ccu_cfg.value("enable_pcuhw").toBool();
    }

    // pcutc config
    if (ccu_cfg.contains("pcutc")) {
        m_ccu_cfg.pcutc = jsonToPcutc(ccu_cfg.value("pcutc").toObject());
    }

    // 判断QJsonObject中是否包含ocpp,或者判断key值中有多少包含‘ocpp’字符串
    auto count = countKeysContaining(ccu_cfg, "enable_ocpp");
    m_ccu_cfg.ocpp_list.clear();
    for (auto index = 1; index <= count; index ++ ) {
        auto key = QString("enable_ocpp%1").arg(QString::number(index));
        auto ocpp_key = QString("ocpp%1").arg(QString::number(index));
        auto info = jsonToOcppInfo(ccu_cfg.value(ocpp_key).toObject());
        info.enable_ocpp = ccu_cfg.value(key).toBool();

        m_ccu_cfg.ocpp_list.append(info);
    }

    m_ccu_cfg.enable_qttcu = ccu_cfg.value("enable_qttcu").toBool();

    GLOBALS->setValue(GLOBALS_CCU_CFG, QVariant::fromValue(m_ccu_cfg));
}

PCUHW_CFG ConfigManager::jsonToPcuhw(const QJsonObject &obj)
{
    PCUHW_CFG config;
    config.connect_ip_string = obj.value("connect_ip_string").toString("");
    config.connect_port = obj.value("connect_port").toInt();
    config.enable_ssl = obj.value("enable_ssl").toBool();
    return config;
}

PCUTC_CFG ConfigManager::jsonToPcutc(const QJsonObject &obj)
{
    PCUTC_CFG config;
    config.connect_if_name = obj.value("connect_if_name").toString("");
    config.connect_ip_string = obj.value("connect_ip_string").toString("");
    config.connect_port = obj.value("connect_port").toInt();
    config.enable_ssl = obj.value("enable_ssl").toBool();
    return config;
}

ocpp_info_t ConfigManager::jsonToOcppInfo(const QJsonObject &obj)
{
    ocpp_info_t config;
    config.connect_ip_string = obj.value("connect_ip_string").toString("");
    config.connect_port = obj.value("connect_port").toInt();
    config.ssl_ca_filepath = obj.value("ssl_ca_filepath").toString("");
    config.ssl_cert_filepath = obj.value("ssl_cert_filepath").toString("");
    config.ssl_private_key_filepath = obj.value("ssl_private_key_filepath").toString("");
    config.enable_ssl = obj.value("enable_ssl").toBool();
    return config;
}

bool ConfigManager::ccuCfgToJson()
{
    // 如果CCU_CONFIG为空，则返回false
    if (m_cfg_object[CCU_CONFIG].isEmpty()) {
        return false;
    }

    // 将CCU配置信息写入m_cfg_object
    m_cfg_object[CONFIG_KEY]["CCU_SN"] = m_ccu_cfg.CCU_SN;
    m_cfg_object[CONFIG_KEY]["TCU_ID"] = m_ccu_cfg.TCU_ID;
    m_cfg_object[CONFIG_KEY]["GUN_numb"] = m_ccu_cfg.GUN_numb;
    m_cfg_object[CONFIG_KEY]["GUNA_type"] = m_ccu_cfg.GUNA_type;
    m_cfg_object[CONFIG_KEY]["GUNB_type"] = m_ccu_cfg.GUNB_type;
    m_cfg_object[CONFIG_KEY]["GUNA_maxI"] = m_ccu_cfg.GUNA_maxI;
    m_cfg_object[CONFIG_KEY]["GUNB_maxI"] = m_ccu_cfg.GUNB_maxI;

    // 将pcuhw配置信息写入m_cfg_object
    m_cfg_object[CONFIG_KEY]["pcuhw"] = pcuhwToJson(m_ccu_cfg.pcuhw);
    m_cfg_object[CONFIG_KEY]["enable_pcuhw"] = m_ccu_cfg.pcuhw.enable_pcuhw;

    // 将pcutc配置信息写入m_cfg_object
    m_cfg_object[CONFIG_KEY]["pcutc"] = pcutcToJson(m_ccu_cfg.pcutc);

    // 将ocpp配置信息写入m_cfg_object
    for (int i = 0; i < m_ccu_cfg.ocpp_list.size(); i++) {
        auto key = QString("enable_ocpp%1").arg(QString::number(i+1));
        auto ocpp_key = QString("ocpp%1").arg(QString::number(i+1));
        m_cfg_object[CONFIG_KEY][key] = m_ccu_cfg.ocpp_list[i].enable_ocpp;
        m_cfg_object[CONFIG_KEY][ocpp_key] = ocppInfoToJson(m_ccu_cfg.ocpp_list[i]);
    }

    // 将qttcu配置信息写入m_cfg_object
    m_cfg_object[CONFIG_KEY]["enable_qttcu"] = m_ccu_cfg.enable_qttcu;

    return true;
}

QJsonObject ConfigManager::pcuhwToJson(const PCUHW_CFG &config)
{
    QJsonObject obj;

    obj.insert("connect_ip_string", config.connect_ip_string);
    obj.insert("connect_port", config.connect_port);
    obj.insert("enable_ssl", config.enable_ssl);

    return obj;
}

QJsonObject ConfigManager::pcutcToJson(const PCUTC_CFG &config)
{
    QJsonObject obj;

    obj.insert("connect_if_name", config.connect_if_name);
    obj.insert("connect_ip_string", config.connect_ip_string);
    obj.insert("connect_port", config.connect_port);
    obj.insert("enable_ssl", config.enable_ssl);

    return obj;
}

QJsonObject ConfigManager::ocppInfoToJson(const ocpp_info_t &config)
{
    QJsonObject obj;

    obj.insert("connect_ip_string", config.connect_ip_string);
    obj.insert("connect_port", config.connect_port);
    obj.insert("ssl_ca_filepath", config.ssl_ca_filepath);
    obj.insert("ssl_cert_filepath", config.ssl_cert_filepath);
    obj.insert("ssl_private_key_filepath", config.ssl_private_key_filepath);
    obj.insert("enable_ssl", config.enable_ssl);

    return obj;
}

void ConfigManager::authorizationFromJson()
{
    // 如果配置对象为空，则直接返回
    if(m_cfg_object.isEmpty()) return;
    // 如果配置对象不包含AUTHORIZATION，则直接返回
    if(!m_cfg_object.contains(AUTHORIZATION)) return;

    // 获取AUTHORIZATION配置
    auto auth_cfg = m_cfg_object[AUTHORIZATION];
    // 如果AUTHORIZATION配置为空，则直接返回
    if (auth_cfg.isEmpty()) return;

    // local authorization list
    auto local_auth = auth_cfg.value(CONFIG_KEY_LOCAL_AUTH_LIST);
    if (local_auth.isArray()) {
        fromValue(m_auth_list.localAuthorizationList, local_auth.toArray());
    }

    auto auth_cache = auth_cfg.value(CONFIG_KEY_AUTH_CACHE);
    if (auth_cache.isArray()) {
        fromValue(m_auth_list.authorizationCache, auth_cache.toArray());
    }

    GLOBALS->setValue(GLOBALS_AUTH_LIST, QVariant::fromValue(m_auth_list));
}

// 从QJsonArray中获取AUTH_CARD_INFO列表
void ConfigManager::fromValue(QList<AUTH_CARD_INFO> &auth_card_list, const QJsonArray &jsonArray)
{
    // 遍历QJsonArray中的每个元素
    foreach (const QJsonValue &auth_info, jsonArray){
        // 如果元素是对象
        if (auth_info.isObject()) {
            // 获取对象
            auto object = auth_info.toObject();
            // 如果对象不为空
            if (!object.isEmpty()) {
                // 创建AUTH_CARD_INFO对象
                AUTH_CARD_INFO info;
                // 获取idTag并赋值
                info.idTag = object.value("idTag").toString("");
                // 获取expiryDate并赋值
                info.expiryDate = object.value("expiryDate").toString("");
                // 获取parentIdTag并赋值
                info.parentIdTag = object.value("parentIdTag").toString("");
                // 获取status并赋值
                info.status = object.value("status").toString("");

                // 将AUTH_CARD_INFO对象添加到列表中
                auth_card_list.append(info);
            }
        }
    }
}

bool ConfigManager::authorizationToJson()
{
    return true;
}

void ConfigManager::configKeyFromJson()
{
    // 如果配置对象为空，则返回
    if(m_cfg_object.isEmpty()) return;
    // 如果配置对象不包含配置键，则返回
    if(!m_cfg_object.contains(CONFIG_KEY)) return;

    // 获取配置键对象
    auto cfg_key_obj = m_cfg_object[CONFIG_KEY];
    // 如果配置键对象为空，则返回
    if (cfg_key_obj.isEmpty()) return;

    // 解析 CoreProfile
    if (cfg_key_obj.contains("CoreProfile")) {
        // 将 JSON 对象转换为 CoreProfile 对象
        m_cfg_key.CoreProfile = jsonToCoreProfile(cfg_key_obj.value("CoreProfile").toObject());
    }

    // 解析 LocalAuthList
    if (cfg_key_obj.contains("LocalAuthListManagementProfile")) {
        // 将 JSON 对象转换为 LocalAuthList 对象
        m_cfg_key.LocalAuthListManagementProfile = jsonToLocalAuthList(cfg_key_obj.value("LocalAuthListManagementProfile").toObject());
    }

    // 解析 ReservationProfile
    if (cfg_key_obj.contains("ReservationProfile")) {
        // 将 JSON 对象转换为 ReservationProfile 对象
        m_cfg_key.ReservationProfile = jsonToReservationProfile(cfg_key_obj.value("ReservationProfile").toObject());
    }

    // 解析 SmartChargingProfile
    if (cfg_key_obj.contains("SmartChargingProfile")) {
        // 将 JSON 对象转换为 SmartChargingProfile 对象
        m_cfg_key.SmartChargingProfile = jsonToSmartChargingProfile(cfg_key_obj.value("SmartChargingProfile").toObject());
    }

    // 将配置键对象保存到全局变量中
    GLOBALS->setValue(GLOBALS_CFG_KEY, QVariant::fromValue(m_cfg_key));
}

// 将QJsonObject转换为CORE_PROFILE
CORE_PROFILE ConfigManager::jsonToCoreProfile(const QJsonObject &obj)
{
    // 创建一个CORE_PROFILE对象
    CORE_PROFILE config;

    // 将QJsonObject中的值转换为CORE_PROFILE对象的属性
    config.AllowOfflineTxForUnknownId = obj["AllowOfflineTxForUnknownId"].toBool();
    config.AuthorizationCacheEnabled = obj["AuthorizationCacheEnabled"].toBool();
    config.AuthorizeRemoteTxRequests = obj["AuthorizeRemoteTxRequests"].toBool();
    config.BlinkRepeat = obj["BlinkRepeat"].toInt();
    config.ClockAlignedDataInterval = obj["ClockAlignedDataInterval"].toInt();
    config.ConnectionTimeOut = obj["ConnectionTimeOut"].toInt();
    config.ConnectorPhaseRotation = jsonToStringList(obj["ConnectorPhaseRotation"]);
    config.ConnectorPhaseRotationMaxLength = obj["ConnectorPhaseRotationMaxLength"].toInt();
    config.GetConfigurationMaxKeys = obj["GetConfigurationMaxKeys"].toInt();
    config.HeartbeatInterval = obj["HeartbeatInterval"].toInt();
    config.LightIntensity = obj["LightIntensity"].toInt();
    config.LocalAuthorizeOffline = obj["LocalAuthorizeOffline"].toBool();
    config.LocalPreAuthorize = obj["LocalPreAuthorize"].toBool();
    config.MaxEnergyOnInvalidId = obj["MaxEnergyOnInvalidId"].toInt();
    config.MeterValuesAlignedDataMaxLength = obj["MeterValuesAlignedDataMaxLength"].toInt();
    config.MeterValuesSampledDataMaxLength = obj["MeterValuesSampledDataMaxLength"].toInt();
    config.MeterValueSampleInterval = obj["MeterValueSampleInterval"].toInt();
    config.MinimumStatusDuration = obj["MinimumStatusDuration"].toInt();
    config.NumberOfConnectors = obj["NumberOfConnectors"].toInt();
    config.ResetRetries = obj["ResetRetries"].toInt();
    config.StopTransactionOnEVSideDisconnect = obj["StopTransactionOnEVSideDisconnect"].toBool();
    config.StopTransactionOnInvalidId = obj["StopTransactionOnInvalidId"].toBool();
    config.StopTxnAlignedDataMaxLength = obj["StopTxnAlignedDataMaxLength"].toInt();
    config.StopTxnSampledDataMaxLength = obj["StopTxnSampledDataMaxLength"].toInt();
    config.SupportedFeatureProfiles = jsonToStringList(obj["SupportedFeatureProfiles"]);
    config.SupportedFeatureProfilesMaxLength = obj["SupportedFeatureProfilesMaxLength"].toInt();
    config.TransactionMessageAttempts = obj["TransactionMessageAttempts"].toInt();
    config.TransactionMessageRetryInterval = obj["TransactionMessageRetryInterval"].toInt();
    config.UnlockConnectorOnEVSideDisconnect = obj["UnlockConnectorOnEVSideDisconnect"].toBool();
    config.WebSocketPingInterval = obj["WebSocketPingInterval"].toInt();
    config.AuthorizationKey = obj["AuthorizationKey"].toString("");
    config.AuthorizationCacheMaxLength = obj["AuthorizationCacheMaxLength"].toInt();

    // 返回转换后的CORE_PROFILE对象
    return config;
}

// 将JSON对象转换为本地认证列表
AUTH_LIST_MANAGE ConfigManager::jsonToLocalAuthList(const QJsonObject &obj)
{
    // 定义一个AUTH_LIST_MANAGE类型的变量config
    AUTH_LIST_MANAGE config;

    // 将JSON对象中的LocalAuthListEnabled字段转换为布尔类型，并赋值给config的LocalAuthListEnabled成员变量
    config.LocalAuthListEnabled = obj["LocalAuthListEnabled"].toBool();
    // 将JSON对象中的LocalAuthListMaxLength字段转换为整型，并赋值给config的LocalAuthListMaxLength成员变量
    config.LocalAuthListMaxLength = obj["LocalAuthListMaxLength"].toInt();
    // 将JSON对象中的SendLocalListMaxLength字段转换为整型，并赋值给config的SendLocalListMaxLength成员变量
    config.SendLocalListMaxLength = obj["SendLocalListMaxLength"].toInt();

    // 返回config变量
    return config;
}

// 将QJsonObject转换为RESE_PROFILE
RESE_PROFILE ConfigManager::jsonToReservationProfile(const QJsonObject &obj)
{
    // 创建一个RESE_PROFILE对象
    RESE_PROFILE config;

    // 将QJsonObject中的ReserveConnectorZeroSupported属性转换为bool类型，并赋值给RESE_PROFILE对象的ReserveConnectorZeroSupported属性
    config.ReserveConnectorZeroSupported = obj["ReserveConnectorZeroSupported"].toBool();

    // 返回RESE_PROFILE对象
    return config;
}

// 将JSON对象转换为SMART_CHARGE配置
SMART_CHARGE ConfigManager::jsonToSmartChargingProfile(const QJsonObject &obj)
{
    SMART_CHARGE config;

    // 从JSON对象中获取ChargeProfileMaxStackLevel并转换为整数
    config.ChargeProfileMaxStackLevel = obj["ChargeProfileMaxStackLevel"].toInt();
    // 从JSON对象中获取ChargingScheduleAllowedChargingRateUnit并转换为字符串列表
    config.ChargingScheduleAllowedChargingRateUnit = jsonToStringList(obj["ChargingScheduleAllowedChargingRateUnit"]);
    // 从JSON对象中获取ChargingScheduleMaxPeriods并转换为整数
    config.ChargingScheduleMaxPeriods = obj["ChargingScheduleMaxPeriods"].toInt();
    // 从JSON对象中获取ConnectorSwitch3to1PhaseSupported并转换为布尔值
    config.ConnectorSwitch3to1PhaseSupported = obj["ConnectorSwitch3to1PhaseSupported"].toBool();
    // 从JSON对象中获取MaxChargingProfilesInstalled并转换为整数
    config.MaxChargingProfilesInstalled = obj["MaxChargingProfilesInstalled"].toInt();

    return config;
}

bool ConfigManager::configKeyToJson()
{
    // 判断配置对象是否为空
    if (m_cfg_object[CONFIG_KEY].isEmpty()) {
        return false;
    }

    // 将核心配置转换为JSON格式
    m_cfg_object[CONFIG_KEY]["CoreProfile"] = coreProfileToJson(m_cfg_key.CoreProfile);
    // 将本地认证列表管理配置转换为JSON格式
    m_cfg_object[CONFIG_KEY]["LocalAuthListManagementProfile"] = localAuthListToJson(m_cfg_key.LocalAuthListManagementProfile);
    // 将预约配置转换为JSON格式
    m_cfg_object[CONFIG_KEY]["ReservationProfile"] = reservationProfileToJson(m_cfg_key.ReservationProfile);
    // 将智能充电配置转换为JSON格式
    m_cfg_object[CONFIG_KEY]["SmartChargingProfile"] = smartChargingProfileToJson(m_cfg_key.SmartChargingProfile);

    return true;
}

QJsonObject ConfigManager::coreProfileToJson(const CORE_PROFILE &config)
{
    // 将CORE_PROFILE类型的config转换为QJsonObject类型
    QJsonObject obj;

    obj.insert("AllowOfflineTxForUnknownId", config.AllowOfflineTxForUnknownId);
    obj.insert("AuthorizationCacheEnabled", config.AuthorizationCacheEnabled);
    obj.insert("AuthorizeRemoteTxRequests", config.AuthorizeRemoteTxRequests);
    obj.insert("BlinkRepeat", config.BlinkRepeat);
    obj.insert("ClockAlignedDataInterval", config.ClockAlignedDataInterval);
    obj.insert("ConnectionTimeOut", config.ConnectionTimeOut);
    obj.insert("ConnectorPhaseRotation", stringListToJson(config.ConnectorPhaseRotation));
    obj.insert("ConnectorPhaseRotationMaxLength", config.ConnectorPhaseRotationMaxLength);
    obj.insert("GetConfigurationMaxKeys", config.GetConfigurationMaxKeys);
    obj.insert("HeartbeatInterval", config.HeartbeatInterval);
    obj.insert("LightIntensity", config.LightIntensity);
    obj.insert("LocalAuthorizeOffline", config.LocalAuthorizeOffline);
    obj.insert("LocalPreAuthorize", config.LocalPreAuthorize);
    obj.insert("MaxEnergyOnInvalidId", config.MaxEnergyOnInvalidId);
    obj.insert("MeterValuesAlignedDataMaxLength", config.MeterValuesAlignedDataMaxLength);
    obj.insert("MeterValuesSampledDataMaxLength", config.MeterValuesSampledDataMaxLength);
    obj.insert("MeterValueSampleInterval", config.MeterValueSampleInterval);
    obj.insert("MinimumStatusDuration", config.MinimumStatusDuration);
    obj.insert("NumberOfConnectors", config.NumberOfConnectors);
    obj.insert("ResetRetries", config.ResetRetries);
    obj.insert("StopTransactionOnEVSideDisconnect", config.StopTransactionOnEVSideDisconnect);
    obj.insert("StopTransactionOnInvalidId", config.StopTransactionOnInvalidId);
    obj.insert("StopTxnAlignedDataMaxLength", config.StopTxnAlignedDataMaxLength);
    obj.insert("StopTxnSampledDataMaxLength", config.StopTxnSampledDataMaxLength);
    obj.insert("SupportedFeatureProfiles", stringListToJson(config.SupportedFeatureProfiles));
    obj.insert("SupportedFeatureProfilesMaxLength", config.SupportedFeatureProfilesMaxLength);
    obj.insert("TransactionMessageAttempts", config.TransactionMessageAttempts);
    obj.insert("TransactionMessageRetryInterval", config.TransactionMessageRetryInterval);
    obj.insert("UnlockConnectorOnEVSideDisconnect", config.UnlockConnectorOnEVSideDisconnect);
    obj.insert("WebSocketPingInterval", config.WebSocketPingInterval);
    obj.insert("AuthorizationKey", config.AuthorizationKey);
    obj.insert("AuthorizationCacheMaxLength", config.AuthorizationCacheMaxLength);

    return obj;
}

QJsonObject ConfigManager::localAuthListToJson(const AUTH_LIST_MANAGE &config)
{
    QJsonObject obj;
    obj.insert("LocalAuthListEnabled", config.LocalAuthListEnabled);
    obj.insert("LocalAuthListMaxLength", config.LocalAuthListMaxLength);
    obj.insert("SendLocalListMaxLength", config.SendLocalListMaxLength);
    return obj;
}

QJsonObject ConfigManager::reservationProfileToJson(const RESE_PROFILE &config)
{
    QJsonObject obj;
    obj.insert("ReserveConnectorZeroSupported", config.ReserveConnectorZeroSupported);
    return obj;
}

QJsonObject ConfigManager::smartChargingProfileToJson(const SMART_CHARGE &config)
{
    QJsonObject obj;
    obj.insert("ChargeProfileMaxStackLevel", config.ChargeProfileMaxStackLevel);
    obj.insert("ChargingScheduleAllowedChargingRateUnit", stringListToJson(config.ChargingScheduleAllowedChargingRateUnit));
    obj.insert("ChargingScheduleMaxPeriods", config.ChargingScheduleMaxPeriods);
    obj.insert("ConnectorSwitch3to1PhaseSupported", config.ConnectorSwitch3to1PhaseSupported);
    obj.insert("MaxChargingProfilesInstalled", config.MaxChargingProfilesInstalled);
    return obj;
}

void ConfigManager::chargingCfgFromJson()
{
    // 如果配置对象为空，则返回
    if(m_cfg_object.isEmpty()) return;
    // 如果配置对象不包含配置键，则返回
    if(!m_cfg_object.contains(CHARGING_PROFILE)) return;

    // 获取配置键对象
    auto charging_profiles = m_cfg_object[CHARGING_PROFILE];
    // 如果配置键对象为空，则返回
    if (charging_profiles.isEmpty()) return;

    m_charging_profiles.count = charging_profiles["count"].toInt();
    m_charging_profiles.maxLength = charging_profiles["maxLength"].toInt();

    if (charging_profiles["ChargingProfiles"].isArray()) {
        m_charging_profiles.chargingProfiles = jsonToChargingProfileDetail(charging_profiles["ChargingProfiles"].toArray());
    }

    // 将配置键对象保存到全局变量中
    GLOBALS->setValue(GLOBALS_CHARGING_PROFILES, QVariant::fromValue(m_charging_profiles));
}

QList<charging_profiles_detail_info_t> ConfigManager::jsonToChargingProfileDetail(const QJsonArray &array)
{
    QList<charging_profiles_detail_info_t> config;

    if (array.isEmpty()) return config;
    foreach (const auto value, array) {
        charging_profiles_detail_info_t info;
        
        if (value.isObject()) {
            info.chargingProfileId = value.toObject().value("chargingProfileId").toInt();
            info.stackLevel = value.toObject().value("stackLevel").toInt();
            info.validFrom = value.toObject().value("validFrom").toString();
            info.validTo = value.toObject().value("validTo").toString();

            info.chargingProfileKind = value.toObject().value("chargingProfileKind").toString();
            info.recurrencyKind = value.toObject().value("recurrencyKind").toString();
            
            info.connector_id = value.toObject().value("connector_id").toInt();
            info.chargingRateUnitType = value.toObject().value("chargingRateUnitType").toString();
            info.minChargingRate = value.toObject().value("minChargingRate").toInt();
            info.limitChargingRate = value.toObject().value("limitChargingRate").toInt();
            
            info.startSchedule = value.toObject().value("startSchedule").toString();
            info.startPeriod = value.toObject().value("startPeriod").toString();
            info.duration = value.toObject().value("duration").toInt();

            config.append(info);
        }
    }

    return config;
}

bool ConfigManager::chargingCfgToJson()
{
    if(m_cfg_object.isEmpty()) return false;
    if(!m_cfg_object.contains(CHARGING_PROFILE)) return false;

    auto charging_profiles = m_cfg_object[CHARGING_PROFILE];
    charging_profiles["count"] = m_charging_profiles.count;
    charging_profiles["maxLength"] = m_charging_profiles.maxLength;
    charging_profiles["ChargingProfiles"] = chargingProfileDetailToJson(m_charging_profiles.chargingProfiles);

    return true;
}

QJsonArray ConfigManager::chargingProfileDetailToJson(const QList<charging_profiles_detail_info_t> &config)
{
    if (config.isEmpty()) return QJsonArray();

    QJsonArray array;
    for (const auto &info : config) {
        QJsonObject obj;
        obj.insert("chargingProfileId", info.chargingProfileId);
        obj.insert("stackLevel", info.stackLevel);
        obj.insert("validFrom", info.validFrom);
        obj.insert("validTo", info.validTo);

        obj.insert("chargingProfileKind", info.chargingProfileKind);
        obj.insert("recurrencyKind", info.recurrencyKind);

        obj.insert("connector_id", info.connector_id);
        obj.insert("chargingRateUnitType", info.chargingRateUnitType);
        obj.insert("minChargingRate", info.minChargingRate);
        obj.insert("limitChargingRate", info.limitChargingRate);

        obj.insert("startSchedule", info.startSchedule);
        obj.insert("startPeriod", info.startPeriod);
        obj.insert("duration", info.duration);

        array.append(obj);
    }

    return array;
}

void ConfigManager::chargingRecordsFromJson()
{
    // 如果配置对象为空，则返回
    if(m_cfg_object.isEmpty()) return;
    // 如果配置对象不包含配置键，则返回
    if(!m_cfg_object.contains(CHARGING)) return;

    // 获取配置键对象
    auto charging_records = m_cfg_object[CHARGING];
    // 如果配置键对象为空，则返回
    if (charging_records.isEmpty()) return;


    m_charging_records.count = charging_records.value("count").toInt();
    m_charging_records.maxLength = charging_records.value("maxLength").toInt();
    m_charging_records.maxCacheDays = charging_records.value("maxCacheDays").toInt();

    if (charging_records["ChargingRecords"].isArray()) {
        m_charging_records.records = jsonToChargingRecord(charging_records["ChargingRecords"].toArray());
    }

    // 将配置键对象保存到全局变量中
    GLOBALS->setValue(GLOBALS_OFFLINE_CHARGING_RECORDS, QVariant::fromValue(m_charging_records));
}

QList<CHARGING_RECORD_INFO> ConfigManager::jsonToChargingRecord(const QJsonArray &array)
{
    QList<CHARGING_RECORD_INFO> config;
    if (array.isEmpty()) return config;
    foreach (const auto value, array) {
        CHARGING_RECORD_INFO info;
        if (value.isObject()) {
            info.connector_id = value.toObject().value("connector_id").toInt();
            info.transactionId = value.toObject().value("transactionId").toInt();
            info.start_Datetime = value.toObject().value("start_Datetime").toString();
            info.end_Datetime = value.toObject().value("end_Datetime").toString();
            info.start_MeterKWh = value.toObject().value("start_MeterKWh").toInt();
            info.end_MeterKWh = value.toObject().value("end_MeterKWh").toInt();
            
            config.append(info);
        }
    }

    return config;
}

bool ConfigManager::chargingRecordsToJson()
{
    if(m_cfg_object.isEmpty()) return false;
    if(!m_cfg_object.contains(CHARGING)) return false;

    m_cfg_object[CHARGING]["count"] = m_charging_records.count;
    m_cfg_object[CHARGING]["maxLength"] = m_charging_records.maxLength;
    m_cfg_object[CHARGING]["maxCacheDays"] = m_charging_records.maxCacheDays;
    m_cfg_object[CHARGING]["ChargingRecords"] = chargingRecordsDetailToJson(m_charging_records.records);

    return true;
}

QJsonArray ConfigManager::chargingRecordsDetailToJson(const QList<CHARGING_RECORD_INFO> &config)
{
    if (config.isEmpty()) return QJsonArray();

    QJsonArray array;
    for (const auto &info : config) {
        QJsonObject obj;
        obj.insert("connector_id", info.connector_id);
        obj.insert("transactionId", info.transactionId);
        obj.insert("start_Datetime", info.start_Datetime);
        obj.insert("end_Datetime", info.end_Datetime);
        obj.insert("start_MeterKWh", info.start_MeterKWh);
        obj.insert("end_MeterKWh", info.end_MeterKWh);

        array.append(obj);
    }

    return array;
}

QStringList ConfigManager::jsonToStringList(const QJsonValue &value)
{
    QStringList stringList;
    if (value.isArray()) {
        QJsonArray array = value.toArray();
        foreach (const QJsonValue& value, array) {
            stringList.append(value.toString(""));
        }
    }
    return stringList;
}

QJsonValue ConfigManager::stringListToJson(const QStringList &inputStringList)
{
    return QJsonArray::fromStringList(inputStringList);
}

QList<int> ConfigManager::jsonToIntList(const QJsonValue &value)
{
    QList<int> result;
    if (value.isArray()) {
        QJsonArray array = value.toArray();
        foreach (const QJsonValue& value, array) {
            result.append(value.toInt(0));
        }
    }

    return result;
}

QJsonValue ConfigManager::intListToJson(const QList<int> &intList)
{
    QJsonArray array;
    for (auto strect : intList) {
        array.append(strect);
    }

    return array;
}

QString ConfigManager::getTypeString(setting_index_enum type)
{
    switch (type) {
    case TCU_CONFIG: return TO_STRING(TCU_CONFIG);
    case CCU_CONFIG: return TO_STRING(CCU_CONFIG);
    case AUTHORIZATION: return TO_STRING(AUTHORIZATION);
    case CHARGING_PROFILE: return TO_STRING(CHARGING_PROFILE);
    case CONFIG_KEY: return TO_STRING(CONFIG_KEY);
    case CHARGING: return TO_STRING(CHARGING);
    default:
        break;
    }

    return QString();
}

int ConfigManager::countKeysContaining(const QJsonObject &obj, const QString &target, Qt::CaseSensitivity cs)
{
    int count = 0;
    auto keys = obj.keys();
    foreach (const QString &key, keys){
        if (key.contains(target, cs)) {
            count++;
        }
    }
    return count;
}

void ConfigManager::slotTcuConfigFileChanged(const QString &path)
{
    reloadConfig(TCU_CONFIG, path);

    // 重新添加监视（文件修改时可能临时被移除监视列表）
    if (!m_tcu_cfg_watcher->files().contains(path)) {
        m_tcu_cfg_watcher->addPath(path);
    }
}

ccu_config_info_t ConfigManager::ccu_cfg() const
{
    return m_ccu_cfg;
}

tcu_config_info_t ConfigManager::tcu_cfg() const
{
    return m_tcu_cfg;
}
