#include "statuswidget.h"

#include <QDebug>
#include <QBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QStringList>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QTimer>

#include <DThemeManager>

class StatusWidgetPrivate
{
public:
    StatusWidgetPrivate(StatusWidget *parent) : q_ptr(parent) {}

    QWidget *statusWapper           = Q_NULLPTR;
    QVBoxLayout *statusWapperLayout = Q_NULLPTR;
    QWidget *status                 = Q_NULLPTR;
    QLabel  *tipLabel               = Q_NULLPTR;

    StatusWidget *q_ptr;
    Q_DECLARE_PUBLIC(StatusWidget)
};

StatusWidget::StatusWidget(QWidget *parent) :
    QWidget(parent), dd_ptr(new StatusWidgetPrivate(this))
{
    Q_D(StatusWidget);
    Dtk::Widget::DThemeManager::registerWidget(this);

    auto layout = new QVBoxLayout(this);
    layout->setContentsMargins(0, 38, 0, 0);
    auto statusHintLayout = new QHBoxLayout;
    statusHintLayout->setContentsMargins(0, 0, 0, 0);

    QList<QStringList> indicatorInfoList = {
        {tr("Authroized"), "#04ab5f"},
        {tr("Unauthroized"), "#ff6d4d"},
        {tr("Unknown"), "#868686"}
    };
    statusHintLayout->addStretch();

    for (auto indicator : indicatorInfoList) {
        auto str = indicator.value(0);
        auto color = indicator.value(1);

        auto icon = new QLabel;
        icon->setStyleSheet(QString("QLabel{background-color: %1;}").arg(color));
        icon->setFixedSize(12, 12);
        statusHintLayout->addWidget(icon);

        auto text = new QLabel(str);
        text->setObjectName("CategoryHint");
        statusHintLayout->addWidget(text);
    }
    statusHintLayout->addStretch();

    layout->addLayout(statusHintLayout);

    d->statusWapper = new QWidget;
    d->statusWapperLayout = new QVBoxLayout(d->statusWapper);
    d->tipLabel = new QLabel;

    auto backButton = new QPushButton(tr("Back"));
    backButton->setMinimumSize(310, 36);

    layout->addSpacing(20);
    layout->addWidget(d->statusWapper, 0, Qt::AlignCenter);
    layout->addStretch();
    layout->addWidget(d->tipLabel, 0, Qt::AlignCenter);
    layout->addStretch();
    layout->addWidget(backButton, 0, Qt::AlignCenter);

    connect(backButton, &QPushButton::clicked, this, &StatusWidget::back);
}

StatusWidget::~StatusWidget()
{

}

void StatusWidget::updateStatus(QJsonObject offlineResult, QJsonObject onlineResult)
{
    Q_D(StatusWidget);
    if (d->status) {
        d->status->hide();
        d->status->setParent(nullptr);
        d->status->deleteLater();
        d->status = nullptr;
    }

    d->status = new QFrame;
    d->statusWapperLayout->addWidget(d->status);

    auto layout = new QVBoxLayout(d->status);

    QList<QStringList> categoryList = {
        {"os", tr("OS status:")},
        {"office", tr("Office status:")},
        {"antivirus", tr("Antivirus status:")}
    };

    auto onlineCheck = false;
    auto result = offlineResult;
    qDebug() << onlineResult;
    if (onlineResult.contains("soft")) {
        onlineCheck = true;
        result = onlineResult;
        qDebug() << "use online result";
    }

    QMap<QString, QJsonArray> categorySoftwares;
    auto softwares = result.value("soft").toArray();
    for (auto software : softwares) {
        auto obj = software.toObject();
        auto array = categorySoftwares[obj.value("category").toString()];
        array.push_back(obj);
        categorySoftwares[obj.value("category").toString()] = array;
    }

    auto grid = new QGridLayout;
    grid->setColumnStretch(0, 100);
//    grid->setColumnStretch(1, 200);

    auto gridRow = 0;
    for (auto categoryInfo : categoryList) {
        grid->setRowMinimumHeight(gridRow, 22);
        auto category = categoryInfo.value(0);
        auto categoryName = categoryInfo.value(1);
        auto categoryHint = new QLabel(categoryName);
        categoryHint->setObjectName("SoftwareHint");
        grid->addWidget(categoryHint, gridRow, 0, Qt::AlignLeft | Qt::AlignBottom);
        auto firstRow = gridRow;
        ++gridRow;

        for (auto software : categorySoftwares.value(category)) {
            auto obj = software.toObject();
            auto name = obj.value("name").toString();
            auto authorized = obj.value("authorized").toBool();
            if (authorized) {
                name += "（正版）";
            } else {
                name += "（疑似盗版）";
            }
            auto nameLabel = new QLabel(name);
            nameLabel->setObjectName(authorized ? "Authorized" : "Unauthorized");
            auto align = Qt::AlignLeft | ((firstRow == gridRow) ? Qt::AlignBottom : Qt::AlignVCenter);
            grid->addWidget(nameLabel,  gridRow, 0, align);
            ++gridRow;
        }
        if (categorySoftwares.value(category).isEmpty()) {
            auto nameLabel = new QLabel(tr("Unknown"));
            nameLabel->setObjectName("Unknown");
            grid->addWidget(nameLabel,  gridRow, 0);
            ++gridRow;
        }
    }

    auto hint =  QString(tr("Check status:"));

    auto checkStatus = onlineCheck ?
                       QString(tr("Online check")) :
                       QString(tr("Offline check"));
    auto hintLabel = new QLabel(hint + checkStatus);
    hintLabel->setObjectName("SoftwareHint");
    grid->addWidget(hintLabel, gridRow, 0, Qt::AlignLeft | Qt::AlignBottom);
    layout->addLayout(grid);

    d->tipLabel->setText(tr("Your information has been submitted successfully!"));
    d->tipLabel->setObjectName("SuccessLabel");
    QTimer::singleShot(5000, [ = ]() {
        d->tipLabel->setText("");
    });
    setStyleSheet(this->styleSheet());
}
