#include "detdialog.h"
#include "ui_detdialog.h"

DetDialog::DetDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DetDialog)
{
    ui->setupUi(this);

    ui->comboType->addItem("盒条码", "case");
    ui->comboType->addItem("箱条码", "box");
    ui->comboType->setCurrentIndex(-1);
    ui->labFeature->clear();
    ui->lineFeature->hide();

    // 连接信号和槽
    connect(ui->comboType, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &DetDialog::onComboTypeIndexChanged);
    connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &DetDialog::validateInput);
    connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &DetDialog::clearFormData);
}


void DetDialog::onComboTypeIndexChanged(int index)
{
    if (index != -1) {
        ui->lineFeature->show();
        QString value = ui->comboType->itemData(index).toString();
        if (value == "case") {
            ui->labFeature->setText("装盒标准");
        } else if (value == "box") {
            ui->labFeature->setText("特征码");
        }
    } else {
        ui->labFeature->clear();
        ui->lineFeature->hide();
    }
}


void DetDialog::validateInput()
{
    QString codeType = ui->comboType->currentData().toString();
    QString beginCode = ui->lineCode->text().trimmed();
    QString featureorCaseCount = ui->lineFeature->text().trimmed();
    QString count = ui->lineCount->text().trimmed();


    if (codeType.isEmpty() || beginCode.isEmpty() || count.isEmpty()) {

        QMessageBox::warning(this, "输入错误", "请填写所有必填字段。");
        return;
    }

    QJsonObject jsonObject;
    jsonObject["codeType"] = codeType;
    jsonObject["beginCode"] = beginCode;

    if (codeType == "case") {
        jsonObject["inCaseCount"] = featureorCaseCount;
    } else if (codeType == "box") {
        jsonObject["feature"] = featureorCaseCount;
    }
    jsonObject["count"] = count;


    QJsonDocument jsonDoc(jsonObject);
    qDebug() << jsonDoc;


    emit validateDetNum(jsonDoc);
    clearFormData(); // 清除表单数据
    // this->accept();
}

void DetDialog::clearFormData()
{

    QList<QLineEdit*> lineEdits = findChildren<QLineEdit*>();
    for (QLineEdit* lineEdit : lineEdits) {
        lineEdit->clear();
    }


    QList<QComboBox*> comboBoxes = findChildren<QComboBox*>();
    for (QComboBox* comboBox : comboBoxes) {
        comboBox->setCurrentIndex(-1);
    }

}
DetDialog::~DetDialog()
{
    delete ui;
}
