#include "projectdialog.h"

#include "ui_projectdialog.h"

ProjectDialog::ProjectDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ProjectDialog) {
    ui->setupUi(this);
    connect(ui->buttonBox, &QDialogButtonBox::accepted, this,
            &ProjectDialog::validateAndSaveProject);
    connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &ProjectDialog::clearFormData);
}

void ProjectDialog::SetComboBoxBlast(const QJsonArray &bapoYuanArray) {
    blasterArray = bapoYuanArray;
    ui->comboBoxBlast->clear();
    fillComboBox(ui->comboBoxBlast, bapoYuanArray);
    ui->comboBoxBlast->setCurrentIndex(-1);
}

void ProjectDialog::SetComboBoxOperator(const QJsonArray &anQuanYuanArray) {
    operatorArray = anQuanYuanArray;
    ui->comboBoxOperator->clear();
    fillComboBox(ui->comboBoxOperator, anQuanYuanArray);
    ui->comboBoxOperator->setCurrentIndex(-1);
}

void ProjectDialog::on_comboBoxOperator_currentIndexChanged(int index) {
    if (index >= 0 && index < operatorArray.size()) {
        operatorId = operatorArray[index].toObject()["identity"].toString();
    }
}

void ProjectDialog::on_comboBoxBlast_currentIndexChanged(int index) {
    if (index >= 0 && index < blasterArray.size()) {
        blasterId = blasterArray[index].toObject()["identity"].toString();
    }
}

void ProjectDialog::fillComboBox(QComboBox *comboBox, const QJsonArray &jsonArray) {
    for (const QJsonValue &value : jsonArray) {
        if (value.isObject()) {
            QJsonObject obj = value.toObject();
            if (obj.contains("nickName")) {
                QString name = obj["nickName"].toString();
                comboBox->addItem(name);
            }
        }
    }
}

void ProjectDialog::SetL1AddressOptions(const QJsonArray &Options) {
    parentOptions = Options;
    ui->comboBoxAddr->clear();

    for (const QJsonValue &option : Options) {
        ui->comboBoxAddr->addItem(option.toObject()["name"].toString(),
                                  option.toObject()["uuid"].toString());
    }
    ui->comboBoxAddr->setCurrentIndex(-1);
}

void ProjectDialog::updateL2AddressOptions() {
    ui->comboBoxAddr_2->clear();
    for (const QJsonValue &child : L2AddressOptions) {
        ui->comboBoxAddr_2->addItem(child.toObject()["name"].toString(),
                                    child.toObject()["uuid"].toString());
    }
    ui->comboBoxAddr_2->setCurrentIndex(-1);
}

void ProjectDialog::updateL3AddressOptions() {
    ui->comboBoxAddr_3->clear();
    for (const QJsonValue &child : L3AddressOptions) {
        ui->comboBoxAddr_3->addItem(child.toObject()["name"].toString(),
                                    child.toObject()["uuid"].toString());
    }
    ui->comboBoxAddr_3->setCurrentIndex(-1);
}

void ProjectDialog::setChildOptions(const QJsonArray &newDataOptions) {
    dataOptions = newDataOptions;
}

