#include "ctrlpwdpanel.h"
#include "gutil/qgui.h"
#include "base/waitingdlg.h"
#include "QFileDialog"
#include <QMessageBox>
#include <QJsonObject>
#include <globaldefine.h>
#include "tools.h"

CtrlPwdPanel::CtrlPwdPanel(QWidget *parent) : QWidget(parent) {
    auto vBox = new VBox(this);
    lbPwdConfig = new QLabel;
    lbPwdConfig->setAlignment(Qt::AlignCenter);
    vBox->addWidget(lbPwdConfig);
    vBox->addSpacing(20);

    auto grid = new Grid(vBox);
    grid->setColumnStretch(0, 1);
    grid->setColumnStretch(3, 1);

    lbOldPwd = new QLabel;
    grid->addWidget(lbOldPwd, 0, 1);

    lbNewPwd = new QLabel;
    grid->addWidget(lbNewPwd, 1, 1);

    lbPwdAgain = new QLabel;
    grid->addWidget(lbPwdAgain, 2, 1);

    fdOldPwd = new QLineEdit;
    fdOldPwd->setFixedSize(160, 30);
    fdOldPwd->setEchoMode(QLineEdit::PasswordEchoOnEdit);
    grid->addWidget(fdOldPwd, 0, 2);

    fdNewPwd = new QLineEdit;
    fdNewPwd->setFixedSize(160, 30);
    fdNewPwd->setEchoMode(QLineEdit::PasswordEchoOnEdit);
    grid->addWidget(fdNewPwd, 1, 2);

    fdPwdAgain = new QLineEdit;
    fdPwdAgain->setFixedSize(160, 30);
    fdPwdAgain->setEchoMode(QLineEdit::PasswordEchoOnEdit);
    grid->addWidget(fdPwdAgain, 2, 2);

    vBox->addSpacing(20);

    auto hBox = new HBox(vBox);
    hBox->addStretch();

    btnPwdSet = new QPushButton;
    btnPwdSet->setMinimumSize(60, 30);
    btnPwdSet->setProperty("ssType", "progManageTool");
    connect(btnPwdSet, &QPushButton::clicked, this, [this] {
        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        if(fdOldPwd->isVisible() && fdOldPwd->text().isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("InputOriginalPasswordTip"));
            return;
        }
        if(fdNewPwd->text().isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("InputNewPasswordTip"));
            return;
        }
        if(fdPwdAgain->text().isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("InputRepeatPasswordTip"));
            return;
        }
        if(fdNewPwd->text() != fdPwdAgain->text()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("InputRepeatPasswordNotSameTip"));
            return;
        }
        auto res = QMessageBox::information(gMainWin, tr("Tip Info"), tr("After setting the password, please remember the password and record it. If you forget the password, the device will be unable to operate. Are you sure you want to continue with this operation?"), QMessageBox::Ok, QMessageBox::Cancel);
        if(res != QMessageBox::Ok) return;
        QJsonObject json;
        json.insert("_id", "SetControllerPassword");
        json.insert("_type", "SetControllerPassword");
        json.insert("pwd", fdOldPwd->text());
        json.insert("newPwd", fdNewPwd->text());
        if(gSelCards->count() == 1) {
            auto waitingDlg = new WaitingDlg(this, tr("SetControllerPassword")+" ...");
            Def_CtrlReqPre
            connect(reply, &QNetworkReply::finished, card, [=] {
                QJsonDocument json;
                QString err = checkReplyForJson(reply, &json);
                if(! err.isEmpty()) {
                    waitingDlg->close();
                    QMessageBox::critical(gMainWin, tr("Error"), err);
                    return;
                }
                if(json["result"].toInt()) {
                    waitingDlg->close();
                    QMessageBox::critical(gMainWin, tr("Tip"), tr("OriginalPasswordErrorTip"));
                    return;
                }
                waitingDlg->success();
                lbOldPwd->show();
                fdOldPwd->show();
                btnPwdClear->show();
                btnPwdSet->setText(tr("Modify password"));
                card->bPassword = true;
                fdNewPwd->clear();
                fdPwdAgain->clear();
                fdOldPwd->clear();
            });
        } else {
            foreach(auto card, *gSelCards) {
                auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
                connect(reply, &QNetworkReply::finished, card, [=] {
                    QJsonDocument json;
                    QString err = checkReplyForJson(reply, &json);
                    if(err.isEmpty()) {
                        if(json["result"].toInt()) err = tr("OriginalPasswordErrorTip");
                        else {
                            err = tr("Success");
                            lbOldPwd->show();
                            fdOldPwd->show();
                            btnPwdClear->show();
                            btnPwdSet->setText(tr("Modify password"));
                            card->bPassword = true;
                        }
                    }
                    gFdResInfo->append(card->m_strCardId+" "+tr("SetControllerPassword")+" "+err);
                });
            }
        }
    });
    hBox->addWidget(btnPwdSet);

    btnPwdClear = new QPushButton;
    btnPwdClear->setMinimumSize(60, 30);
    btnPwdClear->setProperty("ssType", "progManageTool");
    connect(btnPwdClear, &QPushButton::clicked, this, [this] {
        if(gSelCards->isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("NoSelectedController"));
            return;
        }
        if(fdOldPwd->isVisible() && fdOldPwd->text().isEmpty()) {
            QMessageBox::information(gMainWin, tr("Tip"), tr("InputOriginalPasswordTip"));
            return;
        }
        QJsonObject json;
        json.insert("_id", "SetControllerPassword");
        json.insert("_type", "SetControllerPassword");
        json.insert("pwd", fdOldPwd->text());
        json.insert("newPwd","");
        if(gSelCards->count() == 1) {
            auto waitingDlg = new WaitingDlg(this, tr("SetControllerPassword")+" ...");
            Def_CtrlReqPre
            connect(reply, &QNetworkReply::finished, card, [=] {
                QJsonDocument json;
                QString err = checkReplyForJson(reply, &json);
                if(! err.isEmpty()) {
                    waitingDlg->close();
                    QMessageBox::critical(gMainWin, tr("Error"), err);
                    return;
                }
                if(json["result"].toInt()) {
                    waitingDlg->close();
                    QMessageBox::critical(gMainWin, tr("Tip"), tr("OriginalPasswordErrorTip"));
                    return;
                }
                waitingDlg->success();
                lbOldPwd->hide();
                fdOldPwd->hide();
                btnPwdClear->hide();
                btnPwdSet->setText(tr("Set encryption"));
                card->bPassword = false;
                fdNewPwd->clear();
                fdPwdAgain->clear();
                fdOldPwd->clear();
            });
        } else {
            foreach(auto card, *gSelCards) {
                auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
                connect(reply, &QNetworkReply::finished, card, [=] {
                    QJsonDocument json;
                    QString err = checkReplyForJson(reply, &json);
                    if(err.isEmpty()) {
                        if(json["result"].toInt()) err = tr("OriginalPasswordErrorTip");
                        else {
                            err = tr("Success");
                            lbOldPwd->hide();
                            fdOldPwd->hide();
                            btnPwdClear->hide();
                            btnPwdSet->setText(tr("Set encryption"));
                            card->bPassword = false;
                        }
                    }
                    gFdResInfo->append(card->m_strCardId+" "+tr("SetControllerPassword")+" "+err);
                });
            }
        }
    });
    hBox->addWidget(btnPwdClear);
    hBox->addStretch();

    vBox->addStretch();

    connect(gDevicePanel, &DevicePanel::sigSelectedDeviceList, this, [this] {
        if(isVisible()) init();
    });
    transUi();
}

