#include "lotmachine.h"
#include <QTime>
#include <QApplication>

LotMachine::LotMachine(QObject *parent) :
    QObject(parent),
    m_pTcpThread(NULL),
    m_pTcpClient(NULL),
    m_pComThread(NULL),
    m_pComPort(NULL),
    m_startComm(0)
{
    m_receiveBuff.clear();
    m_keyBuff.clear();
    m_reFlag = 0;
    m_connected = 0;
}

LotMachine::~LotMachine()
{
    if (m_startComm != 0)
    {
        if(m_connectMode == USE_TCP_COMM)
        {
            m_pTcpThread->quit();
            m_pTcpThread->wait();
        }
        else if(m_connectMode == USE_SERIAL_COMM)
        {
            m_pComThread->quit();
            m_pComThread->wait();
        }
    }

    if(m_connectMode == USE_TCP_COMM)
    {
        if(m_pTcpThread != NULL)
        {
            delete m_pTcpThread;
        }
    }
    else if(m_connectMode == USE_SERIAL_COMM)
    {
        if(m_pComThread != NULL)
        {
            delete m_pComThread;
        }
    }
}

//初始化通讯连接方式
void LotMachine::initConnectMode(s16 val)
{
    m_connectMode = val;
    if(m_connectMode == USE_TCP_COMM)//网口
    {
        m_pTcpThread = new QThread();
        m_pTcpClient = new GatewayTcpClient();
    }
    else if(m_connectMode == USE_SERIAL_COMM)//串口
    {
        m_pComThread = new QThread();
        m_pComPort = new ComPort();
        connect(m_pComPort, SIGNAL(siSerialPortOpenState(int)), this, SLOT(slotIfOpenSerialPort(int)) );
    }
}

void LotMachine::setConfigFileName(QString configfilename)
{
    m_configFileName = configfilename;
    if(m_connectMode == USE_TCP_COMM)//网口
    {
        m_pTcpClient->setConfigFileName(m_configFileName);
    }
}

//设置串口名称
void LotMachine::setComportName(QString portName)
{
    if(m_pComPort == NULL)
    {
        return;
    }

    if(m_connectMode == USE_SERIAL_COMM)//串口
    {
        m_pComPort->setComPortName(portName);
    }
}

QString LotMachine::getConfigFileName()
{
    return m_configFileName;
}

int LotMachine::startCommunication()
{
    if (m_startComm == 0)
    {
        //   qDebug() << "Machine " << QThread::currentThread();

        if(m_connectMode == USE_TCP_COMM)//网口
        {
            if (m_configFileName.isEmpty())
            {
                qDebug() << "mast call SetConfigFileName first ";
            }

            m_pTcpClient->moveToThread(m_pTcpThread);     // 移动对象到线程中

            //    connect(qApp, SIGNAL(finished()), m_pTcpThread, SLOT(finished()));

            connect(m_pTcpThread, SIGNAL(started()), m_pTcpClient, SLOT(connectToServer()) );
            connect(m_pTcpThread, SIGNAL(finished()), m_pTcpClient, SLOT(deleteLater()) );  // 退出删除对象

            connect(m_pTcpClient, SIGNAL(siConnectSta(int)),
                    this, SLOT(slotConnectSta(int)), Qt::AutoConnection);             // 连接状态改变
            connect(m_pTcpClient, SIGNAL(siConnectErr(QString)),
                    this, SLOT(slotConnectErr(QString)), Qt::AutoConnection);         // 接收到通讯错误
            connect(m_pTcpClient, SIGNAL(siReceiveData(QByteArray)),
                    this, SLOT(slotReceiveData(QByteArray)), Qt::AutoConnection);     // 接收到数据
            connect(this, SIGNAL(siSendData(QByteArray)),
                    m_pTcpClient, SLOT(slotSendData(QByteArray)), Qt::AutoConnection); // 发送数据的槽

            m_pTcpThread->start();    // 启动线程
        }

        if(m_connectMode == USE_SERIAL_COMM)//串口
        {
            m_pComPort->moveToThread(m_pComThread);

            connect(m_pComThread, SIGNAL(started()), m_pComPort, SLOT(initComm()) );
            connect(m_pComThread, SIGNAL(finished()), m_pComPort, SLOT(deleteLater()) );  // 退出删除对象

            connect(m_pComPort, SIGNAL(siReceiveData(QByteArray)),
                    this, SLOT(slotReceiveData(QByteArray)), Qt::QueuedConnection);       // 接收到数据
            connect(this, SIGNAL(siSendData(QByteArray)),
                    m_pComPort, SLOT(slotSendData(QByteArray)), Qt::QueuedConnection); // 发送数据的槽

            m_pComThread->start();  // 启动线程
        }
        m_startComm = 1;
    }
    return m_startComm;
}