void ProjectDialog::SetComboBoxLora(const QString &grandChildName) {
    ui->comboBoxLora->clear();
    for (const QJsonValue &item : dataOptions) {
        const QJsonArray &childrenArray = item["children"].toArray();
        for (const QJsonValue &child : childrenArray) {
            const QJsonObject &childObj = child.toObject();
            const QJsonArray &grandChildrenArray = childObj["children"].toArray();
            for (const QJsonValue &grandChild : grandChildrenArray) {
                const QJsonObject &grandChildObj = grandChild.toObject();
                if (grandChildObj["name"].toString() == grandChildName) {
                    const QJsonArray &greatGrandChildrenArray = grandChildObj["children"].toArray();
                    for (const QJsonValue &greatGrandChild : greatGrandChildrenArray) {
                        const QJsonObject &greatGrandChildObj = greatGrandChild.toObject();
                        qDebug() << "greatGrandChildObj " << greatGrandChildObj;
                        QString name = greatGrandChildObj["name"].toString();
                        QString loraSn = greatGrandChildObj["loraSn"].toString();
                        ui->comboBoxLora->addItem(name);
                        nameLoraSnMap.insert(name, loraSn);
                        QHash<QString, QString>::const_iterator i;
                        for (i = nameLoraSnMap.constBegin(); i != nameLoraSnMap.constEnd(); ++i) {
                            qDebug() << "Key:" << i.key() << ", Value:" << i.value();
                        }
                    }
                    break;
                }
            }
        }
    }
    ui->comboBoxLora->setCurrentIndex(-1);
}

void ProjectDialog::extractNames(const QJsonArray &array, QStringList &names) {
    for (const auto &item : array) {
        if (item.isObject()) {
            QJsonObject obj = item.toObject();
            if (obj.contains("name")) {
                names.append(obj["name"].toString());
            }
            if (obj.contains("children") && obj["children"].isArray()) {
                extractNames(obj["children"].toArray(), names);
            }
        }
    }
}

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

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

void ProjectDialog::on_comboBoxAddr_currentIndexChanged(int index) {
    if (index >= 0 && index < parentOptions.size()) {
        L2AddressOptions = parentOptions[index].toObject()["children"].toArray();
        updateL2AddressOptions();
    }
}

void ProjectDialog::on_comboBoxAddr_2_currentIndexChanged(int index) {
    if (index >= 0 && index < L2AddressOptions.size()) {
        QJsonArray subOptions = L2AddressOptions[index].toObject()["children"].toArray();
        L3AddressOptions = subOptions;
        updateL3AddressOptions();
    }
}

void ProjectDialog::on_comboBoxAddr_3_currentIndexChanged(int index) {
    if (index >= 0 && index < L3AddressOptions.size()) {
        QString grandChildName = L3AddressOptions[index].toObject()["uuid"].toString();
        SetComboBoxLora(grandChildName);
    }
}

void ProjectDialog::validateAndSaveProject() {
    QString detNum = ui->editDetNum->text().trimmed();
    QString blastCount = ui->editRegCount->text().trimmed();
    QString projectName = ui->editName->text().trimmed();
    QString blastName = ui->comboBoxBlast->currentText().trimmed();
    QString operatorName = ui->comboBoxOperator->currentText().trimmed();
    QString l1AddressUuid = ui->comboBoxAddr->currentData().toString().trimmed();
    QString l2AddressUuid = ui->comboBoxAddr_2->currentData().toString().trimmed();
    QString l3AddressUuid = ui->comboBoxAddr_3->currentData().toString().trimmed();
    QString l1AddressName = ui->comboBoxAddr->currentText().trimmed();
    QString l2AddressName = ui->comboBoxAddr_2->currentText().trimmed();
    QString l3AddressName = ui->comboBoxAddr_3->currentText().trimmed();
    QString loraAddress = ui->comboBoxLora->currentText().trimmed();

    if (detNum.isEmpty() || !ui->editDetNum->hasAcceptableInput()) {
        QMessageBox::warning(nullptr, "输入错误", "请输入0-10000的数字！");
        return;
    }
    // 创建一个 QMap 集合，存储数据
    QMap<QString, QString> data;
    data["detNum"] = detNum;
    data["name"] = projectName;
    data["operatorName"] = operatorName;
    data["blasterName"] = blastName;
    // 选择level最低的uui：w
    QString addressUuid = l1AddressUuid;
    if (l3AddressUuid != "") {
        addressUuid = l3AddressUuid;
    } else if (l2AddressUuid != "") {
        addressUuid = l2AddressUuid;
    } else if (l1AddressUuid != "") {
        addressUuid = l1AddressUuid;
    } else {
        QMessageBox::warning(nullptr, "输入错误", "请选择地址！");
        return;
    }
    data["addressPath"] = l1AddressName + "/" + l2AddressName + "/" + l3AddressName;
    data["addressUuid"] = addressUuid;
    data["blasterIdentity"] = blasterId;
    data["operatorIdentity"] = operatorId;
    data["loraAddress"] = loraAddress;
    data["loraSn"] = nameLoraSnMap.value(loraAddress);
    data["blastCount"] = blastCount;
    if (operationStatus == 0) {
        emit validateDetNum(data);
    } else if (operationStatus == 1) {
        emit validateDetNumUpdate(data);
    }
    clearFormData();  // 清除表单数据
    // this->accept();
}

