#include "HttpCardLogin.h"

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

#include <QEvent>
#include <QKeyEvent>

#include <unistd.h>
#include <fcntl.h>
#include <cstring>

HttpCardLogin::HttpCardLogin(QObject *parent)
    : QThread(parent)
{
}

void HttpCardLogin::run()
{
    qDebug() << "[HttpCardLogin] 线程启动，cardID:" << m_cardID;
    if (m_cardID.length() > 0 && cardIDToNfc(m_cardID)) {
        qDebug() << "[HttpCardLogin] 卡号转换成功，cardNfc:" << m_cardNfc;
        httpRequestCardLogin();
    } else {
        qDebug() << "[HttpCardLogin] 卡号为空或转换失败，cardID:" << m_cardID;
    }
}

void HttpCardLogin::httpRequestCardLogin()
{
    QJsonObject jsonRoot;
    QDateTime currentDateTime = QDateTime::currentDateTime();
    qint64 timestampSeconds = currentDateTime.toMSecsSinceEpoch();

    QString url = Config()->cardLogin_url;
    jsonRoot.insert("cardNfc", this->m_cardNfc);

    QJsonDocument jsonDoc(jsonRoot);
    QByteArray jsonData = jsonDoc.toJson(QJsonDocument::Compact);
    
    qDebug() << "[HttpCardLogin] 发送登录请求:";
    qDebug() << "[HttpCardLogin]   URL:" << url;
    qDebug() << "[HttpCardLogin]   请求数据:" << QString::fromUtf8(jsonData);
    qDebug() << "[HttpCardLogin]   时间戳:" << timestampSeconds;

    emit signalPostRequestData(timestampSeconds, url, jsonData, NULL, m_accessToken);
    m_cardID = "";
    m_cardNfc = "";
}

bool HttpCardLogin::cardIDToNfc(const QString &cardId)
{
    QString hexStr = QString::number(cardId.toInt(), 16);
    if (hexStr.length() % 2 == 0) {
        for (int i = hexStr.length()/2; i > 0; i--) {
            m_cardNfc = m_cardNfc + hexStr.mid((i-1)*2, 2);
        }
        m_cardNfc = m_cardNfc.toUpper();
        return true;
    }
    return false;
}

void HttpCardLogin::slotHttpResponseCardLogin(QByteArray data)
{
    qDebug() << "[HttpCardLogin] 收到登录响应，数据长度:" << data.length();
    qDebug() << "[HttpCardLogin] 响应数据:" << QString::fromUtf8(data);

    QJsonParseError error;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &error);
    
    // 修复：原逻辑判断条件错误，应该是解析失败时返回错误
    if (error.error != QJsonParseError::NoError) {
        qDebug() << "[HttpCardLogin] JSON解析失败:" << error.errorString();
        GetInteractiveData()->clearToken();
        emit signalLoginReturnStat(-3, "JSON解析失败: " + error.errorString());
        return;
    }

    // 修复：原逻辑判断条件错误，应该是文档为空时返回错误
    if (jsonDoc.isNull() || jsonDoc.isEmpty()) {
        qDebug() << "[HttpCardLogin] JSON文档为空";
        GetInteractiveData()->clearToken();
        emit signalLoginReturnStat(-3, "服务器返回数据为空");
        return;
    }

    QJsonObject rootObj = jsonDoc.object();
    qDebug() << "[HttpCardLogin] 解析JSON对象成功";
    
    if(rootObj.contains("code"))
    {
        int codeValue = rootObj.value("code").toInt();
        qDebug() << "[HttpCardLogin] 响应code:" << codeValue;
        
        if (codeValue == 408) {
            qDebug() << "[HttpCardLogin] 请求超时(408)";
            GetInteractiveData()->clearToken();
            emit signalLoginReturnStat(408, "处理超时，请稍后重试。");
            return;
        }
        if(codeValue == 200 || codeValue == 0)
        {
            if(rootObj.contains("data"))
            {
                QJsonObject vDataObj = rootObj.value("data").toObject();
                if (vDataObj.empty()) {
                    qDebug() << "[HttpCardLogin] data对象为空";
                    GetInteractiveData()->clearToken();
                    emit signalLoginReturnStat(-3, "登录失败：返回数据为空");
                    return;
                }
                if (!vDataObj.contains("accessToken")) {
                    qDebug() << "[HttpCardLogin] 缺少accessToken字段";
                    GetInteractiveData()->clearToken();
                    emit signalLoginReturnStat(-3, "登录失败：缺少accessToken");
                    return;
                }
                QJsonValue value = vDataObj.value("accessToken");
                if(value.type() == QJsonValue::String)
                {
                    GetInteractiveData()->m_token = value.toString();
                    InteractiveHttp::strToken = value.toString();
                    m_accessToken = value.toString();
                    if (vDataObj.contains("refreshToken") && vDataObj.value("refreshToken").type() == QJsonValue::String) {
                        m_refreshToken = vDataObj.value("refreshToken").toString();
                    }
                    QString username = "未知用户";
                    if(vDataObj.contains("nickName"))
                    {
                        QJsonValue name = vDataObj.value("nickName");
                        if(name.type() == QJsonValue::String)
                        {
                            username = name.toString();
                        }
                    }
                    if(vDataObj.contains("userName"))
                    {
                        QJsonValue username = vDataObj.value("userName");
                        if(username.type() == QJsonValue::String)
                        {
                            Config()->username = username.toString();
                        }
                    }
                    if(vDataObj.contains("userId"))
                    {
                        QJsonValue userId = vDataObj.value("userId");
                        if(userId.type() == QJsonValue::String)
                        {
                            Config()->userId = userId.toString();
                        }
                    }
                    Config()->username = username;
                    qDebug() << "[HttpCardLogin] 登录成功，用户名:" << username;
                    emit signalLoginReturnStat(0, "登录成功");
                    emit signalLoginReturnParam(username, 0);
                    m_threadstatus = false;
                }
                else{
                    qDebug() << "[HttpCardLogin] accessToken类型不是字符串";
                    GetInteractiveData()->clearToken();
                    emit signalLoginReturnStat(-3, "登录失败：accessToken格式错误");
                }
            }
            else{
                qDebug() << "[HttpCardLogin] 响应中缺少data字段";
                GetInteractiveData()->clearToken();
                emit signalLoginReturnStat(-3, "登录失败：响应缺少data字段");
            }
        }
        else{
            // 获取服务器返回的错误信息
            QString errorMsg = "用户不存在";
            if (rootObj.contains("msg") && rootObj.value("msg").type() == QJsonValue::String) {
                errorMsg = rootObj.value("msg").toString();
            }
            qDebug() << "[HttpCardLogin] 登录失败，code:" << codeValue << "，msg:" << errorMsg;
            GetInteractiveData()->clearToken();
            emit signalLoginReturnStat(-2, errorMsg);
        }
    }
    else{
        qDebug() << "[HttpCardLogin] 响应中缺少code字段";
        GetInteractiveData()->clearToken();
        emit signalLoginReturnStat(-3, "登录失败：响应格式错误");
    }
}
