// #define WIN32_LEAN_AND_MEAN
#include <winsock2.h>  // 必须在所有网络相关头文件之前
#include <windows.h>

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickWindow>
#include "qmltool.h"
#include "sshmanager.h"
#include "FileTransfer.h"
#include "jsonhighlighter.h"
#include "HuskarUI/husapp.h"

void runPowerShellCommandAsAdmin(const QString& command) {
    QString powershellCommand = QString("powershell -Command \"%1\"").arg(command);
    SHELLEXECUTEINFOW sei = { sizeof(sei) };
    sei.lpVerb = L"runas";
    sei.lpFile = L"powershell.exe";
    sei.lpParameters = reinterpret_cast<LPCWSTR>(powershellCommand.utf16());
    sei.nShow = SW_SHOWNORMAL;

    if (!ShellExecuteExW(&sei)) {
        // DWORD error = GetLastError();
        // QMessageBox::critical(nullptr, "Error", QString("Failed to execute command as administrator. Error code: %1").arg(error));
    }
}

int main(int argc, char *argv[])
{
    // QString command = "netsh interface tcp set global timestamps=enabled";
    // runPowerShellCommandAsAdmin(command);
    // AllocConsole();
    // SetConsoleOutputCP(65001);
    // freopen(("CONOUT$"), ("w"), stdout);
    // freopen(("CONOUT$"), ("w"), stderr);
    // freopen(("CONIN$"), ("r"), stdin);
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
    QQuickWindow::setGraphicsApi(QSGRendererInterface::OpenGL);
#else
    QQuickWindow::setSceneGraphBackend(QSGRendererInterface::OpenGL);
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
#endif
    QQuickWindow::setDefaultAlphaBuffer(true);

    QGuiApplication app(argc, argv);
    // 设置组织信息
    app.setOrganizationName("Yosin");    // 替换为你的组织名称
    app.setOrganizationDomain("dps-doc.senzo.online");    // 替换为你的组织域名
    app.setApplicationName("DPS后台管理工具");  // 替换为你的应用程序名称

    // 注册 C++ 类到 QML
    qmlRegisterType<JsonHighlighter>("JsonEditor", 1, 0, "JsonHighlighter");
    qmlRegisterType<JsonProcessor>("JsonEditor", 1, 0, "JsonProcessor");
    qmlRegisterSingletonInstance<SSHManager>("SSHManager", 1, 0, "SSHManager",SSHManager::instance());
    qmlRegisterSingletonInstance("QmlTool", 1, 0, "QmlTool", QmlTool::getInstance());
    qmlRegisterSingletonInstance("FileTransfer", 1, 0, "FileTransfer", FileTransfer::instance());

    QQmlApplicationEngine engine;
    HusApp::initialize(&engine);
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(
        &engine,
        &QQmlApplicationEngine::objectCreated,
        &app,
        [url](QObject *obj, const QUrl &objUrl) {
            if (!obj && url == objUrl)
                QCoreApplication::exit(-1);
        },
        Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}