int ProjectDialog::getOperationStatus() const { return operationStatus; }

void ProjectDialog::setOperationStatus(int newOperationStatus) {
    operationStatus = newOperationStatus;
}

void ProjectDialog::setFormData(const HProject &Project) {
    try {
        ui->editName->setText(Project.getName());
        ui->editDetNum->setText(Project.getDetSum());
        ui->editHTID->setText(Project.getHtid());
        ui->editXMBH->setText(Project.getXmbh());
        int indexBlast = ui->comboBoxBlast->findText(Project.getBlasterName());
        if (indexBlast != -1) {
            ui->comboBoxBlast->setCurrentIndex(indexBlast);
        } else {
            qDebug() << "未找到选项 " << "。";
        }
        int indexOper = ui->comboBoxOperator->findText(Project.getOperatorName());
        if (indexOper != -1) {
            ui->comboBoxOperator->setCurrentIndex(indexOper);
        } else {
            qDebug() << "未找到选项 " << "。";
        }
        QStringList addressParts = Project.getAddressUuid().split("/");
        int numAddresses = addressParts.size();
        qDebug() << "numAddresses " << numAddresses;
        QVector<QString> addressVariables;
        for (int i = 0; i < numAddresses; ++i) {
            QString part = addressParts[i];
            addressVariables.append(part);
        }
        // 查找目标文本对应的索引
        int indexAddr = ui->comboBoxAddr->findText(addressVariables[0]);

        if (indexAddr != -1) {
            // 如果找到了对应的索引，设置为当前索引
            ui->comboBoxAddr->setCurrentIndex(indexAddr);
            qDebug() << "已将选项 " << addressVariables[0] << " 设置为当前显示的选项。";
        } else {
            // 如果没找到，输出提示信息
            qDebug() << "未找到选项 " << addressVariables[0];
        }
        if (addressVariables.size() >= 2) {
            int indexAddr_2 = ui->comboBoxAddr_2->findText(addressVariables[1]);

            if (indexAddr_2 != -1) {
                // 如果找到了对应的索引，设置为当前索引
                ui->comboBoxAddr_2->setCurrentIndex(indexAddr_2);
                qDebug() << "已将选项 " << addressVariables[1] << " 设置为当前显示的选项。";
            } else {
                // 如果没找到，输出提示信息
                qDebug() << "未找到选项 " << addressVariables[1];
            }
        }

        if (addressVariables.size() >= 3) {
            int indexAddr_3 = ui->comboBoxAddr_3->findText(addressVariables[2]);

            if (indexAddr_3 != -1) {
                // 如果找到了对应的索引，设置为当前索引
                ui->comboBoxAddr_3->setCurrentIndex(indexAddr_3);
                qDebug() << "已将选项 " << addressVariables[2] << " 设置为当前显示的选项。";
            } else {
                // 如果没找到，输出提示信息
                qDebug() << "未找到选项 " << addressVariables[2];
            }
        }
    } catch (const std::exception &e) {
        qDebug() << "发生异常: " << e.what();
    } catch (...) {
        qDebug() << "发生未知异常";
    }
}

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