#include "blastrecord.h"

#include "ui_blastrecord.h"

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

void BlastRecord::loadAndRefreshData() { loadDataFromSource(currentPage, pageSize); }

void BlastRecord::loadDataFromSource(int currentPage, int pageSize) {
    PaginatedHBlastRecordResult result = dao.getAllHRecords(currentPage, pageSize);

    QList<QSharedPointer<HBlastRecord>> blastRecordsList = result.BlastRecords;
    totalCount = result.totalCount;

    m_pPageWidget->setMaxPage(ceil(static_cast<double>(totalCount) / pageSize));
    QStandardItemModel* model;
    model = new QStandardItemModel(this);
    // 定义表头信息

    QList<HeaderInfo> headers = {
        {"工程名称", "projectName"},   {"是否离线", "isOfflineBlast"}, {"app版本", "appVersion"},
        {"起爆器编号", "equipmentSn"}, {"注册雷管", "regDetCount"},    {"起爆时间", "blastAt"},
        {"上报时间", "updatedAt"},
    };

    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 < blastRecordsList.size(); ++row) {
        HBlastRecord& HBlastRecord = *blastRecordsList.at(row).data();
        for (int col = 0; col < headers.size(); ++col) {
            QString prop = propMap[col];
            QStandardItem* item = nullptr;
            if (!prop.isEmpty()) {
                QMetaProperty metaProp = HBlastRecord.metaObject()->property(
                    HBlastRecord.metaObject()->indexOfProperty(prop.toUtf8()));
                QVariant value = metaProp.read(&HBlastRecord);
                if (value.type() == QVariant::DateTime) {
                    QDateTime dateTime = value.toDateTime();
                    item = new QStandardItem(dateTime.toString("yyyy-MM-dd HH:mm:ss"));
                } else if (prop == "isOfflineBlast") {
                    item = new QStandardItem(value.toBool() ? "离线爆破" : "线上爆破");
                } 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->setAlternatingRowColors(true);  // 启用交替行颜色
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
}
void BlastRecord::PageChanged(int page) {
    currentPage = page;
    loadDataFromSource(currentPage, pageSize);
}

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

void BlastRecord::dataTable(const QJsonDocument& jsonDoc) {
    parseJsonString(jsonDoc);
    model = new QStandardItemModel(this);
    model->setHorizontalHeaderLabels(
        {"工程名称", "离线爆破", "app版本", "起爆器编号", "注册雷管", "起爆时间", "上报时间"});

    for (const QJsonValue& jsonValue : dataArray) {
        QJsonObject jsonObj = jsonValue.toObject();
        QList<QStandardItem*> items = jsonToItem(jsonObj);
        model->appendRow(items);
    }

    ui->tableView->setModel(model);
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableView->setAlternatingRowColors(true);
}

QList<QStandardItem*> BlastRecord::jsonToItem(const QJsonObject& jsonObj) {
    QStandardItem* nameItem = new QStandardItem(jsonObj["name"].toString());
    nameItem->setTextAlignment(Qt::AlignCenter);
    qDebug() << "jsonObj:" << jsonObj;
    QStandardItem* isOfflineBlastItem = new QStandardItem(jsonObj["isOfflineBlast"].toString());
    QStandardItem* equipItem = new QStandardItem(jsonObj["equipmentSn"].toString());
    QStandardItem* typeItem = new QStandardItem(jsonObj["equipmentTypeName"].toString());
    QStandardItem* statusItem = new QStandardItem(jsonObj["statusName"].toString());
    QStandardItem* onlineItem = new QStandardItem(jsonObj["onlineName"].toString());
    QString createdAtStr = jsonObj["createdAt"].toString();
    QDateTime createdAt = QDateTime::fromString(createdAtStr, Qt::ISODateWithMs);
    QString formattedCreatedAt = createdAt.toString("yyyy-MM-dd HH:mm:ss");
    QStandardItem* createdItem = new QStandardItem(formattedCreatedAt);

    return QList<QStandardItem*>() << nameItem << isOfflineBlastItem << equipItem << typeItem
                                   << statusItem << onlineItem << createdItem;
}
void BlastRecord::parseJsonString(const QJsonDocument& jsonDoc) {
    QJsonObject jsonObj = jsonDoc.object();
    QJsonObject dataObj = jsonObj["data"].toObject();
    dataArray = dataObj["list"].toArray();
    totalCount = dataObj["count"].toInt();
    m_pPageWidget->setMaxPage(ceil(static_cast<double>(totalCount) / pageSize));
}
BlastRecord::~BlastRecord() { delete ui; }
