#include "blastprojectpage.h"

#include <QUrl>
#include <iostream>

#include "../backendapimanager.h"
#include "../databasemanager.h"
#include "../global.h"
#include "ui_blastprojectpage.h"

BlastProjectPage::BlastProjectPage(QWidget *parent)
    : QWidget(parent),
      ui(new Ui::BlastProjectPage),
      dao(DatabaseManager::getInstance().getDatabase()) {
    ui->setupUi(this);
    pageWidget = new PageWidget;
    connect(pageWidget, &PageWidget::currentPageChanged, this, &BlastProjectPage::PageChanged);
    connect(pageWidget->getComboBox(), QOverload<int>::of(&QComboBox::currentIndexChanged), this,
            &BlastProjectPage::onComboBoxIndexChanged);
    ui->verticalLayout_4->addWidget(pageWidget);
    pageSize = 10;
    currentPage = 1;

    RefreshData();

    dialog = new ProjectDialog(this);
    QJsonArray pcs = backendAPIManager::getHAddresses();
    addressOptions(pcs);
    QJsonArray sysUsersObj = backendAPIManager::getSysUsers();
    personOptionsByType(sysUsersObj);
    connect(dialog, &ProjectDialog::validateDetNum, this, &BlastProjectPage::insertPlan);
    connect(dialog, &ProjectDialog::validateDetNumUpdate, this, &BlastProjectPage::updateProject);

    mqttClient = MqttClient::getInstance();
}

void BlastProjectPage::RefreshData() { loadDataFromSource(currentPage, pageSize); }

void BlastProjectPage::loadDataFromSource(int currentPage, int pageSize) {
    PaginatedHProjectResult result = dao.getAllHProjects(currentPage, pageSize);

    QList<QSharedPointer<HProject>> projectList = result.projects;

    totalCount = result.totalCount;
    pageWidget->setMaxPage(ceil(static_cast<double>(totalCount) / pageSize));
    QStandardItemModel *model;
    model = new QStandardItemModel(this);

    // 定义表头信息
    QList<HeaderInfo> headers = {
        {"工程名称", "name"},        {"操作员", "operatorName"},
        {"爆破员", "blasterName"},   {"井下地址", "addressPath"},
        {"雷管数量", "detSum"},      {"起爆器数量", "blastCount"},
        {"起爆状态", "blastStatus"}, {"操作", ""},
    };

    int headerCount = headers.size();
    QStringList headerLabels;
    QMap<int, QString> propMap;
    for (int i = 0; i < headers.size(); ++i) {
        headerLabels << headers[i].label;
        propMap[i] = headers[i].prop;
    }
    model->setHorizontalHeaderLabels(headerLabels);

    for (int row = 0; row < projectList.size(); ++row) {
        HProject &HProject = *projectList.at(row).data();
        for (int col = 0; col < headers.size(); ++col) {
            QString prop = propMap[col];
            QStandardItem *item = nullptr;

            if (!prop.isEmpty()) {
                QMetaProperty metaProp = HProject.metaObject()->property(
                    HProject.metaObject()->indexOfProperty(prop.toUtf8()));
                QVariant value = metaProp.read(&HProject);
                if (prop == "blastStatus") {
                    QString statusText;
                    if (value.toString() == BlastStatus::Created) {
                        statusText = "未注册";
                        item = new QStandardItem(statusText);
                        item->setForeground(QColor("#e7c66b"));
                    } else if (value.toString() == BlastStatus::Registered) {
                        statusText = "待安全确认";
                        item = new QStandardItem(statusText);
                        item->setForeground(QColor("#f3a361"));
                    } else if (value.toString() == BlastStatus::SafeChecked) {
                        statusText = "待起爆";
                        item = new QStandardItem(statusText);
                        item->setForeground(QColor("#f3a361"));

                    } else if (value.toString() == BlastStatus::Blasted) {
                        statusText = "起爆完成";
                        item = new QStandardItem(statusText);
                        item->setForeground(QColor("#90d543"));
                    } else {
                        item = new QStandardItem(value.toString());
                    }
                } else {
                    item = new QStandardItem(value.toString());
                }

            } else {
                item = new QStandardItem("操作");
            }
            if (item) {
                item->setTextAlignment(Qt::AlignCenter);
                model->setItem(row, col, item);
            }
        }
    }
    ui->tableView->setModel(model);
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView->setAlternatingRowColors(true);
    // 创建并设置自定义委托
    ButtonDelegate *delegate = new ButtonDelegate(headerCount - 1, this);
    QObject::connect(delegate, &ButtonDelegate::buttonClicked, [=](int row, int column) {
        // 获取 HPlan 引用
        HProject &HPlanDeleteOrUpdate = *projectList.at(row).data();
        updateId = HPlanDeleteOrUpdate.getId();
        if (column == 1) {
            deleteButtonClicked(HPlanDeleteOrUpdate);
        }
        if (column == 2) {
            updateButtonClicked(HPlanDeleteOrUpdate);
        }
    });
    ui->tableView->setItemDelegateForColumn(headerCount - 1, delegate);
}

void BlastProjectPage::PageChanged(int page) {
    currentPage = page;
    loadDataFromSource(currentPage, pageSize);
}

void BlastProjectPage::onComboBoxIndexChanged(int index) {
    QVariant variant = pageWidget->getComboBox()->itemData(index);
    int value = variant.toInt();
    pageSize = value;
    currentPage = 1;
    loadDataFromSource(currentPage, pageSize);
}

