#include "addresspage.h"

#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QUrl>

#include "global.h"
#include "httpclient.h"
#include "ui_addresspage.h"
AddressPage::AddressPage(QWidget* parent) : QWidget(parent), ui(new Ui::AddressPage) {
    ui->setupUi(this);
    m_httpClient = new HttpClient(this);
    QUrl localUrl("h-address/pc");
    QUrl fullUrl = apiBackendUrl.resolved(localUrl);
    m_httpClient->sendHttpGetRequest(fullUrl);

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

void AddressPage::dataTable(const QJsonDocument& jsonDoc) {
    parseJsonString(jsonDoc);
    model = new QStandardItemModel(this);
    model->setHorizontalHeaderLabels({"名称", "设备编号", "LORA地址", "描述", "创建时间"});

    if (jsonDoc["data"].isArray()) {
        QJsonArray jsonArray = jsonDoc["data"].toArray();

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

    ui->treeView->setModel(model);
    ui->treeView->header()->setSectionResizeMode(QHeaderView::Stretch);
    ui->treeView->header()->setDefaultAlignment(Qt::AlignCenter);
    ui->treeView->setAlternatingRowColors(true);
}

void AddressPage::parseJsonString(const QJsonDocument& jsonDoc) {
    QJsonObject jsonObj = jsonDoc.object();
    QJsonObject dataObj = jsonObj["data"].toObject();
    dataArray = dataObj["list"].toArray();
}

QList<QStandardItem*> AddressPage::jsonToItem(const QJsonObject& jsonObj) {
    QStandardItem* nameItem = new QStandardItem(jsonObj["name"].toString());
    nameItem->setTextAlignment(Qt::AlignCenter);
    QStandardItem* equipmentSn = new QStandardItem(jsonObj["equipmentSn"].toString());
    QStandardItem* loraSn = new QStandardItem(jsonObj["loraSn"].toString());
    QStandardItem* describe = new QStandardItem(jsonObj["describe"].toString());
    QString isoDateTimeStr = jsonObj["createdAt"].toString();
    QDateTime dateTime = QDateTime::fromString(isoDateTimeStr, Qt::ISODateWithMs);
    QString formattedDateTime = dateTime.toString("yyyy-MM-dd hh:mm:ss");
    QStandardItem* createdAt = new QStandardItem(formattedDateTime);
    if (jsonObj.contains("children") && jsonObj["children"].isArray()) {
        QJsonArray childrenArray = jsonObj["children"].toArray();
        for (const QJsonValue& child : childrenArray) {
            QList<QStandardItem*> childItems = jsonToItem(child.toObject());
            nameItem->appendRow(childItems);
        }
    }

    return QList<QStandardItem*>() << nameItem << equipmentSn << loraSn << describe << createdAt;
}

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