#include "wupgradeapkitem.h"
#include "tools.h"
#include "base/x_uimsgboxok.h"
#include "passwordindlg.h"
#include <QMessageBox>
#include <QJsonValue>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QProgressBar>
#include <globaldefine.h>
#include <QSizePolicy>
#include <QUuid>
#include <QMap>
#include <QMessageBox>
#include <QHostAddress>
#include <QInputDialog>

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

void wUpgradeApkItem::OnCheckFpgaVersions() {
    QJsonObject json;
    json.insert("_id", "CheckHardwareVersions");
    json.insert("_type", "CheckHardwareVersions");
    auto reply = Tools::netManager().post(reqForJson("http://"+mCard->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
    connect(reply, &QNetworkReply::finished, this, [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 = Tools::netManager().post(reqForJson("http://"+mCard->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
    connect(reply, &QNetworkReply::finished, this, [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::onVerifyLockPassword() {
    bool ok;
    auto pwd = QInputDialog::getText(gMainWin, tr("Input password"), 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 reply = Tools::netManager().post(reqForJson("http://"+mCard->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
    connect(reply, &QNetworkReply::finished, this, [reply, this] {
        QJsonDocument json;
        QString err = checkReplyForJson(reply, &json);
        if(! err.isEmpty()) {
            QMessageBox::critical(gMainWin, tr("Error"), err);
            return;
        }
        if(json["result"].toBool()) mCard->m_bLockStatus = false;
        else {
            mCard->m_bLockStatus = true;
            QMessageBox::critical(gMainWin, tr("Tip Info"), tr("password is wrong"));
        }
        SetPasswordItem(mCard);
    });
}
void wUpgradeApkItem::SetPasswordItem(LedCard *p){
    if(p->bPassword) {//加过密
        if(m_bnLock==nullptr){
            m_bnLock = new QPushButton(m_pWnd);
            m_bnLock->setStyleSheet("background-color:transparent;");
            m_bnLock->setStyleSheet("margin-left:12px; margin-right:12px;margin-top:12px; margin-bottom:12px;");
            m_parent->setItemWidget(this, Upgrade_ENCRYPT, m_bnLock);
            connect(m_bnLock, SIGNAL(clicked()), this, SLOT(onVerifyLockPassword()));
        }
        if(p->m_bLockStatus) m_bnLock->setIcon(QIcon(":/res/device/Lock.png")); //如果已经验证通过密码显示绿色图标
        else m_bnLock->setIcon(QIcon(":/res/device/UnLock.png")); //如果没有验证显示蓝色锁图标
        m_parent->setItemWidget(this, Upgrade_ENCRYPT, m_bnLock);
    }
}
void wUpgradeApkItem::setResult(QString tip, QColor color) {
    setText(Upgrade_Remark, tip);
    setToolTip(Upgrade_Remark, tip);
    setForeground(Upgrade_Remark, color);
}
void wUpgradeApkItem::SetItemParam(LedCard *p) {
    setData(Upgrade_SCREEN_ID, 0, p->m_strCardId);
    setData(Upgrade_SCREEN_IP, 0, p->m_strCardIp);
    mCard->m_strCardId = p->m_strCardId;
    mCard->m_strCardIp = p->m_strCardIp;
    mCard->m_bOnLine = p->m_bOnLine;
    if(mCard->m_bOnLine) m_ImageOnline->setPixmap(QPixmap(mCard->m_bOnLine ? ":/res/device/O_Online.png" : ":/res/device/O_Offline.png"));
    SetPasswordItem(mCard);
    setData(Upgrade_REMARK_NAME, 0, p->m_strCardRemarkName);
    OnCheckSoftVersions();
    OnCheckFpgaVersions();
}
