#include "controlencryptwidget.h"
#include "ui_controlencryptwidget.h"
#include "LoUIClass/x_uimsgboxok.h"
#include "LoUIClass/x_uimsgboxokcancel.h"
#include "QFileDialog"
#include "QDir"
#include <QJsonValue>
#include <QJsonObject>
#include <QJsonDocument>
#include <globaldefine.h>
ControlEncryptWidget::ControlEncryptWidget(QWidget *parent,QList<LedCard *> *list) :
    QWidget(parent),
    ui(new Ui::ControlEncryptWidget)
{
    m_pLedlist=list;
    ui->setupUi(this);
    refreshLable();
    ui->pushButtonSetPassword->setProperty("ssType", "progManageTool");
    ui->pushButtonSetPassword->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");
    ui->pushButtonCancelPassword->setProperty("ssType", "progManageTool");
    ui->pushButtonCancelPassword->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");
    //按钮事件绑定
    connect(ui->pushButtonSetPassword,SIGNAL(clicked()),this,SLOT(OnSetPassword()));
    connect(ui->pushButtonCancelPassword,SIGNAL(clicked()),this,SLOT(OnCancelPassword()));
    MARCO_DEFINE_CONTROL_FUNC2(parent->parent(),parent)


//            pHpptClient = new HpptClient(this);
//            connect(pHpptClient,SIGNAL(httpPostRspReady(QString , QString , QByteArray )),this,SLOT(OnProHttpResponse(QString , QString , QByteArray)));
//            pHpptClientAll = new HpptClient(this);
//            connect(pHpptClientAll,SIGNAL(httpPostRspReady(QString , QString , QByteArray )),this,SLOT(OnProHttpResponseAll(QString , QString , QByteArray)));
//            m_pGetAskTimer=new QTimer(this);
//            connect(parent,SIGNAL(sigSwitchIndexChanged(int)),this,SLOT(OnControlTypeSwitchIndexChanged(int)));
//            connect(parent->parent(),SIGNAL(sigSelectedDeviceList(QList<LedCard *> *)),this,SLOT(onSelectedDeviceList(QList<LedCard *> *)));
//            connect(this,SIGNAL(sigSend(QJsonObject &,QString)),parent->parent(),SLOT(OnControlSendJson(QJsonObject &,QString)));
//            connect(parent->parent(),SIGNAL(sigChangeLanguage()),this,SLOT(refreshLable()));
//            onSelectedDeviceList(list);


 }

ControlEncryptWidget::~ControlEncryptWidget()
{
    delete ui;
    if(pHpptClient != nullptr)
    {
        qDebug() <<"delete pHpptClient in ~NetComm";
        delete pHpptClient;
        pHpptClient=nullptr;
    }
    if(pHpptClientAll != nullptr)
    {
        qDebug() <<"delete pHpptClientAll in ~NetComm";
        delete pHpptClientAll;
        pHpptClientAll=nullptr;
    }
}

void ControlEncryptWidget::refreshLable()
{
    ui->labelNewPassword->setText(tr("New password"));
    ui->labelRepeatPassword->setText(tr("Enter password"));
    ui->labelOriginalPassword->setText(tr("original password"));
    ui->labelEntryptConfiguration->setText(tr("Entrypt Configuration"));
    ui->lineEditNewPassword->setPlaceholderText(tr("New password"));
    ui->lineEditRepeatPassword->setPlaceholderText(tr("Repeat new password"));
    ui->lineEditOriginalPassword->setPlaceholderText(tr("original password"));
    ui->pushButtonSetPassword->setText(tr("Set encryption"));
    ui->pushButtonCancelPassword->setText(tr("Cancel encryption"));
}

