#include "global.h"

#include <QSettings>

#include "logger.h"

QUrl apiBackendUrl;  // 定义并初始化全局变量
QString labLat("未知");
QString labLon("未知");
QString globalAuthority;
QString firewidgetPort;  // 4 for dev; 1: 爆破装置
QString gpsPort;
QString databaseHost;
QString mqttClientId;
QString MQTT_TOPIC_COMPANY_PROJECTS_SUB;      // 接受爆破器的topic
QString MQTT_TOPIC_COMPANY_PROJECTS_PUBLISH;  // 发布工程的topic
QString COMPANY_CODE;
QString DET_PARAM_XMBH;
QString DET_PARAM_DWDM;
QString DET_PARAM_HTID;
QString DET_PARAM_SBBH;
bool isShowTriggeringWidget;

void loadConfig() {
    QSettings settings("config.ini", QSettings::IniFormat);

    // Remove local variable declarations and assign directly to global variables
    apiBackendUrl = QUrl(settings.value("api_backend_url", "http://192.168.0.241:8000/api/v1/").toString());
    firewidgetPort = settings.value("Ports/firewidget_port", "COM1").toString();
    gpsPort = settings.value("Ports/gps_port", "COM3").toString();
    databaseHost = settings.value("Database/host", "127.0.0.1").toString();
    mqttClientId = settings.value("MQTT/client_id", "mqttclient_PC").toString();
    MQTT_TOPIC_COMPANY_PROJECTS_SUB = settings.value("MQTT/topic", "hxgc/companycode/pro/P").toString();
    MQTT_TOPIC_COMPANY_PROJECTS_PUBLISH = settings.value("MQTT/publish_topic", "hxgc/companycode/pro/B").toString();
    COMPANY_CODE = settings.value("Company/code", "cc_hxgc").toString();
    isShowTriggeringWidget = settings.value("UI/show_triggering_widget", false).toBool();

    // Load det parameters
    DET_PARAM_XMBH = settings.value("DetParams/xmbh", "").toString();
    DET_PARAM_DWDM = settings.value("DetParams/dwdm", "").toString();
    DET_PARAM_HTID = settings.value("DetParams/htid", "").toString();
    DET_PARAM_SBBH = settings.value("DetParams/sbbh", "").toString();

    qDebug() << "Loaded configuration:" << "detparams" << DET_PARAM_XMBH << DET_PARAM_DWDM << DET_PARAM_HTID
             << DET_PARAM_SBBH;
}

QMutex globalMutex;                    // 全局操作锁
MqttClient* mainMqttClient = nullptr;  // 定义全局 MQTT 客户端