#include "websocketclient.h"

union FC {
    float f;
    unsigned char c[4];
};

WebsocketClient::WebsocketClient(QWebSocket *so,QObject *parent) : QObject(parent)
{
    m_client = so;
    connect(m_client,&QWebSocket::textMessageReceived,this,&WebsocketClient::processTextMessage);
    connect(m_client,&QWebSocket::disconnected,this,&WebsocketClient::socketDisconnected);

}

WebsocketClient::~WebsocketClient()
{
    m_client->abort();
    m_client->deleteLater();
    emit closed();
}

void WebsocketClient::socketDisconnected()
{
    m_client->abort();
    m_client->deleteLater();
    emit closed();
}

void WebsocketClient::processTextMessage(QString message)
{
    union FC fc;
    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(message.toUtf8(),&json_error));
    if(json_error.error == QJsonParseError::NoError){
        QJsonObject obj = jsonDoc.object();
        int datatype = obj.value("dataType").toInt();
        int devicetype = obj.value("deviceType").toInt();
        QString pointData = obj.value("dataMessage").toString();
        QString type = obj.value("type").toString();
        QString checkRsa = this->rsa_pri_decrypt_base64(type);
        if(checkRsa.compare("usky20221018")==0){
            QByteArray data = QByteArray::fromHex(pointData.toLatin1());
            QString temp;
            for(int i=0;i<data.length();i++){
                temp.append(QString(" %1").arg(data.at(i)&0xff,2,16,QChar('0')));
            }
            if((data[12]&0xff)==0x44){
                QJsonDocument jdoc;
                QJsonObject root;

                int IdLen = ((data[13]&0x00ff)<<8)|(data[14]&0x00ff);

                for(int j=0;j<32;j++){
                    for(int i=0;i<4;i++)
                        fc.c[3-i] = data[IdLen+16+4*j+i]&0xff;
                    float RealVal = fc.f;
                    root.insert(QString("point%1").arg(j),QJsonValue(static_cast<float>(RealVal)));
                }
                jdoc.setObject(root);
                m_client->sendTextMessage(QString(jdoc.toJson()));
            }
        }else{
            m_client->abort();
            m_client->deleteLater();
            emit closed();
        }

    }

}

QString WebsocketClient::rsa_pri_decrypt_base64(const QString &strDecryptData)
{
    char private_key[] = "-----BEGIN PRIVATE KEY-----\n"\
            "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAL0aOI/LPcV8dwQA\n"\
            "m7maBiRoDK3GzWRJEiDuP2cUHhxQ4qfl+WxPAeOf6VHkPQxVzjFL2C0QKA4wmxrO\n"\
            "qzEXfkvlMpaLQaJfnPD02FDPou/o/fSZybmYmzZQc7J6qvuu0NCflS6ftD1x/KZB\n"\
            "D6WfsjnisKsaFOuRDMzDz6+FNU8pAgMBAAECgYAsJCzD1AttR+p4MrQnFP8ODIO5\n"\
            "JMjY+f2TVknSg+2ram4eBx67241zVuadyQs/D+B7vVqO2lCfT1VFYqyvXu6J3YX0\n"\
            "yagkQRiVLJLSMmP14ZCOlVA6jmit0MnMxG0XZltWnjpWyMmlGiNFnmK1Y84b913W\n"\
            "k1H0mXKnCV2v5xD0AQJBAPQitqPCEPtLECXzdw3DBKNj8w1ldMNHU61dGKF/xDsQ\n"\
            "6pbX5UZGeHBueqGKB2VqFFMtND6IlEVZ9kVTN1VIYEECQQDGStc+EMn3Xbixk2Al\n"\
            "cMyfbGtpRQuGUk77uBf0HP7VMoL5j+t8KW3KflgKnY1AJa2VxoCk/Fx1tsdu2CbY\n"\
            "qLTpAkAZ9PbmQmP70+dLoa8uz2VW2fGlovvfJ15GOHe99A+xGANZNmsyJZv4mEaB\n"\
            "lmNi7PxsO4oqe+sH1KDSjh57+s4BAkEAp9YK73aobB7AyFT0iVw7ZikPlS+ivJOI\n"\
            "VNkSNUYhj/TMFU3yxMoQKtfbz0hhmU0K6v30PzF3VQ9bKH/+CV5qmQJBAKhH5m6E\n"\
            "af/baa6dQJbCCS8aVeiFe0AAUQKamAjkRdfUa1/W6O71A3ePsr41l0X4TGpXPapG\n"\
            "dc/Ul5Q8wSTXkYE=\n"\
            "-----END PRIVATE KEY-----";

    BIO *pKeyBio = BIO_new_mem_buf(private_key,strlen(private_key));
    if(pKeyBio == NULL)
    {
        return "";
    }

    RSA *pRsa = RSA_new();
    pRsa = PEM_read_bio_RSAPrivateKey(pKeyBio,&pRsa,NULL,NULL);
    if(pRsa == NULL){
        BIO_free_all(pKeyBio);
        return "";
    }
    int nLen = RSA_size(pRsa);
    char *pClearBuf = new char[nLen];
    memset(pClearBuf,0,nLen);
    //解密
    QByteArray decryptDataArry = strDecryptData.toUtf8();
    decryptDataArry = QByteArray::fromBase64(decryptDataArry);
    int nDecryptDataLen = decryptDataArry.length();
    uchar *pDecryptData = (uchar*)decryptDataArry.data();
    int nSize = RSA_private_decrypt(nDecryptDataLen,pDecryptData,(uchar*)pClearBuf,pRsa,RSA_PKCS1_PADDING);
    QString strClearData = "";
    if(nSize >= 0){
        strClearData = QByteArray(pClearBuf,nSize);
    }

    delete[] pClearBuf;
    BIO_free_all(pKeyBio);
    RSA_free(pRsa);


    return strClearData;
}





