#include "detinfopage.h"

#include <QTimer>

#include "QMessageBox"
#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::createDets, 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);

    QJsonObject postData;
    if (!jsonDoc.isNull() && jsonDoc.isObject()) {
        QJsonObject obj = jsonDoc.object();
        for (const QString& key : obj.keys()) {
            QJsonValue value = obj.value(key);
            if (value.isString()) {
                postData[key] = value.toString();
            }
        }
        postData["xmbh"] = DET_PARAM_XMBH;
        postData["dwdm"] = DET_PARAM_DWDM;
        postData["htid"] = DET_PARAM_HTID;
        postData["sbbh"] = DET_PARAM_SBBH;
    }
    QNetworkRequest request(fullUrl);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setRawHeader("Authorization", globalAuthority.toUtf8());
    QJsonDocument jsonDocument(postData);
    QByteArray jsonData = jsonDocument.toJson();
    QNetworkReply* reply = manager.post(request, jsonData);
    // 使用事件循环等待请求完成
    QEventLoop loop;
    QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();
    // 检查请求是否成功
    if (reply->error() == QNetworkReply::NoError) {
        // 获取响应数据
        QByteArray responseData = reply->readAll();
        QJsonDocument respData = QJsonDocument::fromJson(responseData);
        QJsonObject responseObject = respData.object();
        if (responseObject.contains("code") && responseObject["code"].toInt() == 200) {
            // 处理成功响应
            QMessageBox::information(nullptr, "雷管密文下发",
                                     "密文下发已经成功申请，由于请求较慢,请2分钟后刷新确认下发成功");
            loadAndRefreshData();
        } else {
            // 处理错误响应
            QMessageBox::information(nullptr, "雷管密文下发",
                                     QString("密文下发申请失败: %1").arg(responseObject.value("msg").toString()));
            Logger::getInstance().error(
                QString("请求创建雷管报错. Error: %1\n\t response:  %2").arg(reply->errorString()).arg(responseData));
        }

    } else {
        // 处理请求错误
        Logger::getInstance().error(
            QString("请求创建雷管报错. Error: %1\n\t query: %2").arg(reply->errorString()).arg(jsonData));
    }
    // 释放资源
    reply->deleteLater();
}
