#include "MTcpSocket.h"

MTcpSocket::MTcpSocket(QObject* parent)
    : QObject{ parent }
{
}

MTcpSocket::~MTcpSocket()
{
    releaseSocket();
}

void MTcpSocket::setMsgHandle(MsgHandle handle)
{
    m_msg_handle = handle;
}

void MTcpSocket::sendData(const QString& data)
{
    if (!(m_socket && m_socket->isValid() && m_socket->isWritable())) {
        if (m_is_server)
            initSocket(m_handle);
        else
            connectSocket(m_ip, m_port);
    }
    if (m_socket && m_socket->isValid() && m_socket->isWritable()) {
        qDebug() << "send data: " << data;
        qint64 res = m_socket->write(data.toStdString().c_str(), data.toLocal8Bit().length());
        if (m_socket->waitForBytesWritten(1000) == false)
            emit sendFail();
        //  qDebug() <<"rrrrrrrrrrrrrrrr" <<res;
    } else
        qDebug() << Q_FUNC_INFO << "reconnect failed!";
}

void MTcpSocket::connectSocket(const QString& ip, quint16 port)
{
    if (m_socket)
        releaseSocket();
    createSocket(new QTcpSocket);

    m_socket->connectToHost(ip, port);
    m_socket->waitForConnected(1000);

    m_ip = ip;
    m_port = port;
    m_is_server = false;
}

void MTcpSocket::initSocket(qintptr handle)
{
    if (m_socket)
        releaseSocket();
    createSocket(new QTcpSocket);
    m_socket->setSocketDescriptor(handle);
    m_handle = handle;

    m_is_server = true;
}

void MTcpSocket::readData()
{
    QByteArray rawData = m_socket->readAll();
    QString data = QString::fromLocal8Bit(rawData);

    qDebug() << "原始接收数据:" << data << "长度:" << data.length();

    m_str += data;

    if (m_msg_handle == nullptr) {
        emit recvData(m_str);
        m_str.clear();  // 重要：处理完后清空
        return;
    }

    QString res;
    while ((res = m_msg_handle(m_str, m_head)) != "") {
        qDebug() << "解析出完整消息:" << res;
        emit recvData(res);

        // 重要：从缓存中移除已处理的消息
        // 这里需要根据实际协议来确定移除多少数据
        if (m_str.startsWith(res)) {
            m_str = m_str.mid(res.length());
        } else {
            // 如果不匹配，清空缓存防止循环
            m_str.clear();
            break;
        }
    }

    // 如果缓存过长，清空防止内存泄漏
    if (m_str.length() > 1024) {
        qDebug() << "缓存过长，清空缓存";
        m_str.clear();
    }
}

//void MTcpSocket::readData()
//{
//    QString data = m_socket->readAll();
//    m_str += data;
//    int cur = 0;
//    while((cur = m_str.indexOf(m_head, cur)) != -1)
//    {
//        if(cur + 8 >= m_str.toLocal8Bit().length())
//        {
//            qDebug() << Q_FUNC_INFO << "recv data is not complete! " << data << cur + 8 << m_str.toLocal8Bit().length();
//            m_str.clear();
//            return;
//        }
//        int size = m_str.mid(cur + 4, 4).toInt();
//        if((cur + 8 + size) > m_str.toLocal8Bit().length())
//        {
//            qDebug() << Q_FUNC_INFO << "recv data is not complete! " << data << size << m_str.toLocal8Bit().length();
//            m_str.clear();
//            return;
//        }
//        QString alarm_str = m_str.mid(cur + 8, size);
//        emit recvData(alarm_str);
//        cur += 8 + size;
//    }
//    if(cur == -1)
//        m_str.clear();
//    else
//        m_str = m_str.remove(0, cur);
//}

void MTcpSocket::createSocket(QTcpSocket* socket)
{
    m_socket = socket;
    connect(m_socket, &QTcpSocket::readyRead, this, &MTcpSocket::readData);
    connect(m_socket, &QTcpSocket::disconnected, this, &MTcpSocket::sendFail);
}

void MTcpSocket::releaseSocket()
{
    m_socket->disconnectFromHost();
    delete m_socket;
    m_socket = nullptr;
}
