#ifndef TCPSOCKETHELPER_H
#define TCPSOCKETHELPER_H

#include <QObject>
#include <QTcpSocket>
#include <QTimer>
#include <windows.h>
#include "TCPSocketHelper/CJsonObject.h"
#include "TCPSocketHelper/cJSON.h"
#include "vehinfo.h"
using namespace std;
using namespace neb;
class TCPSocketHelper : public QObject
{
    Q_OBJECT
public:
    explicit TCPSocketHelper(QObject *parent = nullptr);
    ~TCPSocketHelper();
    using SocketState = QAbstractSocket::SocketState;
    enum MessageTypes {
        LatencyTest,                 //服务器测速
    };
    Q_ENUM(MessageTypes)
    void setHostAndePort(const QString &m_ServerHost,const int &m_ServerPort);
    void closeTCPSocker();//TCPSocket 默认启动,用此函数可以停止 TCP 连接,它会直接关掉 Socket ,并置 isClose 为真,以关闭心跳检查,防止自动重连机制恢复连接.
    void openTCPSocket();
    SocketState getSocketStatus(){
        return m_TCPSocket->state();
    }

signals:
    void ResponseData(MessageTypes,short,QByteArray);
    void ResponseInfoData(MessageTypes,short,QByteArray);
    void TCPSocketIsConnected();
    void TCPSocketIsDisconnected();
    void TCPSocketUnstable();

public slots:
    ///站点注册
    void Register();
    ///绑定
    void Binding(QString epc,QString carPlnum);
private slots:
    void onConnected();
    void onReadyRead(); //负责接收数据,并缓存以及验证这些数据.
    void onDisconnected();
    void checkHeartBeat();  //心跳检查

private:
    ///获取 opcode ,(有待优化) <--- opcode
    char getOpCode(const QByteArray& Arr);
    bool writeData(const QByteArray& payloadData);
    ///设置套接字关闭标志
    void setCloseFlag(bool _isClose){
        m_CloseFlag = _isClose;
    }

    ///获取套接字关闭标志
    bool getCloseFlag(){
        return m_CloseFlag;
    }

    ///心跳标记
    void setHeartBeatFlag(bool _Flag){m_heartbeatFlag = _Flag;}
    ///获取心跳标记
    bool getHeartBeatFlag(){return m_heartbeatFlag;}
    ///发送一个ping
    void sendPing();
    ///按照 OPCode 分类
    void classifyByOPCode(const QByteArray& Arrtmp);

    //心跳测试
    QByteArray Send_HeartBeat_rv(PacketHeartBeat &heartBeat);
    //注册
    QByteArray Send_Register(PacketRegister &m_register);
    QByteArray Send_Binding(PacketBinding &form);
    string MD5(CJsonObject cj,string key);
private:
    QTcpSocket *m_TCPSocket = nullptr;
    bool m_tcpServerStatus = true;
    QTimer *m_tcpServerTimer;   //定时重连服务器


    QTimer *m_HeartBeatTimer;   //心跳定时

    QString m_ServerHost = "127.0.0.1";
    quint16 m_ServerPort = 40008;
    int m_LossCount = 0;
    bool m_heartbeatFlag = true;
    bool m_CloseFlag = false;
    QByteArray m_ArrBuff;
};

#endif // TCPSOCKETHELPER_H