// 连接状态改变的槽函数
void LotMachine::slotConnectSta(int sta)
{
    //    qDebug() << "SlotConnectSta" << sta;
    if(m_connected != sta)
    {
        m_connected = sta;
        if(m_connected == 3)//已连接
        {
            emit siConnectToMqtt();
        }
    }
}

// 接收到通讯错误槽函数
void LotMachine::slotConnectErr(QString errinfo)
{
    if(errinfo.length() <= 0){}
    //qDebug() << "SlotConnectErr" << errinfo;
}


// 接收到数据的槽函数
void LotMachine::slotReceiveData(QByteArray dat)
{
    m_receiveBuff.append(dat);
    int size = m_receiveBuff.length();
    QString str = m_receiveBuff;
    if(str == "success")
    {
        m_receiveBuff.remove(0, size);
        return;
    }

    //QString rackNumStr = getJsonValue("device");//机架号
    QString bootCmd = getJsonValue("data","boot");//执行命令

    if(bootCmd.length() > 0)
    {
        emit siRunLotDataAction(bootCmd);
    }

    m_receiveBuff.remove(0, size);
}

//串口是否打开
void LotMachine::slotIfOpenSerialPort(int val)
{
    if(val != 0)
    {
        if(m_connectMode == USE_SERIAL_COMM)
        {
            m_connected = 3;//串口已打开
        }
    }
}

//获取键值对属性值
QString LotMachine::getJsonValue(QString name1, QString name2)
{
    QString rstr;
    rstr.clear();

    if(name1.length() <= 0 && name2.length() <= 0)
    {
        return rstr;
    }

    //QString str = "{\"device\":\"xiuhuaji133\",\"data\":{\"boot\":9}}";
    QString str = m_receiveBuff;

    QStringList vallist;
    if(str.indexOf(",") == -1)
    {
        return rstr;
    }
    else
    {
        vallist = str.split(",", QString::SkipEmptyParts);
    }

    if(name2.length() <= 0)
    {
        if(vallist.size() >= 1)
        {
            QStringList vallist1;
            if(QString(vallist[0]).indexOf(":") == -1)
            {
                return rstr;
            }
            else
            {
                vallist1 = QString(vallist[0]).split(":", QString::SkipEmptyParts);
            }

            if(QString(vallist1[0]).indexOf(name1) == -1)
            {
                return rstr;
            }
            else
            {
                rstr = QString(vallist1[1]).remove("\"");
            }
        }
    }
    else
    {
        if(vallist.size() >= 2)
        {
            QStringList vallist1;
            if(QString(vallist[1]).indexOf(":") == -1)
            {
                return rstr;
            }
            else
            {
                vallist1 = QString(vallist[1]).split(":", QString::SkipEmptyParts);
            }

            for(int i = 0; i < vallist1.size(); i++)
            {
                if(QString(vallist1[i]).indexOf(name2) != -1)
                {
                    if(i+1 < vallist1.size())
                    {
                        rstr = QString(vallist1[i+1]).remove("\"").remove("}");
                    }
                }
            }
        }
    }

    return rstr;
}

//发送物联数据到网关
void LotMachine::sendLotDataToGateway(QString str)
{
    QByteArray dat;
    dat.clear();
    dat = str.toLatin1();

    emit(siSendData(dat));
}
