#include "HttpUpdateUserInfo.h"

#include <QJsonObject>

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

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

}

void HttpUpdateUserInfo::run()
{
    httpRequestUpdateUserInfo();
}

void HttpUpdateUserInfo::httpRequestUpdateUserInfo()
{
    QJsonObject jsonRoot;
    QDateTime currentDateTime = QDateTime::currentDateTime();
    qint64 timestampSeconds = currentDateTime.toMSecsSinceEpoch();

    QString url = Config()->updatePasswordUrl;
    jsonRoot.insert("avatar", this->m_avatar);
    jsonRoot.insert("email", this->m_email);
    jsonRoot.insert("mobile", this->m_mobile);
    jsonRoot.insert("nickname", this->m_nickname);
    jsonRoot.insert("sex", this->m_sex);

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

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

void HttpUpdateUserInfo::slotHttpResponseUpdateUserInfo(QByteArray data)
{
    QJsonParseError error;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &error);
    if (error.error != QJsonParseError::NoError) {
        emit signalUpdateUserInfoReturnStat(-3, "更新用户信息失败");
        return;
    }
    if(jsonDoc.isNull() || jsonDoc.isEmpty()) {
        emit signalUpdateUserInfoReturnStat(-3, "更新用户信息失败");
        return;
    }

    QJsonObject rootObj = jsonDoc.object();
    if(rootObj.contains("code"))
    {
        int codeValue = rootObj.value("code").toInt();
        if (codeValue == 408) {
            emit signalUpdateUserInfoReturnStat(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 signalUpdateUserInfoReturnStat(0, msg);
        }
        else {
            QString msg = "更新密码失败";
            if (rootObj.contains("msg")) {
                msg = rootObj.value("msg").toString();
            }
            emit signalUpdateUserInfoReturnStat(-3, msg);
        }
    }
}