void BlastProjectPage::personOptionsByType(const QJsonArray &dataArray) {
    QJsonArray blasterDeployerArray;
    QJsonArray operatorArray;
    for (const QJsonValue &value : dataArray) {
        if (value.isObject()) {
            QJsonObject obj = value.toObject();
            if (obj.contains("roleIds")) {
                QJsonArray roleIdsArray = obj["roleIds"].toArray();
                // TODO: 角色ID改成常量
                if (roleIdsArray.contains(4)) {  // 爆破员
                    blasterDeployerArray.append(obj);
                } else if (roleIdsArray.contains(7)) {  // 操作员
                    operatorArray.append(obj);
                }
            }
        }
    }

    dialog->SetComboBoxBlast(blasterDeployerArray);
    dialog->SetComboBoxOperator(operatorArray);
}

void BlastProjectPage::addressOptions(const QJsonArray &dataArrayAddress) {
    dialog->SetL1AddressOptions(dataArrayAddress);
    // dialog->setChildOptions(dataArrayAddress);
}

// 递归函数，用于提取所有的 name 信息
void BlastProjectPage::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 BlastProjectPage::parseJsonString(const QJsonDocument &jsonDoc) {
    QJsonObject jsonObj = jsonDoc.object();
    QJsonObject dataObj = jsonObj["data"].toObject();
    dataArray = dataObj["list"].toArray();
}

void BlastProjectPage::on_pushButton_clicked() {
    dialog->setModal(false);
    dialog->setOperationStatus(0);
    int ref = dialog->exec();
    if (ref == QDialog::Accepted) {};
}

void BlastProjectPage::insertPlan(const QMap<QString, QString> &data) {
    HProject project;
    project.setName(data.value("name"));
    project.setDetSum(data.value("detNum"));
    project.setBlasterName(data.value("blasterName"));
    project.setOperatorName(data.value("operatorName"));
    project.setAddressUuid(data.value("addressUuid"));
    project.setAddressPath(data.value("addressPath"));
    project.setBlasterIdentity(data.value("blasterIdentity"));
    project.setOperatorIdentity(data.value("operatorIdentity"));
    project.setLoraAddress(data.value("loraAddress"));
    project.setLoraSn(data.value("loraSn"));
    project.setBlastCount(data.value("blastCount"));
    project.setBlastStatus("1");
    // 生成 32 位的 UUID
    QString uuidString =
        QUuid::createUuid().toString(QUuid::WithoutBraces).remove(QRegularExpression("-"));
    project.setUuid(uuidString);
    project.setCreatedAt(QDateTime::currentDateTime());
    if (dao.addHProject(project)) {
        RefreshData();
        QJsonArray jsonArray;
        QList<QSharedPointer<HProject>> projectsReg = dao.getAllHProjectsReg();
        for (const auto &projectPtr : projectsReg) {
            if (projectPtr) {
                QByteArray projectJson = projectPtr->ProjectToJson(*projectPtr);
                QJsonDocument doc = QJsonDocument::fromJson(projectJson);
                jsonArray.append(doc.object());
            }
        }

        QJsonDocument jsonDoc(jsonArray);
        QByteArray jsonData = jsonDoc.toJson(QJsonDocument::Indented);

        mqttClient->sendMessage("hxgc/companycode/pro/B", jsonData, 2, true);
    }
}

void BlastProjectPage::updateButtonClicked(const HProject &project) {
    dialog->setModal(false);
    dialog->setOperationStatus(1);
    dialog->setFormData(project);
    int ref = dialog->exec();
    if (ref == QDialog::Accepted) {};
}

void BlastProjectPage::updateProject(const QMap<QString, QString> &data) {
    HProject project;
    project.setId(updateId);
    project.setName(data.value("name"));
    project.setDetSum(data.value("detNum"));
    project.setBlasterName(data.value("blasterName"));
    project.setOperatorName(data.value("operatorName"));
    project.setAddressUuid(data.value("addressUuid"));
    project.setBlasterIdentity(data.value("blasterIdentity"));
    project.setOperatorIdentity(data.value("operatorIdentity"));
    project.setUpdatedAt(QDateTime::currentDateTime());
    if (dao.updateHProject(project)) {
        RefreshData();
    }
}
void BlastProjectPage::deleteButtonClicked(const HProject &project) {
    if (dao.deleteHProject(project)) {
        RefreshData();
    }
}

void BlastProjectPage::messageAndTopicReceived(const QByteArray &message,
                                               const QMqttTopicName &topic) {
    QJsonDocument jsonDoc = QJsonDocument::fromJson(message);
    if (!jsonDoc.isNull() && jsonDoc.isObject()) {
        QJsonObject jsonObj = jsonDoc.object();
        if (jsonObj.contains("uuid") && jsonObj.contains("status")) {
            QJsonValue uuidValue = jsonObj["uuid"];
            QJsonValue statusValue = jsonObj["status"];
            if (statusValue.isString() && statusValue.toString() == "1") {
                if (uuidValue.isNull()) {
                    qDebug() << "uuid 的值为 null";
                } else {
                    QString uuid = uuidValue.toString();
                    updateProjectUUId(uuid);
                }
            }
        }
    }
}

void BlastProjectPage::updateProjectUUId(QString uuid) { dao.updateBlastStatusByUuid(uuid, "2"); }

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