#include "devinfotcpserver.h"
#include "../agVideoProcess/boxdeviceshm.h"

DevInfoTcpServer::DevInfoTcpServer(QObject *parent) : QObject(parent)
{
    svr = new QTcpServer(this);
    connect(svr,SIGNAL(newConnection()),this,SLOT(new_incomming()));

    networkManager = new QNetworkAccessManager(this);
    connect(networkManager,SIGNAL(finished(QNetworkReply *)),this,SLOT(finishedSlot(QNetworkReply *)));
}

void DevInfoTcpServer::start()
{
    if(!svr->listen(QHostAddress::Any,15231)){
        printf("devinfo tcp listen 15231 failed\n");
        exit(-1);
    }
    printf("devinfo tcp listen 15231 success\n");
}

void DevInfoTcpServer::finishedSlot(QNetworkReply *reply)
{
    if(reply->error() == QNetworkReply::NoError){
        QString data = QString::fromUtf8(reply->readAll());
        QByteArray ba = data.toLocal8Bit();
        ba = QString::fromLocal8Bit(ba).toUtf8();

        emit tcp_log(QString("[%1] generator devinfo tcp %2").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")).arg(data));

        QJsonParseError json_error;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(ba,&json_error);
        printf("tcpServer parseErr.error %d\n",json_error.error);
        if(json_error.error==QJsonParseError::NoError){
            QJsonObject root = jsonDoc.object();
            QJsonValue data_val = root.value("data");
            QJsonObject data_obj = data_val.toObject();
            QJsonValue list_val = data_obj.value("data");
            QString msg = "";
            QStringList devTcpList;
            if(list_val.isArray()){
                QJsonArray list_array = list_val.toArray();
                for(int i=0;i<list_array.size();i++){
                    QJsonObject list_object = list_array.at(i).toObject();
                    QString device_code = QString::number(list_object.value("id").toInt());
                    QString device_name = list_object.value("name").toString();
                    bool found = false;
                    for(int i=0;i<1024;i++){
                        if((boxDeviceShm->device[i].Enabled == 0x01) && (boxDeviceShm->device[i].device_type == 504)){
                            if(device_code.compare(QString(boxDeviceShm->device[i].device_code))==0){
                                found = true;
                                msg.append(QString("{\"product_id\": \"4\",\"company_code\": \"10000001\",\"device_id\": \"%1\",\"device_code\": \"%2\",\"device_name\": \"%3\",\"flag\": 0},").arg(boxDeviceShm->device[i].device_id).arg(device_code).arg(device_name));
                                break;
                            }
                        }
                    }
                    if(!found){
                        QString device_id = QCryptographicHash::hash(QString("4%1").arg(device_code).toUtf8(),QCryptographicHash::Md5).toHex();
                        QString sql = QString("insert into yt_t_device values('%1','%2',504,'10000001',null);").arg(device_code).arg(device_id);
                        emit append_sql(sql);

                        msg.append(QString("{\"product_id\": \"4\",\"company_code\": \"10000001\",\"device_id\": \"%1\",\"device_code\": \"%2\",\"device_name\": \"%3\",\"flag\": 1},").arg(device_id).arg(device_code).arg(device_name));
                    }
                    devTcpList.append(device_code);
                }
            }


            for(int i=0;i<1024;i++){
                if((boxDeviceShm->device[i].Enabled == 0x01) && (boxDeviceShm->device[i].device_type == 504)){
                    bool found1 = false;
                    QString device_code = QString(boxDeviceShm->device[i].device_code);
                    if(devTcpList.size() > 0){
                        for(int j=0;j<devTcpList.size();j++){
                            if(device_code.compare(devTcpList.at(j))==0){
                                found1 = true;
                                break;
                            }
                        }

                    }
                    if(!found1){
                        QString sql = QString("delete from yt_t_device where device_code = '%1';").arg(device_code);
                        emit append_sql(sql);

                        msg.append(QString("{\"product_id\": \"4\",\"company_code\": \"10000001\",\"device_id\": \"%1\",\"device_code\": \"%2\",\"device_name\": \"\",\"flag\": -1},").arg(boxDeviceShm->device[i].device_id).arg(device_code));
                    }

                }
            }


            msg = msg.left(msg.length()-1);
            QString msgrec = QString("HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-type: text/plain\r\n\r\n{\"code\": \"0\",\"msg\": \"success\",\"data\": [%1]}").arg(msg);
            so->write(msgrec.toUtf8());
            so->close();
        }
    }

    reply->abort();
    reply->deleteLater();
}

void DevInfoTcpServer::new_incomming()
{
    so = svr->nextPendingConnection();
    connect(so,SIGNAL(readyRead()),this,SLOT(read_data()));

}

void DevInfoTcpServer::read_data()
{
    QString str = QString::fromUtf8(so->readAll());
    int begin = str.indexOf("{",0);
    int len = str.length();
    QString datetime = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
    QString data = str.mid(begin,len-begin+1);
    emit tcp_log(QString("[%1] generator deviceinfo tcp %2").arg(datetime).arg(data));
    QByteArray ba = data.toLocal8Bit();
    ba = QString::fromLocal8Bit(ba).toUtf8();

    QJsonParseError parse_error;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(ba,&parse_error);
    printf("tcpserver parse_error %d\n",parse_error.error);
    if(parse_error.error == QJsonParseError::NoError){
        QJsonObject doc = jsonDoc.object();
        QJsonValue param_val = doc.value("params");
        QJsonObject param_obj = param_val.toObject();
        QString sceneId = param_obj.value("scene_id").toString();
        QNetworkRequest *req = new QNetworkRequest();
        req->setUrl(QUrl("http://172.17.200.209:8080/service/page/node.json?paged=1"));
        req->setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
        req->setRawHeader("USER-KEY","426aad8a150a4d85a8fa7221085edca3");
        QString postdata = QString("{\"scene_id\": %1}").arg(sceneId);
        req->setRawHeader("Content_Length",QString("%1").arg(postdata.length()).toUtf8());
        networkManager->post(*req,postdata.toUtf8());

    }


}
