#include "HttpUpdateUserPassword.h"

#include <QJsonObject>

#include "../usr/config.h"
#include "../interactive/InteractiveData.h"

HttpUpdateUserPassword::HttpUpdateUserPassword(QObject *parent)
    : QThread(parent)
{

}

void HttpUpdateUserPassword::run()
{
    httpRequestUpdatePassword();
}

void HttpUpdateUserPassword::httpRequestUpdatePassword()
{
    QJsonObject jsonRoot;
    QDateTime currentDateTime = QDateTime::currentDateTime();
    qint64 timestampSeconds = currentDateTime.toMSecsSinceEpoch();

    QString url = Config()->updatePasswordUrl;
    jsonRoot.insert("oldPassword", this->m_oldPassword);
    jsonRoot.insert("newPassword", this->m_newPassword);

    QJsonDocument jsonDoc(jsonRoot);
    QByteArray jsonData = jsonDoc.toJson(QJsonDocument::Compact);

    emit signalPutRequestData(timestampSeconds, url, jsonData, NULL, GetInteractiveData()->m_token);
}

void HttpUpdateUserPassword::slotHttpResponseUpdatePassword(QByteArray data)
{
    QJsonParseError error;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &error);
    if (error.error != QJsonParseError::NoError) {
        emit signalUpdatePasswordReturnStat(-3, "更新密码失败");
        return;
    }
    if(jsonDoc.isNull() || jsonDoc.isEmpty()) {
        emit signalUpdatePasswordReturnStat(-3, "更新密码失败");
        return;
    }

    QJsonObject rootObj = jsonDoc.object();
    if(rootObj.contains("code"))
    {
        int codeValue = rootObj.value("code").toInt();
        if (codeValue == 408) {
            emit signalUpdatePasswordReturnStat(408, "处理超时，请稍后重试。");
            return;
        }
        if(codeValue == 200 || codeValue == 0) {
            QString msg = "更新密码成功";
            if (rootObj.contains("msg")) {
                if (!rootObj.value("msg").toString().isEmpty()) {
                    msg = rootObj.value("msg").toString();
                }
            }
            emit signalUpdatePasswordReturnStat(0, msg);
        }
        else {
            QString msg = "更新密码失败";
            if (rootObj.contains("msg")) {
                if (!rootObj.value("msg").toString().isEmpty()) {
                    msg = rootObj.value("msg").toString();
                }
            }
            emit signalUpdatePasswordReturnStat(-3, msg);
        }
    }
}