void ControlEncryptWidget::OnSetPassword()
{
    if(m_pLedlist==nullptr)
        return;
    if(m_pLedlist->count()<=1)
    {
        if(m_pLedCard==nullptr||m_pLedlist->count()==0)
        {
            X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1);
            pDlg->exec();
            return;
        }
    }

    if(ui->lineEditOriginalPassword->isVisible())
    {
        if(ui->lineEditOriginalPassword->text().isEmpty())
        {
            X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("InputOriginalPasswordTip"),this,1);
            pDlg->exec();
            return;
        }
    }

    if(ui->lineEditNewPassword->text().isEmpty())
    {
        X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("InputNewPasswordTip"),this,1);
        pDlg->exec();
        return;
    }
    if(ui->lineEditRepeatPassword->text().isEmpty())
    {
        X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("InputRepeatPasswordTip"),this,1);
        pDlg->exec();
        return;
    }
    if(ui->lineEditNewPassword->text()!=ui->lineEditRepeatPassword->text())
    {
        X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("InputRepeatPasswordNotSameTip"),this,1);
        pDlg->exec();
        return;

    }
    X_UIMsgBoxOkCancel *dlg = new X_UIMsgBoxOkCancel(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?"), this);
    if(dlg->exec() == QDialog::Accepted)
    {
        QJsonObject json;
        json.insert("_id", getRandomString(10));
        json.insert("_type", "SetControllerPassword");
        json.insert("pwd", ui->lineEditOriginalPassword->text());
        json.insert("newPwd", ui->lineEditNewPassword->text());
        MACRO_DEFINE_TIPDLG_FUCN(tr("SetControllerPassword"),tr("Success"),tr("failed"))

    }
    else {

    }



}
void ControlEncryptWidget::OnCancelPassword()
{
    if(ui->lineEditOriginalPassword->isVisible())
    {
        if(ui->lineEditOriginalPassword->text().isEmpty())
        {
            X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("InputOriginalPasswordTip"),this,1);
            pDlg->exec();
            return;
        }
    }
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "SetControllerPassword");
    json.insert("pwd", ui->lineEditOriginalPassword->text());
    json.insert("newPwd","");
    MACRO_DEFINE_TIPDLG_FUCN(tr("SetControllerPassword"),tr("Success"),tr("failed"))
}
void ControlEncryptWidget::onSelectedDeviceList(QList<LedCard*> *list)
{
    m_pLedlist=list;
    if(m_pLedlist==nullptr)
        return;
    MACRO_DEFINE_CONTROL_FUNC3
}
void ControlEncryptWidget::OnControlTypeSwitchIndexChanged(int index)
{
    if(index==ENUM_CONTRL_WIDGET_ENCRYPT)
    {
        m_bSelected=true;
        if(m_pLedCard!=nullptr)
            onReadbackAllThisPage();
    }
    else {
        m_bSelected=false;
    }
}
void  ControlEncryptWidget::onReadbackAllThisPage()
{
    if(m_pLedlist==nullptr)
        return;
    if(m_pLedlist->count()!=1)
        return;
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "HasControllerPassword");
    HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json);
    MACRO_DEFINE_TIPDLG_ALL_FUCN(tr("Readback"),tr("Success"),tr("failed"))
}
//获取到httpPost的应答，如果参数变化需要出发修改控件item的内容
void ControlEncryptWidget::OnProHttpResponse(QString url, QString postMD5, QByteArray data)
{
    Q_UNUSED(postMD5)
    //qDebug()<< url + "\r\n"+m_strUrl;
    if(url == m_strUrl)
    {
        QJsonParseError parseJsonErr;
        QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr);
        if(!(parseJsonErr.error == QJsonParseError::NoError))
        {
            if(data.size()==0)
                qDebug()<<"json is empty";
            else
                qDebug()<<tr("wDevicesItem OnProHttpResponse 解析json文件错误！");
            return;
        }
        QJsonObject jsonObject = document.object();
        QString strType=jsonObject["_type"].toString();
        if(jsonObject["success"].toBool()==true)
        {
            qDebug()<<m_pLedCard->m_strCardId +"---------"+ strType;
            if(strType == "HasControllerPassword")
            {
                if(jsonObject["result"].toBool())
                {//已经加密
                    ui->labelOriginalPassword->show();
                    ui->lineEditOriginalPassword->show();
                    ui->pushButtonCancelPassword->show();
                    ui->pushButtonSetPassword->setText(tr("Modify password"));
                    m_pLedCard->bPassword=true;

                }
                else {//没有加密
                    ui->labelOriginalPassword->hide();
                    ui->lineEditOriginalPassword->hide();
                    ui->pushButtonCancelPassword->hide();
                    ui->pushButtonSetPassword->setText(tr("Set encryption"));
                    m_pLedCard->bPassword=false;
                }
            }
            else if(strType == "SetControllerPassword")
            {
                if(jsonObject["result"].toInt()==0)
                {//原始密码正确
                    QJsonObject json;
                    json.insert("_id", getRandomString(10));
                    json.insert("_type", "HasControllerPassword");
                    HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json);
                    ui->lineEditNewPassword->clear();
                    ui->lineEditRepeatPassword->clear();
                    ui->lineEditOriginalPassword->clear();
                }
                else {//原始密码错误
                    MACRO_ASKTIME_STOP
                     if(m_PostingDlg!=nullptr)
                    {
                        m_PostingDlg->SetFailedTipString(tr("OriginalPasswordErrorTip"));
                        m_PostingDlg->TimerOutUnlock();
                    }
                    ui->lineEditNewPassword->clear();
                    ui->lineEditRepeatPassword->clear();
                    ui->lineEditOriginalPassword->clear();
                    return;

                }
            }
            MACRO_ASKTIME_STOP
            MACRO_POSTING_DLG_UNLOCK

        }
    }
}

//获取到httpPost的应答，如果参数变化需要出发修改控件item的内容
void ControlEncryptWidget::OnProHttpResponseAll(QString url, QString postMD5, QByteArray data)
{
    Q_UNUSED(postMD5)
    //qDebug()<< url + "\r\n"+m_strUrl;
    if(url == m_strUrl)
    {
        QJsonParseError parseJsonErr;
        QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr);
        if(!(parseJsonErr.error == QJsonParseError::NoError))
        {
            if(data.size()==0)
                qDebug()<<"json is empty";
            else
                qDebug()<<tr("wDevicesItem OnProHttpResponse 解析json文件错误！");
            return;
        }
        QJsonObject jsonObject = document.object();
        QString strType=jsonObject["_type"].toString();
        if(jsonObject["success"].toBool()==true)
        {
            qDebug()<<m_pLedCard->m_strCardId +"---------"+ strType;
            if(strType == "HasControllerPassword")
            {
                if(jsonObject["result"].toBool())
                {//已经加密
                    ui->labelOriginalPassword->show();
                    ui->lineEditOriginalPassword->show();
                    ui->pushButtonCancelPassword->show();
                    ui->pushButtonSetPassword->setText(tr("Modify password"));
                    m_pLedCard->bPassword=true;

                }
                else {//没有加密
                    ui->labelOriginalPassword->hide();
                    ui->lineEditOriginalPassword->hide();
                    ui->pushButtonCancelPassword->hide();
                    ui->pushButtonSetPassword->setText(tr("Set encryption"));
                    m_pLedCard->bPassword=false;

                }

            }
            MACRO_ASKTIME_STOP
            MACRO_POSTING_DLG_UNLOCK

        }
    }
}
void ControlEncryptWidget::DeletePostingDlg()
{
    if(m_PostingDlg!=nullptr)
    {
        delete m_PostingDlg;
        m_PostingDlg=nullptr;
    }
}
