#include "wupgradeapkitem.h"
#include "base/waitingdlg.h"
#include "deviceitem.h"
#include "gutil/qgui.h"
#include "gutil/qnetwork.h"
#include <QMessageBox>
#include <QJsonArray>
#include <QJsonDocument>
#include <QProgressBar>
#include <globaldefine.h>
#include <QMessageBox>
#include <QInputDialog>

wUpgradeApkItem::wUpgradeApkItem(LedCard pLedCard, LoQTreeWidget *parent) : QTreeWidgetItem(UserType), mCard(pLedCard), m_parent(parent) {
    setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
    setCheckState(0, Qt::Unchecked);
    m_parent->addTopLevelItem(this);
    m_ImageOnline = new QLabel();
    m_ImageOnline->setAlignment(Qt::AlignCenter);
    m_parent->setItemWidget(this, Upgrade_ONLINE, m_ImageOnline);
    for(int i=1; i<Upgrade_END; i++) setTextAlignment(i, Qt::AlignCenter);
    mProgress = new QProgressBar;
    mProgress->setAlignment(Qt::AlignCenter);
    mProgress->setStyleSheet("margin-top:8px; margin-bottom:8px; ");
    m_parent->setItemWidget(this, Upgrade_PROGRESS, mProgress);

    btnUnlock = new QPushButton;
    btnUnlock->setMaximumHeight(40);
    auto wgt = new QWidget;
    auto vBox = new VBox(wgt);
    vBox->setContentsMargins(0,0,0,0);
    vBox->addWidget(btnUnlock);
    m_parent->setItemWidget(this, Upgrade_ENCRYPT, wgt);
    QObject::connect(btnUnlock, &QPushButton::clicked, mProgress, [this] {
        if(! mCard.isLocked) return;
        bool ok;
        auto pwd = QInputDialog::getText(treeWidget(), QObject::tr("Input password"), QObject::tr("Input password"), QLineEdit::Password, QString(), &ok);
        if(! ok) return;
        QJsonObject json;
        json.insert("_id", "VerifyPassword");
        json.insert("_type", "VerifyPassword");
        json.insert("pwd", pwd);
        auto waitingDlg = new WaitingDlg(treeWidget(), QObject::tr("VerifyPassword")+" ...");
        waitingDlg->show();
        auto reply = NetReq("http://"+mCard.ip+":2016/settings").timeout(120000).post(json);
        waitingDlg->connAbort(reply);
        QObject::connect(reply, &QNetworkReply::finished, mProgress, [=] {
            QJsonDocument json;
            QString err = checkReplyForJson(reply, &json);
            if(! err.isEmpty()) {
                waitingDlg->close();
                QMessageBox::critical(treeWidget(), QObject::tr("Error"), err);
                return;
            }
            if(! json["result"].toBool()) {
                waitingDlg->close();
                QMessageBox::critical(treeWidget(), QObject::tr("Tip Info"), QObject::tr("password is wrong"));
                return;
            }
            waitingDlg->success();
            mCard.isLocked = false;
            btnUnlock->setIcon(QIcon(":/res/device/UnLock.png"));
            auto item = findItem(mCard.id);
            if(item) {
                item->mCard.isLocked = false;
                item->btnUnlock->setIcon(QIcon(":/res/device/UnLock.png"));
            }
        });
    });

    SetItemParam(mCard);
}

void wUpgradeApkItem::OnCheckFpgaVersions() {
    QJsonObject json;
    json.insert("_id", "CheckHardwareVersions");
    json.insert("_type", "CheckHardwareVersions");
    auto reply = NetReq("http://"+mCard.ip+":2016/settings").timeout(120000).post(json);
    QObject::connect(reply, &QNetworkReply::finished, mProgress, [reply, this] {
        QJsonDocument json;
        QString err = checkReplyForJson(reply, &json);
        if(! err.isEmpty()) {
            return;
        }
        QString strBuf;
        auto vers = json["versions"].toArray();
        for(int i=0; i<vers.size(); i++) {
            if(i==0) strBuf += "["+QString::number(i)+"]:"+vers[i].toString();
            else strBuf +="\r\n["+QString::number(i)+"]:"+vers[i].toString();
        }
        setData(Upgrade_FPAG_VERSION, 0, strBuf);
    });
}
void wUpgradeApkItem::OnCheckSoftVersions() {
    QJsonObject json;
    json.insert("_id", "CheckSoftVersions");
    json.insert("_type", "CheckSoftVersions");
    auto reply = NetReq("http://"+mCard.ip+":2016/settings").timeout(120000).post(json);
    QObject::connect(reply, &QNetworkReply::finished, mProgress, [reply, this] {
        QJsonDocument json;
        QString err = checkReplyForJson(reply, &json);
        if(! err.isEmpty()) {
            return;
        }
        auto apps = json["apps"].toArray();
        foreach(QJsonValue app, apps) {
            QString packageName = app["packageName"].toString();
            QString verName = app["versionName"].toString();
            if(packageName=="com.xixun.xixunplayer") setData(Upgrade_XIXUNPLAYER_VERSION, 0, verName);
            else if(packageName=="com.xixun.joey.cardsystem") setData(Upgrade_CARDSYSTEM_VERSION, 0, verName);
            else if(packageName=="net.sysolution.starter") setData(Upgrade_STARTER_VERSION, 0, verName);
            else if(packageName=="net.sysolution.taxiapp") setData(Upgrade_TAXIAPP_VERSION, 0, verName);
            else if(packageName=="com.xixun.display") setData(Upgrade_DISPLAYER_VERSION, 0, verName);
            else if(packageName=="com.xixun.xy.conn") setData(Upgrade_CONNECTION_VERSION, 0, verName);
            else if(packageName=="com.xixun.xy.update") setData(Upgrade_UPDATE_VERSION, 0, verName);
        }
    });
}
void wUpgradeApkItem::setResult(QString tip, QColor color) {
    setText(Upgrade_Remark, tip);
    setToolTip(Upgrade_Remark, tip);
    setForeground(Upgrade_Remark, color);
}
void wUpgradeApkItem::SetItemParam(LedCard card) {
    mCard.id = card.id;
    mCard.ip = card.ip;
    mCard.isOnline = card.isOnline;
    setData(Upgrade_SCREEN_ID, 0, card.id);
    setData(Upgrade_SCREEN_IP, 0, card.ip);
    setData(Upgrade_REMARK_NAME, 0, card.alias);
    m_ImageOnline->setPixmap(QPixmap(mCard.isOnline ? ":/res/device/O_Online.png" : ":/res/device/O_Offline.png"));
    OnCheckSoftVersions();
    OnCheckFpgaVersions();
    if(! card.hasPassword) btnUnlock->hide();
    else {
        if(! btnUnlock->isVisible()) btnUnlock->show();
        btnUnlock->setIcon(QIcon(card.isLocked ? ":/res/device/Lock.png" : ":/res/device/UnLock.png")); //如果已经验证通过密码显示绿色图标 没有验证显示蓝色锁图标
    }
}
