#ifndef Socket_H
#define Socket_H

#include <QThread>
#include <QMutex>
#include <QWaitCondition>
#include <QNetworkAccessManager>

class Socket : public QThread
{
    Q_OBJECT
public:
    explicit Socket(QObject *parent=0);

    typedef enum{Login,SetPosNo,Query,Accpet,
                 Reject,Bind,Consume,Sendout,
                 UpdStock,Finsh,Delivers,AgreeRefund,CancelRefund
    }RequstType;

    typedef enum{TCP,HTTP}AgreementType;

    void setByTcp(QString _hostName, quint16 _port);
    void setByHttp(QString _httpUrl);

//    void getNewJosn(const Socket::RequstType type,  const QJsonObject& json);
    void getNewJosn(const Socket::RequstType type,  const QByteArray &json);


protected:
    void run();

private:
//    bool sendByHttp(QJsonObject &returnJosn);
//    bool sendByTcp(QJsonObject &returnJosn);
    bool sendByHttp(QByteArray &returnJosn);
    bool sendByTcp(QByteArray &returnJosn);

    bool isFullJson( const QByteArray& array);
//    QJsonObject getReturnJsonObject( const QByteArray& array);
//    QString getReturnJsonObject( const QByteArray& array);

    QByteArray getEncodeArray( const QByteArray& array);

    QString hostName;
    quint16 port;
    QString httpUrl;
    //中间数据
    QByteArray sendArray;
    RequstType reType;
    AgreementType agreementType;
    //锁和信号
    QMutex mutex;
    QWaitCondition cond;

    bool quit;
    QNetworkAccessManager *manger;

    int     m_retry_cnt;
    int     m_retry_max;

signals:
    void error(int socketError, const QString &message);
    void    timeout();
//    void recvReturn(const Socket::RequstType type, const QJsonObject& json);
    void recvReturn(const Socket::RequstType type, const QByteArray& json);
};

#endif // Socket_H
