#include "equipmentpage.h"

#include "../global.h"
#include "ui_equipmentpage.h"

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

void EquipmentPage::on_btnSearch_clicked() {
    QString equipmentSn = ui->editSn->text();
    loadDataFromSource(currentPage, pageSize, equipmentSn);
}

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

void EquipmentPage::loadDataFromSource(int currentPage, int pageSize, const QString& equipmentSn) {
    QUrl localUrl("equipment/pc");

    QUrlQuery query;
    query.addQueryItem("pageIndex", QString::number(currentPage));
    query.addQueryItem("pageSize", QString::number(pageSize));
    if (!equipmentSn.isEmpty()) {
        query.addQueryItem("equipmentSn", equipmentSn);
    }
    localUrl.setQuery(query);
    QUrl fullUrl = apiBackendUrl.resolved(localUrl);
    m_httpClient->sendHttpGetRequest(fullUrl);

    connect(m_httpClient, &HttpClient::httpGetFinished, [this](const QJsonDocument& data) {
        this->dataTable(data);
    });
}

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

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

void EquipmentPage::dataTable(const QJsonDocument& jsonDoc) {
    parseJsonString(jsonDoc);
    model = new QStandardItemModel(this);
    model->setHorizontalHeaderLabels(
        {"名称", "设备编号", "设备类型", "设备状态", "在线状态", "创建时间"});

    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*> EquipmentPage::jsonToItem(const QJsonObject& jsonObj) {
    QStandardItem* nameItem = new QStandardItem(jsonObj["name"].toString());
    nameItem->setTextAlignment(Qt::AlignCenter);
    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 << equipItem << typeItem << statusItem << onlineItem << createdItem;
}

void EquipmentPage::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));
}

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