#include "timeout.h"
#include "config.h"
#include "httpclient.h"

#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>


extern config *pconfig;

timeout::timeout()
{
    m_iLockTimeout = startTimer(TIMER_LOCKNOTCLOSED);
    m_iHttpTimeout = startTimer(TIMER_HTTPSENDRELAY);
}


void timeout::timerEvent(QTimerEvent *event)
{
    // 锁超时未关检测定时器
    if (event->timerId() == m_iLockTimeout)
    {
        if(pconfig->lastLockTimeEpoch == 0)
        {
            pconfig->locktimeout = false;
        }
        else
        {
            qint64 timeoutEpoch = QDateTime::currentSecsSinceEpoch() - pconfig->lastLockTimeEpoch;
            if(timeoutEpoch > pconfig->lockCloseTimeout)
            {
                emit signal_timeoutRun(timeoutEpoch - pconfig->lockCloseTimeout);

                pconfig->locktimeout = true;
            }
        }
    }
    else if (event->timerId() ==  m_iHttpTimeout)
    {
        if (m_epochLaseHttpPost == 0 && pconfig->locktimeout == true)
        {
            emit signal_timeoutStart();

            m_epochLaseHttpPost = QDateTime::currentSecsSinceEpoch();
            // 向服务器发送开锁异常请求
            QJsonObject jsonObjRoot;
            jsonObjRoot.insert("loanFromCode", pconfig->devUuid);
            QJsonDocument jsonDoc(jsonObjRoot);
            QByteArray jsonData = jsonDoc.toJson(QJsonDocument::Compact);

            // 访问http服务
            QString strUrl = "http://" + pconfig->httpHost + pconfig->postInsertCabinetOpenTimeout_url;
            QByteArray inData = jsonData;
            QByteArray outData;

            httpClient::postRequest(strUrl, httpClient::sToken, inData, outData);

            qDebug() << outData;
        }
        else if (m_epochLaseHttpPost != 0 && pconfig->locktimeout == false)
        {
            emit signal_timeoutEnd();

            m_epochLaseHttpPost = 0;
            // 向服务器发送解除开锁异常
            QJsonObject jsonObjRoot;
            jsonObjRoot.insert("loanFromCode", pconfig->devUuid);
            QJsonDocument jsonDoc(jsonObjRoot);
            QByteArray jsonData = jsonDoc.toJson(QJsonDocument::Compact);

            // 访问http服务
            QString strUrl = "http://" + pconfig->httpHost + pconfig->postUpdateCabinetOpenTimeout_url;
            QByteArray inData = jsonData;
            QByteArray outData;

            httpClient::postRequest(strUrl, httpClient::sToken, inData, outData);

            qDebug() << outData;
        }

    }
}



