#include "TcpClient.h"
#include <QHostAddress>
#include <QDebug>

TcpClient::TcpClient(QObject *parent)
    : QObject(parent)
    , m_socket(new QTcpSocket(this))
{
    // 连接信号槽
    connect(m_socket, &QTcpSocket::connected, this, &TcpClient::onConnected);
    connect(m_socket, &QTcpSocket::disconnected, this, &TcpClient::onDisconnected);
    connect(m_socket, &QTcpSocket::readyRead, this, &TcpClient::onReadyRead);
    connect(m_socket, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error),
                this, &TcpClient::onErrorOccurred);
}

TcpClient::~TcpClient()
{
    disconnectFromServer();
}

void TcpClient::connectToServer(const QString &host, quint16 port)
{
    qDebug() << "正在连接到服务器:" << host << ":" << port;
    m_socket->connectToHost(host, port);
}

void TcpClient::sendMessage(const QJsonObject &message)
{
    if (m_socket->state() != QAbstractSocket::ConnectedState) {
        qWarning() << "未连接到服务器，无法发送消息";
        return;
    }

    // 将JSON对象转换为字符串
    QJsonDocument doc(message);
    QString jsonString = doc.toJson(QJsonDocument::Compact);

    // 添加换行符作为消息结束标记（根据你的服务端实现）
    jsonString += "\n";

    // 发送消息
    qint64 bytesWritten = m_socket->write(jsonString.toUtf8());
    if (bytesWritten == -1) {
        qWarning() << "发送消息失败";
    } else {
        qDebug() << "消息发送成功，字节数:" << bytesWritten;
        qDebug() << "发送的内容:" << jsonString.trimmed();
    }
}

void TcpClient::disconnectFromServer()
{
    if (m_socket->state() == QAbstractSocket::ConnectedState) {
        m_socket->disconnectFromHost();
    }
}

void TcpClient::onConnected()
{
    qDebug() << "成功连接到服务器";
    emit connected();
}

void TcpClient::onDisconnected()
{
    qDebug() << "与服务器断开连接";
    emit disconnected();
}

void TcpClient::onReadyRead()
{
    QByteArray data = m_socket->readAll();
    m_buffer.append(data);

    qDebug() << "接收到服务器响应:" << data;

    // 简单的消息分割（根据你的服务端实现调整）
    while (m_buffer.contains('\n')) {
        int endIndex = m_buffer.indexOf('\n');
        QByteArray messageData = m_buffer.left(endIndex).trimmed();
        m_buffer = m_buffer.mid(endIndex + 1);

        // 解析JSON响应
        QJsonParseError parseError;
        QJsonDocument doc = QJsonDocument::fromJson(messageData, &parseError);

        if (parseError.error == QJsonParseError::NoError && doc.isObject()) {
            QJsonObject jsonObj = doc.object();
            emit messageReceived(jsonObj);
            qDebug() << "解析服务器响应成功:" << jsonObj;
        } else {
            // 如果不是JSON，直接作为字符串处理
            QString response = QString::fromUtf8(messageData);
            qDebug() << "服务器响应:" << response;
        }
    }
}

void TcpClient::onErrorOccurred(QAbstractSocket::SocketError error)
{
    QString errorString = m_socket->errorString();
    qWarning() << "Socket错误:" << errorString;
    emit errorOccurred(errorString);
}
