#include "detinfopage.h"

#include <QTimer>

#include "ui_detinfopage.h"

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

void DetInfoPage::loadDataFromSource(int currentPage, int pageSize, const QString& equipmentSn) {
    QUrl localUrl("projectdet/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 DetInfoPage::PageChanged(int page) {
    currentPage = page;
    loadDataFromSource(currentPage, pageSize);
}

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

void DetInfoPage::dataTable(const QJsonDocument& jsonDoc) {
    parseJsonString(jsonDoc);
    model = new QStandardItemModel(this);
    model->setHorizontalHeaderLabels({"管码", "uid码", "创建时间"});
    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*> DetInfoPage::jsonToItem(const QJsonObject& jsonObj) {
    // QStandardItem* nameItem = new QStandardItem(jsonObj["name"].toString());
    // nameItem->setTextAlignment(Qt::AlignCenter);
    QStandardItem* fbhItem = new QStandardItem(jsonObj["fbh"].toString());
    QStandardItem* uidItem = new QStandardItem(jsonObj["uid"].toString());
    QStandardItem* gzmItem = new QStandardItem(jsonObj["gzm"].toString());

    QString yxqStr = jsonObj["yxq"].toString();
    QDateTime yxq = QDateTime::fromString(yxqStr, Qt::ISODateWithMs);
    QString formattedYxq = yxq.toString("yyyy-MM-dd HH:mm:ss");
    QStandardItem* yxqItem = new QStandardItem(formattedYxq);
    QStandardItem* isUseItem = new QStandardItem(jsonObj["isUse"].toInt());

    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*>() << fbhItem << uidItem << createdItem;
}

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

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

void DetInfoPage::on_pushButton_clicked() {
    dialog = new DetDialog;
    dialog->setModal(false);
    connect(dialog, &DetDialog::validateDetNum, this, &DetInfoPage::insertDet);
    int ref = dialog->exec();
    if (ref == QDialog::Accepted) {};
}

void DetInfoPage::insertDet(const QJsonDocument& jsonDoc) {
    QNetworkAccessManager manager;
    QUrl localUrl("det");
    QUrl fullUrl = apiBackendUrl.resolved(localUrl);
    qDebug() << "-----insert Det" << fullUrl;
    QUrlQuery query;
    if (!jsonDoc.isNull() && jsonDoc.isObject()) {
        QJsonObject obj = jsonDoc.object();
        for (const QString& key : obj.keys()) {
            QJsonValue value = obj.value(key);
            if (value.isString()) {
                query.addQueryItem(key, value.toString());
            }
        }
    }

    fullUrl.setQuery(query);
    QNetworkRequest request(fullUrl);

    request.setRawHeader("Authorization", globalAuthority.toUtf8());
    QNetworkReply* reply = manager.get(request);
    // 使用事件循环等待请求完成
    QEventLoop loop;
    QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();
    // 检查请求是否成功
    if (reply->error() == QNetworkReply::NoError) {
        // 获取响应数据
        QByteArray responseData = reply->readAll();
        QString responseString = QString::fromUtf8(responseData);
        qDebug() << "Response:" << responseString;
        loadAndRefreshData();
    } else {
        // 处理请求错误
        qDebug() << "Error:" << reply->errorString();
    }
    // 释放资源
    reply->deleteLater();
}
