#include "mysock.h"

mySock::mySock(QObject *parent) : QThread(parent),quit(false)
{
    hostName = "127.0.0.1";
    port = 34952;

    qRegisterMetaType<mySock::RequstType>("mySock::RequstType");

    connect( this, &mySock::error, this, &mySock::threadQuitErr);
}

int ZH_caclChkValue(char * pJsonData, int startPos, int endPos)
{
    int value = 0, loop = startPos, count = 0;
    for (; loop < endPos; loop++)
    {
        if( pJsonData[loop] == '"' || pJsonData[loop] == '\'')
            continue;

        if (2 > count){
            value += (int)pJsonData[loop];
        }
        else if  (2 == count){
            value *= (int)pJsonData[loop];

        }else{
            value -= (int)pJsonData[loop];
        }
        count = (count + 1) & 3;
    }
    return value;
}

QByteArray checkSendArray( QByteArray & jsonArray)
{
    char* tmpBuf = new char[ jsonArray.size() + 50];

    strcpy(tmpBuf, jsonArray.data());

    int strLength = strlen(tmpBuf);

    while('}' != tmpBuf[strLength - 1])
    {
        strLength--;
    }
    strLength--;

    sprintf(tmpBuf + strLength, ", \"checkValue\":");

    int aLength = strlen(tmpBuf + strLength);

    int nValue = ZH_caclChkValue( tmpBuf, 0, strLength + 2);
    strLength += aLength;

    sprintf(tmpBuf + strLength, " %d", nValue);

    aLength = strlen(tmpBuf + strLength);

    strLength += aLength;

    tmpBuf[strLength] = '}';
    tmpBuf[strLength + 1] = '\0';
    strLength ++;

    QByteArray array(tmpBuf);

    return array;
}

void mySock::threadQuitErr(int socketError, const QString &message)
{
    Q_UNUSED(socketError);
    Q_UNUSED(message);
    emit sgThreadBegin(false);
}

void mySock::getNewJosn(const RequstType type, const QJsonObject &json)
{
    QMutexLocker locker(&mutex);  //锁

    emit sgThreadBegin(true);

    QJsonDocument doc(json);
    QByteArray array = doc.toJson( QJsonDocument::Compact);

    qDebug() << array;
    sendArray = checkSendArray( array);
    reType = type;

    if( !isRunning()){
        qDebug() << "stra";
        start();
    }else{
        cond.wakeOne();
        qDebug() << "wakeOne";
    }
}

bool mySock::isFullJson(const QByteArray &array)
{
    QJsonParseError json_error;

    QJsonDocument::fromJson( array, &json_error);

    return  (json_error.error == QJsonParseError::NoError);
}

QJsonObject mySock::getReturnJsonObject(const QByteArray &array)
{
    QJsonDocument doc = QJsonDocument::fromJson( array);

    return doc.object();
}


void mySock::run()
{
    mutex.lock();
    QString serverName = hostName;
    quint16 serverPort = port;
    mutex.unlock();
    const int Timeout = 60 * 1000;
    QTcpSocket socket;
    while( !quit){            

        //连接
        socket.connectToHost(serverName, serverPort);
        if (!socket.waitForConnected(Timeout)) {
            emit error(socket.error(), socket.errorString());
            return;
        }
        //发送
        /*int wLen = */socket.write( sendArray);
        if ( !socket.waitForBytesWritten( Timeout)){
            emit error( socket.error(), socket.errorString());
            return;
        }
        //接受
        QByteArray receArray;
        do{
            if (!socket.waitForReadyRead(Timeout)) {
                emit error(socket.error(), socket.errorString());
                return;
            }

            receArray.append( socket.readAll());
            qDebug()<< "receArray" << receArray;

        }while( !isFullJson( receArray));
        socket.close();

        const QJsonObject returnJson = getReturnJsonObject( receArray);
        mutex.lock();
        emit sgReturnJson( reType, returnJson);   //将数据返回给界面
        emit sgThreadBegin(false);
        qDebug()<<"returnJson" << returnJson;

        cond.wait(&mutex);
        mutex.unlock();
    }
}

mySock * g_sock = NULL;

mySock *getMySock()
{
    if( g_sock == NULL)
        g_sock = new mySock(qApp);

    return g_sock;
}



