#include "ConfigDialog.hpp"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFormLayout>
#include <QJsonDocument>

ConfigDialog::ConfigDialog(QWidget* parent)
    : QDialog(parent)
{
    setWindowTitle(tr("PLC Configuration"));

    // 创建输入控件
    ipEdit_ = new QLineEdit("192.168.0.1", this);
    rackEdit_ = new QLineEdit("0", this);
    slotEdit_ = new QLineEdit("1", this);
    dbConfigEdit_ = new QLineEdit("1", this);
    dbCommandEdit_ = new QLineEdit("2", this);
    dbStatusEdit_ = new QLineEdit("3", this);
    dbPointsEdit_ = new QLineEdit("4", this);

    // 创建按钮
    okButton_ = new QPushButton(tr("OK"), this);
    cancelButton_ = new QPushButton(tr("Cancel"), this);

    // 创建布局
    auto mainLayout = new QVBoxLayout(this);
    auto formLayout = new QFormLayout;
    auto buttonLayout = new QHBoxLayout;

    // 添加输入控件到表单布局
    formLayout->addRow(tr("IP Address:"), ipEdit_);
    formLayout->addRow(tr("Rack:"), rackEdit_);
    formLayout->addRow(tr("Slot:"), slotEdit_);
    formLayout->addRow(tr("Config DB:"), dbConfigEdit_);
    formLayout->addRow(tr("Command DB:"), dbCommandEdit_);
    formLayout->addRow(tr("Status DB:"), dbStatusEdit_);
    formLayout->addRow(tr("Points DB:"), dbPointsEdit_);

    // 添加按钮到按钮布局
    buttonLayout->addWidget(okButton_);
    buttonLayout->addWidget(cancelButton_);

    // 组合布局
    mainLayout->addLayout(formLayout);
    mainLayout->addLayout(buttonLayout);

    // 连接信号
    connect(okButton_, &QPushButton::clicked, this, &ConfigDialog::onOKClicked);
    connect(cancelButton_, &QPushButton::clicked, this, &ConfigDialog::onCancelClicked);
}

void ConfigDialog::onOKClicked()
{
    emit configFinished(generateConfig());
    accept();
}

void ConfigDialog::onCancelClicked()
{
    reject();
}

QString ConfigDialog::generateConfig()
{
    QJsonObject config;
    config["ip"] = ipEdit_->text();
    config["rack"] = rackEdit_->text().toInt();
    config["slot"] = slotEdit_->text().toInt();
    config["db_config"] = dbConfigEdit_->text().toInt();
    config["db_command"] = dbCommandEdit_->text().toInt();
    config["db_status"] = dbStatusEdit_->text().toInt();
    config["db_points"] = dbPointsEdit_->text().toInt();

    QJsonDocument doc(config);
    return doc.toJson(QJsonDocument::Compact);
} 