#include "tcpclient.h"
#include <QDataStream>
#include "datatype.h"
#include <QDebug>
TcpClient::TcpClient(QObject * parent):QObject (parent)
{
    connect(&m_TcpSocket,SIGNAL(readyRead()),this,SLOT(slotReadMessage()));
    connect(&m_TcpSocket,SIGNAL(disconnected()),this,SLOT(slotDisconnected()));
    // 设置接收缓冲区大小
     int receiveBufferSize = 1024 * 1024; // 1MB
     m_TcpSocket.setSocketOption(QAbstractSocket::ReceiveBufferSizeSocketOption, receiveBufferSize);
}
TcpClient::~TcpClient()
{

    disConnectServer();
    m_isConnected = false;

}
bool   TcpClient::disConnectServer()
{
    if (m_TcpSocket.state() == QAbstractSocket::ConnectedState || m_TcpSocket.state() == QAbstractSocket::ConnectingState)
    {
           qDebug() << "Disconnecting from server...";
           m_TcpSocket.disconnectFromHost();

    }
    else
    {
            qDebug() << "Already disconnected or not connected.";

    }
    m_isConnected = false;
    qDebug()<<"state"<<m_TcpSocket.state()<<endl;
    return m_TcpSocket.state() ==  QAbstractSocket::UnconnectedState;

}

 bool TcpClient::connectServer(QString ip ,qint16 port)
 {

     //直接读取状态，如果连接正常，则直接返回
      if(m_TcpSocket.state()== QAbstractSocket::ConnectedState)
       {
            if(m_TcpSocket.isValid())
            {
                m_isConnected = true;
                return true;
            }
            else
            {
                m_isConnected = false;
                return false;
            }
        }

       //尝试连接
       m_TcpSocket.abort();//取消原有连接
       m_TcpSocket.connectToHost(ip,port);
        if(m_TcpSocket.waitForConnected(1000))
        {
            m_isConnected = true;
        }
        else
        {
             m_isConnected = false;
        }

        return m_isConnected;

 }



bool TcpClient::sendMessage(QByteArray & data)
{

    if(!m_isConnected)
    {
        return false;
    }
    //分包发送
    const int PayloadSize = 64*1024;//一个帧数据包大小
    int totalSize = data.size();
    int bytesWritten = 0;
    int bytesToWrite = totalSize;
    while(bytesWritten<totalSize)
    {
        int startIdx = bytesWritten;
        int length = std::min(PayloadSize,bytesToWrite);
        if(startIdx+length>totalSize)
            return false;

        QByteArray smallBlock = data.mid(startIdx,length);
        qint64 written = m_TcpSocket.write(smallBlock);
        bool success = m_TcpSocket.waitForBytesWritten();

        if(!success)//发送失败包时，停止发送
        {
               return false;
        }

        bytesWritten+=written;
        bytesToWrite-=written;
    }
    m_TcpSocket.flush();

    return true;


}

 QByteArray TcpClient::GetData()
 {

    return QByteArray();
 }
 void   TcpClient::slotTestReadMessage()
 {

     QByteArray temp_BtyeArray = m_TcpSocket.readAll();
     m_msgArray.append(temp_BtyeArray );
     //数据头大小为23个字节
     //数据块长度192或者6
     //剩余部分5
     while(!m_msgArray.isEmpty())
     {
             qint32 allSize = m_msgArray.size();
             //数据头不够
             if (allSize < 23)
             {
                 qDebug()<<"sizeRcre"<<temp_BtyeArray<<endl;
                 return;
             }
             DataPacket dataRec;
             dataRec.deserializeHeader(m_msgArray);
             //数据总数不够
             qint32 dataLength = dataRec.dataLength+23+5;
             if(dataRec.dataLength+23+5 >allSize )
             {
                 qDebug()<<"datalength:"<<dataRec.dataLength<<temp_BtyeArray<<endl;
                 return ;
             }
             dataRec.deserialize(m_msgArray);
             QByteArray readContent = m_msgArray.left(dataLength);
             m_msgArray.remove(0, dataLength);
             emit  SigRectMsg(readContent);
       }

 }
 void  TcpClient::slotReadMessage()
 {
       qDebug()<<m_msgArray.size()<<endl;
     QByteArray temp_BtyeArray = m_TcpSocket.readAll();
     qDebug()<<temp_BtyeArray<<endl;
     qDebug()<<temp_BtyeArray.size()<<endl;
     m_msgArray.append(temp_BtyeArray );
     quint8 frameHeader;       // 帧头 (1 byte)
     quint32 packetSeq;        // 包序号 (4 bytes)
     quint16 dataLength;       // 数据块长度 (2 bytes)
     quint8 batteryLevel;      // 电量 (1 byte)
     quint8 channelCount;      // 通道数量 (1 byte)
     qint16 pitchAngle;        // 俯仰角 (2 bytes)
     qint16 rollAngle;         // 滚动角 (2 bytes)
     qint16 yawAngle;          // 偏航角 (2 bytes)
     quint16 ecg;              // 心电 (2 bytes)
     quint16 spo2;             // 血氧 (2 bytes)
     quint8 reserved1;         // 预留1 (1 byte)
     quint8 reserved2;         // 预留2 (1 byte)
     quint8 reserved3;         // 预留3 (1 byte)
     quint8 reserved4;         // 预留4 (1 byte)

     QByteArray dataBlock;     // 数据块 (192 bytes 或 6 bytes)
     quint8 syncSource;        // 同步触发源 (1 byte)
     quint8 syncSeq;           // 同步触发序号 (1 byte)
     quint8 checksum;          // 校验和 (1 byte)
     quint16 packetTail;       // 包尾 (2 bytes)


     QDataStream in(m_msgArray);
            in.setVersion(QDataStream::Qt_5_13);



     in >>frameHeader>>frameHeader >> packetSeq >> dataLength >> batteryLevel >> channelCount
        >> pitchAngle >> rollAngle >> yawAngle >> ecg >> spo2
        >> reserved1 >> reserved2 >> reserved3 >> reserved4;
    qDebug()<<"---:"<<dataLength<<endl;
     dataBlock.resize(dataLength);
     in.readRawData(dataBlock.data(), dataLength);

     in >> syncSource >> syncSeq;

     in >> checksum;

     in >> packetTail;
     qDebug()<<"getdataLength:"<<dataLength<<endl;
      m_msgArray.remove(0, dataLength+23+5);
 }


 void  TcpClient::slotDisconnected()
 {
        disConnectServer();
 }
 void TcpClient::slotSendMessage(QByteArray & data)
 {
     sendMessage(data);
 }