void CtrlPwdPanel::showEvent(QShowEvent *event) {
    QWidget::showEvent(event);
    init();
}
void CtrlPwdPanel::init() {
    bool isSingle = gSelCards->count()==1;
    if(! isSingle) return;
    auto card = gSelCards->at(0);

    QJsonObject json;
    json.insert("_id", "HasControllerPassword");
    json.insert("_type", "HasControllerPassword");
    auto reply = Tools::netManager().post(reqForJson("http://"+card->m_strCardIp+":2016/settings"), QJsonDocument{json}.toJson(QJsonDocument::Compact));
    connect(reply, &QNetworkReply::finished, card, [=] {
        QJsonDocument json;
        QString err = checkReplyForJson(reply, &json);
        if(! err.isEmpty()) return;
        if(json["result"].toBool()) {
            lbOldPwd->show();
            fdOldPwd->show();
            btnPwdClear->show();
            btnPwdSet->setText(tr("Modify password"));
            card->bPassword = true;
        } else {
            lbOldPwd->hide();
            fdOldPwd->hide();
            btnPwdClear->hide();
            btnPwdSet->setText(tr("Set encryption"));
            card->bPassword = false;
        }
    });
}
void CtrlPwdPanel::changeEvent(QEvent *event) {
    QWidget::changeEvent(event);
    if(event->type() == QEvent::LanguageChange) transUi();
}
void CtrlPwdPanel::transUi() {
    lbPwdConfig->setText(tr("Set Password"));
    lbOldPwd->setText(tr("Original password"));
    lbNewPwd->setText(tr("New password"));
    lbPwdAgain->setText(tr("Enter again"));
    fdOldPwd->setPlaceholderText(tr("original password"));
    fdNewPwd->setPlaceholderText(tr("New password"));
    fdPwdAgain->setPlaceholderText(tr("Repeat new password"));
    btnPwdSet->setText(tr("Set encryption"));
    btnPwdClear->setText(tr("Cancel encryption"));
}
