#include "wprogrampublishitem.h"
#include "tools.h"
#include "base/x_uimsgboxok.h"
#include "passwordindlg.h"
#include <QMessageBox>
#include <QJsonValue>
#include <QJsonObject>
#include <QJsonDocument>
#include <QProgressBar>
#include <globaldefine.h>
#include <QSizePolicy>
#include <QInputDialog>
#include <QMetaEnum>
wProgramPublishItem::wProgramPublishItem(LedCard *pLedCard, LoQTreeWidget *parent, QWidget *pWnd, QString strProgramName, QString strProgramPath) : QObject(parent), QTreeWidgetItem(UserType), m_parent(parent) {
    m_strProgramName = strProgramName;
    m_strProgramPath = strProgramPath;
    m_pWnd = pWnd;
    mLedCard = pLedCard;

    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, ENUM_DEVICE_PUBLISH_HEADE_ONLINE, m_ImageOnline);
    for(int i=1; i<ENUM_DEVICE_PUBLISH_HEADE_REMARKS; i++) setTextAlignment(i, Qt::AlignCenter);
    SetItemParam(mLedCard);
    fdProgress = new QProgressBar();
    fdProgress->setStyleSheet("margin-top: 8px; margin-bottom: 8px;");
    m_parent->setItemWidget(this, ENUM_DEVICE_PUBLISH_HEADE_PROGRESS, fdProgress);
    fdProgress->setAlignment(Qt::AlignCenter);
}

void wProgramPublishItem::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("_type", "VerifyPassword");
    json.insert("_id", QString::number(QDateTime::currentMSecsSinceEpoch()));
    json.insert("pwd", pwd);

    QNetworkRequest request{"http://"+mLedCard->m_strCardIp+":2016/settings"};
    request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    auto reply = Tools::netManager().post(request, QJsonDocument{json}.toJson(QJsonDocument::Compact));
    connect(reply, &QNetworkReply::finished, this, [this, reply] {
        reply->deleteLater();
        if(reply->error() != QNetworkReply::NoError) {
            QMessageBox::critical(gMainWin, tr("Error"), QString::number(reply->error())+" "+QMetaEnum::fromType<QNetworkReply::NetworkError>().valueToKey(reply->error())+" "+reply->errorString());
            return;
        }
        auto status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        if(status != 200) {
            QMessageBox::critical(gMainWin, tr("Error"), QString::number(status)+" "+reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString());
            return;
        }
        auto resp = reply->readAll();
        QJsonParseError jsonErr;
        QJsonDocument json = QJsonDocument::fromJson(resp, &jsonErr);
        if(jsonErr.error != QJsonParseError::NoError) {
            QMessageBox::critical(gMainWin, tr("Error"), "JsonParseError "+jsonErr.errorString());
            return;
        }
        if(! json["success"].toBool()) {
            QMessageBox::warning(gMainWin, tr("Tip Info"), tr("Fail"));
            return;
        }
        if(json["result"].toBool()) mLedCard->m_bLockStatus = false;
        else {
            mLedCard->m_bLockStatus = true;
            QMessageBox::warning(gMainWin, tr("Tip Info"),tr("password is wrong"));
        }
        SetPasswordItem(mLedCard);
    });
}
void wProgramPublishItem::SetPasswordItem(LedCard *card) {
    if(! card->bPassword) return;
    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, ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT, m_bnLock);
        connect(m_bnLock, SIGNAL(clicked()), this, SLOT(onVerifyLockPassword()));
    }
    m_bnLock->setIcon(QIcon(card->m_bLockStatus ? ":/res/device/Lock.png" : ":/res/device/UnLock.png")); //如果已经验证通过密码显示绿色图标 没有验证显示蓝色锁图标
    m_parent->setItemWidget(this, ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT, m_bnLock);
}

void wProgramPublishItem::SetItemParam(LedCard *p) {
    setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID, 0, p->m_strCardId);
    setData(ENUM_DEVICE_PUBLISH_HEADE_REMARK_NAME, 0, p->m_strCardRemarkName);
    setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_IP, 0, p->m_strCardIp);
    setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_SIZE, 0, QString("%1 x %2").arg(p->m_iWidth).arg(p->m_iHeight));
    m_ImageOnline->setPixmap(QPixmap(mLedCard->m_bOnLine ? ":/res/device/O_Online.png" : ":/res/device/O_Offline.png"));
    SetPasswordItem(mLedCard);

//    //progresss.append(progress);
//    QTableWidgetItem *topLevelItem = new QTableWidgetItem();     //创建一个 TreeItem 容器用于后来装载控件
//    topLevelItem->setData(0,listProgramName->at(i));
//    topLevelItem->setFlags(topLevelItem->flags() & ~Qt::ItemIsEnabled & ~Qt::ItemIsSelectable);
//    /*上面用到的两个枚举中：~Qt::ItemIsEnabled可以保证单击该Item时不会被选中，但是在启用Ctrl + A时，全选操作会导致Item被选中。
//     * ~Qt::ItemIsSelectable的使用可以保证全选状态下也不会被选中，但是在单独使用时出现了虚线框，没有真正实现“不存在”的效果。所以必须两个同用。*/
//    ctrlProgramList->setItem(i,0,topLevelItem);
//    ctrlProgramList->setCellWidget(i, 1, progress);
}
