#include "TcpClient.h"
//#include "mainWindow.h"
TcpClient::TcpClient(QObject *parent)
    : QObject(parent)
{
    m_heartbeatTimer = new QTimer(this); //心跳包定时器
    connect(&m_tcpSocket, &QTcpSocket::readyRead, this, &TcpClient::onReadyRead);
    connect(m_heartbeatTimer, &QTimer::timeout, this, &TcpClient::sendHeartbeat);//心跳包
    connect(&m_tcpSocket, &QTcpSocket::connected, this, &TcpClient::handleConnected);
    connect(&m_tcpSocket, &QTcpSocket::disconnected, this, &TcpClient::handleDisconnected);
}

void TcpClient::connectToServer(const QString &host, int port)
{
    m_host = host;
    m_port = port;
    m_tcpSocket.connectToHost(host,port); // Replace with actual server IP and port

}

void TcpClient::onReadyRead()
{

    QByteArray jsonData = m_tcpSocket.readAll();
//    qDebug()<< jsonData <<Qt::endl;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(jsonData);
    if ( jsonDocument.isObject()) {
        QJsonObject jsonObject = jsonDocument.object();
        QString t = jsonObject["cometime"].toString();
          io_car = jsonObject["type"].toString();
          direction = jsonObject["direction"].toString();
          qDebug() << "direction" << direction << "\n";
           if((io_car !="0" && io_car!="1") ||(direction != "0" && direction !="1" && direction !="2") )
           {
               QJsonObject jsonObject;
               jsonObject["success"] ="false";
               jsonObject["err_msg"] = "type or direction value is err...";
               QJsonDocument jsonDocument(jsonObject);
               QByteArray jsonData = jsonDocument.toJson();

               m_tcpSocket.write(jsonData);
           }
           else
           {
               QJsonObject jsonObject;
               jsonObject["success"] = "true";
               jsonObject["err_msg"] = "";
               QJsonDocument jsonDocument(jsonObject);
               QByteArray jsonData = jsonDocument.toJson();
               m_tcpSocket.write(jsonData);
           }

//        // Process received JSON data
//        // ...
        qDebug()<< jsonData <<"  "<< io_car<<" "<< direction<<" "<< t  << "\n"<<Qt::endl;
   }
}
void TcpClient::sendHeartbeat()
{
    if (m_tcpSocket.state() == QAbstractSocket::ConnectedState) {
        // 发送心跳包

        //QByteArray heartbeatData = "matrixai";
       // std::string head = "matrixai";
        m_tcpSocket.write("matrixai");

    }
}
void TcpClient::reconnect()
{
    if (m_tcpSocket.state() != QAbstractSocket::ConnectedState) {
        // 断线重连
        m_tcpSocket.connectToHost("127.0.0.1",7000);
    }
}
void TcpClient::handleConnected()
{
    if (!m_heartbeatTimer->isActive()) {
        // 心跳包定时器启动
        m_heartbeatTimer->start(3000);
    }
}

void  TcpClient::handleDisconnected()
{
    if (m_heartbeatTimer->isActive()) {
        // 停止发送心跳包
        m_heartbeatTimer->stop();
    }

    // 5秒后尝试重新连接
    QTimer::singleShot(5000, this, &TcpClient::reconnect);
}
