#include "localHttpServer.h"
#include "Control/flowControl.h"
#include "DTools/configManger.h"
#include "QsLog.h"
#include <QString>

LocalHttpServer::LocalHttpServer()
{
    QLOG_INFO()<< QString::fromLocal8Bit("[<<<<---LocalHttpServer::启动本地 Https Server [QThread]--->>>>]");
    m_tcpServerManage = new JQHttpServer::TcpServerManage(10);
}

void LocalHttpServer::run()
{
    /*** 启动Http服务:用来响应Http获取订单的请求***/
    QLOG_INFO()<< "[<<<<---LocalHttpServer::Receive Http Request：m_tcpServerManage:--->>>>]" << m_tcpServerManage;
    m_tcpServerManage->setHttpAcceptedCallback( [this]( const QPointer< JQHttpServer::Session > &session )
    {
        QLOG_INFO()<< "[<<<<---LocalHttpServer::Receive Http Request:currentThreadId:--->>>>]" << QThread::currentThreadId();
        // 回调发生在新的线程内;
        /***解析FM外卖插件HTTP服务与Http请求的会话连接是否断开: 会话连接未断开***/
        if(!session.isNull())
        {
            // QString recvData = QString::fromUtf8(session->requestRawData());
            QString recvData = QString::fromUtf8(session->requestBody());
            QLOG_INFO() << QString::fromLocal8Bit("[<<<<---Receive Http Request recvData: %1--->>>>]").arg(recvData);
            QJsonParseError jsonError;
            QJsonObject recvObject;
            QJsonObject replyObject;
            int status; //解析json结果
            QString msg;
            QString pushOrderId;
            QJsonObject data; //回复的内容json
            int iscontinue =0;
            recvObject = QJsonDocument::fromJson(recvData.toUtf8(), &jsonError).object();
            /***解析Http Request json格式: 解析失败***/
            if(jsonError.error != QJsonParseError::NoError)
            {
                status = 0;
                msg = jsonError.errorString();
            } /***解析Http Request json格式: 解析成功***/
            else {
                /***解析：FM外卖插件为响应http 请求准备返回数据：准备返回数据成功***/
                if(FlowControl::GetInstance()._ResponseHttpRequest(recvObject,data, msg)) {
                     status = 100;
                } /***解析：FM外卖插件为响应 Http 请求准备返回数据：准备返回数据失败***/
                else {
                    status = 0;
                } /***解析：等待Http获取的有效订单列表是否为空: sim有效订单列表不为空***/
                if(!FlowControl::GetInstance()._SimValidOrdersListIsEmpty()) {
                    iscontinue=1;
                }
                pushOrderId = recvObject["orderId"].toString();
            }
            /***将FM外卖插件中的合法有效数据返回给上面Http发过来的请求***/
            replyObject = FlowControl::GetInstance()._PackHttpReplyJson( status, msg, data,iscontinue, pushOrderId );
            QLOG_INFO() << QString::fromLocal8Bit("[<<<<---FM外卖插件回应Http拉单请求后的返回结果:--->>>>]") << replyObject;
            session->replyJsonObject(replyObject);
      }
      /***解析FM外卖插件HTTP服务与Http请求的会话连接是否断开: 会话连接断开***/
      else{
         QLOG_INFO() << QString::fromLocal8Bit("[<<<<---FM外卖插件Http服务与Http请求会话断开链接--->>>>]");
      }
   } );

  /***FM外卖插件绑定启动HTTP服务的端口***/
  int port  = ConfigManger::GetInstance().GetHttpServerPort();
  QLOG_INFO() << QString::fromLocal8Bit("[<<<<---FM外卖插件Http服务监听端口：%1 :--->>>>]").arg(port);
  if(m_tcpServerManage->listen( QHostAddress::Any, port))
  {
       QLOG_INFO() << QString::fromLocal8Bit("[<<<<---FM外卖插件Http服务 绑定端口成功:--->>>>]");
  }else{
       QLOG_INFO() << QString::fromLocal8Bit("[<<<<---FM外卖插件Http服务 绑定端口失败:--->>>>]");
  }

}

void LocalHttpServer::stop()
{
    terminate();
    wait();
}
