#include "clientthread.h"
#include "../AGBoxDog/boxshm.h"
#include "../agVideoProcess/boxdeviceshm.h"

ClientThread::ClientThread(QObject *parent) : QThread(parent)
{
    keep = false;
    CmdList.clear();
    devCode.clear();
    switch_status = 0;
}

void ClientThread::stop()
{
    keep = false;
}

void ClientThread::deviceStatus()
{
    for(int i=0;i<1024;i++){
        if((boxDeviceShm->device[i].Enabled == 0x01)&&(boxDeviceShm->device[i].device_type == 510)){
            int cur=0;
            unsigned char data[256];
            data[cur++] = 0x00;
            data[cur++] = 0x00;
            data[cur++] = 0x00;
            data[cur++] = 0x00;
            data[cur++] = 0x00;
            data[cur++] = 0x06;
            data[cur++] = 0x01;
            data[cur++] = 0x03;

            QByteArray deviceCode = QByteArray::fromHex(QString(boxDeviceShm->device[i].device_code).toLatin1());
            emit dataListLog(QString("deviceCode %1").arg(boxDeviceShm->device[i].device_code));
            printf("deviceCode %s\n",boxDeviceShm->device[i].device_code);
            data[cur++] = deviceCode.at(0)&0xff;
            data[cur++] = deviceCode.at(1)&0xff;
            data[cur++] = 0x00;
            data[cur++] = 0x01;

            QString DataStr;
            QByteArray rtn = QByteArray((const char *)data,12);
            for(int i=0;i<rtn.length();i++){
                DataStr.append(QString("%1").arg(rtn.at(i)&0xff,2,16,QChar('0')));
            }
//            printf("4444 %s\n",DataStr.toUtf8().data());
            CmdList.append(rtn);
        }
    }

}

void ClientThread::controlData(QString deviceId,int switchStatus)
{
    int cur=0;
    unsigned char data[256];
    data[cur++] = 0x00;
    data[cur++] = 0x00;
    data[cur++] = 0x00;
    data[cur++] = 0x00;
    data[cur++] = 0x00;
    data[cur++] = 0x09;
    data[cur++] = 0x01;
    data[cur++] = 0x10;

    for(int i=0;i<1024;i++){
        if(deviceId.compare(boxDeviceShm->device[i].device_id)==0){
            QByteArray deviceCode = QByteArray::fromHex(QString(boxDeviceShm->device[i].device_code).toLatin1());
            emit dataListLog(QString("deviceCode %1").arg(boxDeviceShm->device[i].device_code));
            printf("deviceCode %s\n",boxDeviceShm->device[i].device_code);
            data[cur++] = deviceCode.at(0)&0xff;
            data[cur++] = deviceCode.at(1)&0xff;
            break;
        }
    }

    data[cur++] = 0x00;
    data[cur++] = 0x01;
    data[cur++] = 0x02;
    switch_status = switchStatus;
    if(switchStatus == 1){
        data[cur++] = 0x00;
        data[cur++] = 0x01;
    }else{
        data[cur++] = 0x00;
        data[cur++] = 0x00;
    }


    QString DataStr;
    QByteArray rtn = QByteArray((const char *)data,15);
    for(int i=0;i<rtn.length();i++){
        DataStr.append(QString("%1").arg(rtn.at(i)&0xff,2,16,QChar('0')));
    }
    printf("777777 %s\n",DataStr.toUtf8().data());
    CmdList.append(rtn);
}

void ClientThread::readData(QTcpSocket *so,QString devCode)
{

    QByteArray Rtn = so->readAll();
    QString DataStr;
    for(int i=0;i<Rtn.length();i++){
        DataStr.append(QString("%1").arg(Rtn.at(i)&0xff,2,16,QChar('0')));
    }
    emit dataListLog(QString("[%1] devCode %2 %3").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")).arg(devCode).arg(DataStr));

    if((Rtn.at(7)&0xff) == 0x03){
        for(int i=0;i<1024;i++){
            if(devCode.compare(boxDeviceShm->device[i].device_code)==0){
                int switchStatus = ((Rtn.at(9)&0x00ff)<<8)|(Rtn.at(10)&0x00ff);
                boxDeviceShm->device[i].lastTime = QDateTime::currentDateTime().toTime_t();
                emit mqttData(QString("{\"device_id\":\"%1\",\"device_code\":\"%2\",\"product_id\":\"%3\",\"timestamp\":%4,\"tags\":{\"conn_type\":\"\",\"type\":\"\"},\"metrics\":{\"switch_status\":%5,\"device_status\":1},\"device_type\":\"%6-lg\"}")
                              .arg(boxDeviceShm->device[i].device_id).arg(boxDeviceShm->device[i].device_code).arg(boxDeviceShm->device[i].company_code).arg(QDateTime::currentDateTime().toTime_t()).arg(switchStatus).arg(boxDeviceShm->device[i].device_type));
                break;
            }
        }
    }else if((Rtn.at(7)&0xff) == 0x10){
        for(int i=0;i<1024;i++){
            if(devCode.compare(boxDeviceShm->device[i].device_code)==0){
                boxDeviceShm->device[i].lastTime = QDateTime::currentDateTime().toTime_t();
                emit mqttData(QString("{\"device_id\":\"%1\",\"device_code\":\"%2\",\"product_id\":\"%3\",\"timestamp\":%4,\"tags\":{\"conn_type\":\"\",\"type\":\"\"},\"metrics\":{\"switch_status\":%5,\"device_status\":1},\"device_type\":\"%6-lg\"}")
                              .arg(boxDeviceShm->device[i].device_id).arg(boxDeviceShm->device[i].device_code).arg(boxDeviceShm->device[i].company_code).arg(QDateTime::currentDateTime().toTime_t()).arg(switch_status).arg(boxDeviceShm->device[i].device_type));
                emit responseMsg(QString("{\"code\":\"0\",\"msg\":\"success\",\"data\":\"\"}"));
                break;
            }
        }
    }


}

void ClientThread::run()
{
    bool connect = false;
    keep = true;

    so = new QTcpSocket;
    while (keep) {
        if(!connect){
            so->connectToHost(QHostAddress("172.17.203.45"),502);
            if(so->waitForConnected(3000)){
                printf("connect success\n");
                connect = true;
            }else{
                printf("connect failed\n");
                so->abort();
            }
        }else{
            if(so->waitForReadyRead(100)){
                readData(so,devCode);
            }else if(CmdList.length()>0){
                QByteArray cmd = CmdList.first();
                QString DataStr;
                for(int i=0;i<cmd.length();i++){
                    DataStr.append(QString("%1").arg(cmd.at(i)&0xff,2,16,QChar('0')));
                }
                devCode.clear();
                devCode = (QString("%1%2").arg(cmd.at(8)&0xff,2,16,QChar('0')).arg(cmd.at(9)&0xff,2,16,QChar('0'))).toUpper();
                emit dataListLog(QString("[%1] CmdList.first() %2").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")).arg(DataStr));
                so->write(cmd);
                if(!so->waitForBytesWritten(1000)){
                    so->abort();
                    connect = false;
                }else{
                    CmdList.removeFirst();
                }
            }
        }
        usleep(100000);
    }
}
