#include "windows.h"
#include "flowControl.h"
#include "QsLog.h"
#include "DTools/dataManger.h"
#include "preDefine.h"
#include "DTools/configManger.h"
#include "Model/cashierObject.h"
#include <QJsonValue>
#include <QTimer>
#include <QDir>
#include <QApplication>
#include <QDateTime>
#include <QThread>
#include <QtConcurrent>
#include "configManger.h"
#include <QMultiMap>
#include <QMap>
#include <QFile>
#include <DTools/simProcOrderDB.h>
#include <DTools/PrintSumBillPosDB.h>
#include <DTools/getCaboxAReAuth.h>
#include <QHostInfo>


FlowControl &FlowControl::GetInstance()
{
   static FlowControl fc;
   return fc;
}

FlowControl::FlowControl()
{
    m_bLoginResult =false;
    m_bFirstRecvInfo = true;
    m_bFloatFromLockSt = false;
    m_initSimProcOrderDBRet = false;
    m_initPrintSumBillPosDBRet = false;
    m_initGetAuthPosDBRet = false;

    m_loginSocket = NULL;
    m_pullOrderSocket = NULL;
    m_reportOMSRecordOrderSocket = NULL;
    m_procOrderSocket = NULL;
    m_pullDishesSocket = NULL;
    m_pullOrderListSocket = NULL;

    m_clearTimer=new QTimer(this);
    m_heartTimer=new QTimer(this);
    m_pullTimer=new QTimer(this);
    m_reportOMSReocrdOrderTimer = new QTimer(this);
    m_loginTimer=new QTimer(this);
    m_notifySimPullTimer = new QTimer(this);
    m_remindCasherBlinkFloatTimer = new QTimer(this);

    connect(m_loginTimer,&QTimer::timeout,this,&FlowControl::_ClickToLogin);
    connect(m_notifySimPullTimer,&QTimer::timeout,this,&FlowControl::_ClickToNotifySimPullOrder);
    connect(m_remindCasherBlinkFloatTimer,&QTimer::timeout,this,&FlowControl::_RemindCasherBlinkFloatForm);
    connect(m_pullTimer,&QTimer::timeout,this,&FlowControl::_PullOrderData);
    connect(m_reportOMSReocrdOrderTimer,&QTimer::timeout,this,&FlowControl::_ReportOMSRecordOrderInfo);
    connect(m_clearTimer,&QTimer::timeout,this,&FlowControl::_CrondClearExpireOrder);
    connect(m_heartTimer,&QTimer::timeout,this,&FlowControl::_SendHeart);
    connect(this,&FlowControl::doConfirmOrder,this,&FlowControl::_ConfirmOrder,Qt::BlockingQueuedConnection);
    connect(this,&FlowControl::doRefundOrder,this,&FlowControl::_RefundOrder,Qt::BlockingQueuedConnection);
    connect(this, &FlowControl::doLogin, this, &FlowControl::onGetNewStoreInfo,Qt::BlockingQueuedConnection);

    /***打开Sql server express 数据库并登陆外卖插件***/
    SimProcOrderDB::getInstance();
    m_initSimProcOrderDBRet = SimProcOrderDB::getInstance().initSimProcOrderDB();
    /***打开SqlServer POS打印汇总信息本地数据库***/
    PrintSumBillPosDB::getInstance();
    m_initPrintSumBillPosDBRet = PrintSumBillPosDB::getInstance().initPrintSumBillPosDB();
    /***打开SqlServer POS获取 当前用户 是否绑定钱箱+是否拥有退货权限 本地数据库***/
    GetCaboxAReAuth::getInstance();
    m_initGetAuthPosDBRet = GetCaboxAReAuth::getInstance().initGetAuthPosDB();
    QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---FlowControl::FlowControl() m_initSimProcOrderDBRet,m_initPrintSumBillPosDBRet,m_initGetAuthPosDBRet:--->>>>]")
              <<m_initSimProcOrderDBRet <<m_initPrintSumBillPosDBRet<<m_initGetAuthPosDBRet;
    // FlowControl() 初始化时，接受信号的槽对象还没有实例化，所以在此时发信号没有用;
    /*if( !m_initSimProcOrderDBRet || !m_initPrintSumBillPosDBRet ) {
       emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("尝试打开POS本地数据库(MMXB**)失败"));
    }
    if(!m_initGetAuthPosDBRet){
        emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("尝试打开POS本地数据库(DataS**)失败"));
    }*/
    /*** 启动Http服务:用来响应Simphony_Script获取订单的请求***/
    loaclHttpServer = new LoaclHttpServer();
    loaclHttpServer->run();
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /*
    //启动Http服务:用来响应 Http 获取订单的请求
    JQHttpServer::TcpServerManage* m_tcpServerManage = new JQHttpServer::TcpServerManage(10);
    m_tcpServerManage->setHttpAcceptedCallback( [this]( const QPointer< JQHttpServer::Session > &session )
    {
        QLOG_INFO()<< "[<<<<---FlowControl::Receive Http Request:currentThreadId:--->>>>]" << QThread::currentThreadId();
        // 回调发生在新的线程内;
        //解析FM外卖插件HTTP服务 与 Http 请求的会话连接是否断开: 会话连接未断开
        if(!session.isNull())
        {
            QString recvData = QString::fromUtf8(session->requestRawData());
            QLOG_INFO() << QString::fromLocal8Bit("[<<<<---FlowControl::Receive Http Request recvData: %1--->>>>]").arg(recvData);
            QJsonParseError jsonError;
            QJsonObject recvObject;
            QJsonObject replyObject;
            int status; //解析json结果
            QString msg;
            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外卖插件为响应Simphony请求准备返回数据：准备返回数据成功
                if(_ResponseHttpRequest(recvObject,data, msg))
                {
                     status = 100;
                }
                //解析：FM外卖插件为响应Http请求准备返回数据：准备返回数据失败
                else{
                    status = 0;
                }
                //解析：等待Http获取的有效订单列表是否为空: sim有效订单列表不为空
                if(!_SimValidOrdersListIsEmpty())
                {
                    iscontinue=1;
                }
            }
            //将FM外卖插件中的合法有效数据返回给上面Http发过来的请求
            replyObject = _PackHttpReplyJson(status, msg, data,iscontinue);
            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服务 绑定端口失败:--->>>>]");
    }
    */
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
   _ClickOMSAssignArea();
   m_loginTimer->start(10*1000);
}


QString FlowControl::_GetIpAddress()
{
    /***已经验证：IP地址 优先取配置文件中的[IpAddress/ip]；只有没有配置的情况才会根据主机名获取ipv4的IP地址，因此为保证IP的准确性，注释通过配置文件获取ip的代码***/
    QString ipAddress;
    //ipAddress=ConfigManger::GetInstance().GetIpAddress();
    //QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---FlowControl::_GetIpAddress  getFromConfigIni:%1--->>>>]").arg(ipAddress);
    QHostInfo info = QHostInfo::fromName(QHostInfo::localHostName());
    foreach(QHostAddress address,info.addresses())
    {
        if(address.protocol() == QAbstractSocket::IPv4Protocol)
        {
            QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---FlowControl::_GetIpAddress getFromLocalHostName:%1--->>>>]").arg(address.toString());
            //1.1.1.1 > length > 7
            if(address.toString().length()>7){
                ipAddress=address.toString();
            }
            /*
            if(address.toString().contains(ipAddress))
            {
                ipAddress=address.toString();
            }
            */
        }
    }
    return ipAddress+QString(":")+QString::number(ConfigManger::GetInstance().GetHttpServerPort());
}


void FlowControl::_AddOrderPull(const QString &orderId, const QString &channel, const int &pageNumber, const int &pageSize)
{
    m_PullOrderDataMutex.lock();
    /***组装从FM外卖service端的拉单请求参数***/
    PullOrderInfo* orderPull = new PullOrderInfo();
    orderPull->orderId=orderId;
    orderPull->channel=channel;
    orderPull->pageNumber=pageNumber;
    orderPull->pageSize=pageSize;
    QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---FlowControl::_AddOrderPull orderId:%1--->>>>]").arg(orderId);
    m_orderPullList.append(orderPull);
    m_PullOrderDataMutex.unlock();
}


bool FlowControl::_TryAddOrderPull(const QString &orderId, const QString &channel, const int &pageNumber, const int &pageSize)
{
    bool btryLock = m_PullOrderDataMutex.tryLock(2000);
    if (btryLock){
        QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---FlowControl::_TryAddOrderPull orderId:%1--->>>>]").arg(orderId);

        //调用此函数:_TryAddOrderPull() 的函数:_ResponseOMS11Request()没有能百分之百锁定住:插件正触发Simphony在录销售单时，插件立刻接受到OMS推送过来的退货单;
        if(!m_simValidOrdersList.isEmpty()){
            //缩小锁住订单的条件范围: 服务端推单给插件程序且插件程序拒绝本次订单状态发生变化的请求
            if(orderId == m_simValidOrdersList.first() && m_bFloatFromLockSt) {
                QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---FlowControl::_TryAddOrderPull orderId:%1 当前订单正在录POS系统，请耐心等待--->>>>]").arg(orderId);
                m_PullOrderDataMutex.unlock();
                return false;
            }
        }
        /***组装从FM外卖service端的拉单请求参数***/
        PullOrderInfo* orderPull = new PullOrderInfo();
        orderPull->orderId=orderId;
        orderPull->channel=channel;
        orderPull->pageNumber=pageNumber;
        orderPull->pageSize=pageSize;

        m_orderPullList.append(orderPull);
        m_PullOrderDataMutex.unlock();
    }
    return btryLock;
}



//避免 此槽函数 与 拉单定时器触发的槽函数mutex阻塞挂住:因此不调用 emit doPullOrder函数;
//void FlowControl::_GetReadyForPullOrder(const QString &orderId, const QString &channel){}

void FlowControl::_ClickOMSAssignArea()
{
    // 由于星巴克POS存在两种屏幕[①大屏：1366*768 ②小屏：1024*768] 因此采用获取系统屏幕底部坐标减去一个相对距离来实现正确的点击事件(2018-08-13 初步设定：x-10，y-30)；
    // QPoint point=ConfigManger::GetInstance().GetOMSBtnPostion();
    int xOffset = ConfigManger::GetInstance().GetOMSBtnWidthOffset();
    int yOffset = ConfigManger::GetInstance().GetOMSBtnHeightOffset();
    QLOG_INFO()<<QString::fromLocal8Bit("(yOffset%1:,yOffset:%2)").arg(xOffset).arg(yOffset);
    int nWidth = GetSystemMetrics(SM_CXSCREEN) - xOffset;
    int nHeight = GetSystemMetrics(SM_CYSCREEN) - yOffset;
    QLOG_INFO()<<QString::fromLocal8Bit("(x%1:,y:%2)").arg(nWidth).arg(nHeight);
    SetCursorPos(nWidth,nHeight);
    mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0);
    mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0);
    //QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---触发按钮点击事件：Simphony获取订单请求->坐标(x%1:,y:%2):--->>>>]").arg(point.x()).arg(point.y());
    QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---触发按钮点击事件：Simphony获取订单请求->坐标(x%1:,y:%2):--->>>>]").arg(nWidth).arg(nHeight);
}

void FlowControl::_ClickToLogin()
{
    QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---触发按钮点击事件：_ClickToLogin: m_bLoginResult:%1 --->>>>>]").arg(m_bLoginResult);
    if(!m_bLoginResult)
    {
        QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---触发按钮点击事件：FM外卖插件10s后再次尝试登陆--->>>>]");
        _ClickOMSAssignArea();
    }else{
        m_loginTimer->start(1000*60);
    }
}

void FlowControl::_ClickToNotifySimPullOrder()
{
    QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---触发按钮点击事件：_ClickToNotifySimPullOrder: m_simValidOrdersList.isEmpty()==%1--->>>>>]").arg(m_simValidOrdersList.isEmpty());
    if(!m_simValidOrdersList.isEmpty())
    {
        m_notifySimPullTimer->start(1000*10);
        QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---FM外卖插件通知 Simphony 获取订单数据--->>>>]");
        emit doHideMainShowFloatFrom();
        emit doLockFloatForm();
        m_bFloatFromLockSt = true; //更新悬浮框的锁定状态 =true;
        _ClickOMSAssignArea();
    }else{
        m_notifySimPullTimer->start(1000*20);
    }
}


void FlowControl::_RemindCasherBlinkFloatForm()
{
    QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---_RemindCasherBlinkFloatForm: m_simValidOrdersList.isEmpty()==%1--->>>>>]").arg(m_simValidOrdersList.isEmpty());
    if(!m_simValidOrdersList.isEmpty())
    {
        m_remindCasherBlinkFloatTimer->start(1000*5);
        emit startRemind(REMIND_SIM_ORDERLIST_NOEMPTY);
    }else{
        m_remindCasherBlinkFloatTimer->start(1000*15);
    }
}



void FlowControl::_OrderAnalysis(const QJsonObject& jsonObject)
{
    OrderObject *orderObject = NULL;
    orderObject = m_FmOrdersMap.value(jsonObject[JSON_ID].toString());
    /***<1>:FM插件维护的有效订单容器中不存在此订单：整合数据并插入到此订单容器中 ***/
    if(orderObject == NULL)
    {
        orderObject = new OrderObject(this);
        //初始化数据;
        orderObject->orderIndex = 0;
        orderObject->disPlateformFee = 0;
        orderObject->orderDiscount = 0;
        orderObject->deliveryDiscount = 0;

        orderObject->FromJson(jsonObject);
        orderObject->isPush = false;
        orderObject->isCancle = false;

        m_FmOrdersMap.insert(orderObject->id, orderObject);
        QLOG_INFO() << QString("[<<<<---FmTakeout Valid Orders Map:Insert New Order[%1:%2]--->>>>][data:]")
                       .arg(orderObject->id,orderObject->getOrderStatusDec());
        if(!SimProcOrderDB::getInstance().isOrderExist(orderObject->id))
        {
            bool tempBResult = SimProcOrderDB::getInstance().insertSimProcOrder(orderObject->id,QDate::currentDate().toString("yyyy-MM-dd"));
            //判断插入数据库是否出现失败;
            if(!tempBResult) {
                //新增业务逻辑,针对汇报异常的订单需要;添加到 向OMS汇报入机情况的队列中;
                m_RepOMSRecordOrderMutex.lock();
                RepOMSRecordOrderInfo* repOMSRecordOrder = new RepOMSRecordOrderInfo();
                repOMSRecordOrder->orderNo = orderObject->id;
                repOMSRecordOrder->type = (6 == orderObject->orderStatus)?QString::fromLocal8Bit("6"):QString::fromLocal8Bit("3");
                repOMSRecordOrder->status = QString::fromLocal8Bit("2");
                repOMSRecordOrder->opUser = m_cashierName.isEmpty()?QString::fromLocal8Bit("POS"):m_cashierName;
                repOMSRecordOrder->recordDate = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");;
                repOMSRecordOrder->storeId = m_storeId.isEmpty()?QString::fromLocal8Bit("未知门店"):m_storeId;
                repOMSRecordOrder->remark = QString("POS Local DataBase Connect Error Or Table No Exist Error,Please Check DataBase Setting In Time");
                repOMSRecordOrder->reqResult = 0;
                //repOMSRecordOrder->checkNo = QString::fromLocal8Bit("0");
                QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---FlowControl::_OrderAnalysis():m_orderRecordRepOMSList.append()--->>>>]");
                m_orderRecordRepOMSList.append(repOMSRecordOrder);
                m_RepOMSRecordOrderMutex.unlock();
                //修改订单状态，避免后面对数据库出现不稳定的POS机仍然进行录单操作;
                if(6 == orderObject->orderStatus || OrderObject::SimExceptRefund == orderObject->orderStatus){
                    orderObject->orderStatus = OrderObject::SimExceptRefund;
                } else {
                    orderObject->orderStatus = OrderObject::SimExceptSale;
                }
            }

            if((OrderObject::NewOrder==orderObject->orderStatus||OrderObject::Confirmed==orderObject->orderStatus))
            {
                emit startRemind(REMIND_CONFIRMED_ORDER);
            }
        }
        QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis-> changeOrderStatus--->>>>]");
        emit changeOrderStatus(orderObject);
    }
    /***<2>:FM插件维护的有效订单容器中存在此订单:更新订单容器中此订单的订单状态***/
    else
    {
        int oldStatus = orderObject->orderStatus;
        orderObject->FromJson(jsonObject);
        QLOG_INFO() << QString("[<<<<---FmTakeout Valid Order Map:Update  orderId：%1  OldStatus：%2: curStatus：%3]--->>>>]").arg(orderObject->id).arg(oldStatus).arg(orderObject->orderStatus);
        if(oldStatus != orderObject->orderStatus)
        {
            emit changeOrderStatus(orderObject, oldStatus);
        }
    }

    orderObject->updateTime=QDateTime::currentDateTime().toTime_t();
    if(OrderObject::RequestRefund==orderObject->orderStatus)
    {
        emit startRemind(REMIND_REQREFUND_ORDER);
    }

    if(SimProcOrderDB::getInstance().isPushedOrder(orderObject->id))
    {
        orderObject->isPush = true;
    }
    QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis-> orderObject->isPush:(from SimProcOrderDB::getInstance().isPushedOrder)--->>>>]")<<orderObject->isPush;

    // 初始化 退单数据：防止退单标志数据被异常改动；
    if(SimProcOrderDB::getInstance().isRefundOrder(orderObject->id))
    {
        orderObject->isCancle = true;
    }
    QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis-> orderObject->isCancle:(from SimProcOrderDB::getInstance().isRefundOrder)--->>>>]")<< orderObject->isCancle;

    QString posOrderCheckNo = m_orderIdToPosCheckNoMap.value(orderObject->id);

    if(posOrderCheckNo.isEmpty())
    {
        SimProcOrderDB::getInstance().getPosOrderCheckNo(orderObject->id,posOrderCheckNo);
    }
    orderObject->posCheckNo=posOrderCheckNo;
    QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis-> orderObject->posCheckNo:(first:praram empty then getPosOrderCheckNo from databse)--->>>>]")<<orderObject->posCheckNo;
    QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis-> orderObject->orderStatus:--->>>>]")<<orderObject->orderStatus;
    switch (orderObject->orderStatus){
    case OrderObject::NewOrder:
        if(!orderObject->isPush)
        {
            orderObject->pushOrderType = 1;
            orderObject->pushOrderTimes = 0;
            // 针对新订单肯定没有在POS里录入过;
            m_OrderEntryMutex.lock();
            if(!m_simValidOrdersList.contains(orderObject->id))
            {
                m_simValidOrdersList.append(orderObject->id);
            }
            m_OrderEntryMutex.unlock();
            QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis:NewOrder  m_simValidOrdersList.num:%1 --->>>>]")<< m_simValidOrdersList.count();
            QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis:NewOrder  m_simValidOrdersList:%1 --->>>>]")<< m_simValidOrdersList;
            QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis:NewOrder  _ClickOMSAssignArea --->>>>]");
            if("HM" == orderObject->channel){
                QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis:NewOrder [HM Order] don't _ClickOMSAssignArea,Wait Timeout Event --->>>>]");
            }else{
                emit doHideMainShowFloatFrom();
                emit doLockFloatForm();
                m_bFloatFromLockSt = true; //更新悬浮框的锁定状态 =true;
                _ClickOMSAssignArea();
            }
        }
        break;
    case OrderObject::Confirmed:
        // 针对已经确认的订单：POS可能录过，也可能没有; 因此就需要 orderObject->isPush 来判断POS是否录过：true：录过；false：没录过；
        if(!orderObject->isPush)
        {
            orderObject->pushOrderType = 1;
            orderObject->pushOrderTimes = 0;
            m_OrderEntryMutex.lock();
            if(!m_simValidOrdersList.contains(orderObject->id))
            {
                m_simValidOrdersList.append(orderObject->id);
            }
            m_OrderEntryMutex.unlock();
            QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis:OrderConfirmed  m_simValidOrdersList.num:%1 --->>>>]")<< m_simValidOrdersList.count();
            QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis:OrderConfirmed  m_simValidOrdersList:%1 --->>>>]")<< m_simValidOrdersList;
            QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis:OrderConfirmed  _ClickOMSAssignArea --->>>>]");

            if("HM" == orderObject->channel){
                QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis:OrderConfirmed [HM Order] don't _ClickOMSAssignArea,Wait Timeout Event --->>>>]");
            }else{
                emit doHideMainShowFloatFrom();
                emit doLockFloatForm();
                m_bFloatFromLockSt = true; //更新悬浮框的锁定状态 =true;
                _ClickOMSAssignArea();
            }
        }
        break;
    case OrderObject::Sendout:
        if(!orderObject->isPush)
        {
            orderObject->pushOrderType = 1;
            orderObject->pushOrderTimes = 0;
            m_OrderEntryMutex.lock();
            if(!m_simValidOrdersList.contains(orderObject->id))
            {
                m_simValidOrdersList.append(orderObject->id);
            }
            m_OrderEntryMutex.unlock();
            QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis:Sendout  m_simValidOrdersList.num:%1 --->>>>]")<< m_simValidOrdersList.count();
            QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis:Sendout  m_simValidOrdersList:%1 --->>>>]")<< m_simValidOrdersList;
            QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis:Sendout  _ClickOMSAssignArea --->>>>]");
            if("HM" == orderObject->channel){
                QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis:Sendout [HM Order] don't _ClickOMSAssignArea,Wait Timeout Event --->>>>]");
            }else{
                emit doHideMainShowFloatFrom();
                emit doLockFloatForm();
                m_bFloatFromLockSt = true; //更新悬浮框的锁定状态 =true;
                _ClickOMSAssignArea();
            }
        }
        break;
    case OrderObject::Finished:
        if(!orderObject->isPush) {
            orderObject->pushOrderType = 1;
            orderObject->pushOrderTimes = 0;
            m_OrderEntryMutex.lock();
            if(!m_simValidOrdersList.contains(orderObject->id))
            {
                m_simValidOrdersList.append(orderObject->id);
            }
            m_OrderEntryMutex.unlock();
            QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis:Finished  m_simValidOrdersList.num:%1 --->>>>]")<< m_simValidOrdersList.count();
            QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis:Finished  m_simValidOrdersList:%1 --->>>>]")<< m_simValidOrdersList;
            QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis:Finished  _ClickOMSAssignArea --->>>>]");
            if("HM" == orderObject->channel){
                QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis:Finished [HM Order] don't _ClickOMSAssignArea,Wait Timeout Event --->>>>]");
            }else{
                emit doHideMainShowFloatFrom();
                emit doLockFloatForm();
                m_bFloatFromLockSt = true; //更新悬浮框的锁定状态 =true;
                _ClickOMSAssignArea();
            }
        }
        break;
    case OrderObject::RequestRefund:
        // 星巴克：当客户同意退款时，外卖插件收到请求退款后，直接进行退款处理；
        _RefundOrder(orderObject->id,5,QString::fromLocal8Bit("同意退款"),QString());
        break;
    case OrderObject::AgreeRefund:
        break;
    case OrderObject::Refunded:{ /*退单目前本佳那边不区分 OrderObject::Refunded=6 && OrderObject::Cancled =6*/
    /***case:同意退单、退单、取消订单: 此退单还没push到POS[POS没有确认退单或没有返回确认退单的小票号]***/
        //内存会出现BUG：现在改用数据库中标记来判断;
        //if(!orderObject->isCancle)
        bool bIsRefundOrder = SimProcOrderDB::getInstance().isRefundOrder(orderObject->id);
        QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis:Refunded orderObject->id:%1; bIsRefundOrder: --->>>>]").arg(orderObject->id)<<bIsRefundOrder;
        if(!bIsRefundOrder)
        {
            /***case:校验此订单是否已经push到POS：订单还没push到POS[POS没有模拟点单或没有返回小票号]***/
            //内存中处理存在BUG:现在改用 直接读数据库中的标志；
            //if(!orderObject->isPush)
            if(!SimProcOrderDB::getInstance().isPushedOrder(orderObject->id))
            {
                m_OrderEntryMutex.lock();
                m_simValidOrdersList.removeOne(orderObject->id);
                m_OrderEntryMutex.unlock();
            } /***case:校验此订单是否已经push到POS：订单已经push到POS***/
            else{ /***case:校验此订单push到POS后的小票号是否空：[POS已模拟点单且返回小票号]***/
                if(!posOrderCheckNo.isEmpty())
                {
                    orderObject->isCancle =true;    // 和orderObject->pushOrderType 来联合标记传出数据；
                    orderObject->pushOrderType = 0; //标记准备退单动作；
                    orderObject->pushOrderTimes = 0;
                    m_OrderEntryMutex.lock();
                    if(!m_simValidOrdersList.contains(orderObject->id))
                    {
                        m_simValidOrdersList.append(orderObject->id);
                    }
                    m_OrderEntryMutex.unlock();
                    QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis:Cancled  m_simValidOrdersList.num:%1 --->>>>]")<< m_simValidOrdersList.count();
                    QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis:Cancled  m_simValidOrdersList:%1 --->>>>]")<< m_simValidOrdersList;
                    QLOG_INFO() << QString("[<<<<---FmTakeout _OrderAnalysis:Cancled  _ClickOMSAssignArea --->>>>]");
                    //怕程序会卡死或者程序阻塞，所以只能先将此类订单添加到Simphony的有效队列中;
                    //May Cause Program Blocking. Add By ZouWuYang For Reduce The Possibility Of Locking Deliver Refund Order. //
                    emit doHideMainShowFloatFrom();
                    emit doLockFloatForm();
                    m_bFloatFromLockSt = true; //更新悬浮框的锁定状态 =true;
                    _ClickOMSAssignArea();
                }
                /***case:校验此订单push到POS后的小票号是否空：[POS已模拟点单但未返回小票号]***/
                //else{未处理}
            }
        }
        break;
        }
    default:
        break;
    }
}

void FlowControl::onGetNewStoreInfo()
{
    QLOG_INFO()<<"[<<<<---Get New Store Info:Openssl support--->>>>]:"<<QSslSocket::supportsSsl();
    m_loginSocket = new BillSocket(this);
    m_pullOrderSocket = new BillSocket(this);
    m_reportOMSRecordOrderSocket = new BillSocket(this);
    m_procOrderSocket = new BillSocket(this);
    m_pullDishesSocket = new BillSocket(this);
    m_pullOrderListSocket = new BillSocket(this);
    _GetStoreInfo();
    _Login();
    m_bFirstRecvInfo =false;
    return ;
}

//鸡肋：没有用到此函数的实际功能【仅仅用来获取门店登陆用的密码:m_password】；
bool FlowControl::_GetStoreInfo()
{
    bool result=true;
    emit showAlert(AlertForm::LOADING, QString::fromLocal8Bit("正在获取门店信息......"));
    QLOG_INFO() << QString("[<<<<---Get StoreInfo--->>>>]");
    QString tmp;
    ConfigManger::GetInstance().GetStoreInfo(tmp/*, m_posId, m_cashierId*/, m_password);
    return result;
}

QString FlowControl::_GetCashierId()
{
    return m_cashierId;
}

QString FlowControl::_GetCashierName()
{
    return m_cashierName;
}

bool FlowControl::_SimValidOrdersListIsEmpty(){
    return m_simValidOrdersList.empty();
}

bool FlowControl::_Login()
{
    QString error;
    bool result;
    QJsonObject sendJson;
    QJsonObject recvJson;

    sendJson = DataManger::GetInstance().GetLoginData(ConfigManger::GetInstance().GetPartnerId(),m_storeId,
                                                      m_password, m_posId, m_cashierId,_GetIpAddress());
    emit showAlert(AlertForm::LOADING, QString::fromLocal8Bit("正在登录......"));
    QLOG_INFO() << QString("[<<<<---Login--->>>>][requestData:%1]")<<sendJson;
    if(ConfigManger::GetInstance().GetLoginSslConfig())
    {
        m_loginSocket->SetSslConfig();
        QLOG_INFO() << QString("[<<<<---_Login Set ssl Config--->>>>]");
    }

    //  测试oms服务down后，退单时会导致插件程序退出；
    /*if(1){
        QJsonObject sendJsontemp;
        sendJsontemp.insert(JSON_ORDERID, "123456789");
        sendJsontemp.insert("canceledCause", 5 );
        sendJsontemp.insert(JSON_POSIPADDRESS,QString("http://10.222.221.163:8080"));
        QLOG_INFO() << QString("[<<<<---_Login Test:--->>>>][requestData:%1]")<<sendJsontemp;
        if(ConfigManger::GetInstance().GetOrderSslConfig()) {
            m_procOrderSocket->SetSslConfig();
            QLOG_INFO()<<"_Login load ssl";
        } else {
            QLOG_INFO()<<"_Login load not ssl";
        }
        m_procOrderSocket->SetUrl(QUrl(ConfigManger::GetInstance().GetOrderServerUrl() + ConfigManger::GetInstance().GetInterfaceName(INI_INTERFACE_CANCLE)));
        QLOG_INFO() << QString("[<<<<---_Login Refund Order Request: --->>>>]")<< m_procOrderSocket->GetUrl();
        result = m_procOrderSocket->PostRequest(sendJsontemp, recvJson, error);
        QLOG_INFO() << QString("[<<<<---_Login Refund Order response:result:%1 --->>>>]")<<result;
        return true;
    }*/
    //  测试oms服务down后，退单时会导致插件程序退出；

    QLOG_INFO()<<ConfigManger::GetInstance().GetLoginServerUrl()+
              ConfigManger::GetInstance().GetInterfaceName(INI_INTERFACE_ILOGIN);
    m_loginSocket->SetUrl(QUrl(ConfigManger::GetInstance().GetLoginServerUrl()+
                               ConfigManger::GetInstance().GetInterfaceName(INI_INTERFACE_ILOGIN)));
    QLOG_INFO() << QString("[<<<<---_Login Qurl: --->>>>]")<<m_loginSocket->GetUrl();
    result = m_loginSocket->PostRequest(sendJson, recvJson, error);
    QLOG_INFO() << QString("[<<<<---Login Finshed--->>>>][result:%1][msg:%2][recvData:").arg(result).arg(error)<<recvJson;
    if(!result) {
        emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("登录失败![网络错误]"));
    } else {
        if(JSON_STATUSCODE_OK != recvJson[JSON_LOGINCODE].toInt()) {
            result = false;
            emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("登录失败![%1]").arg(recvJson[JSON_MESSAGE].toString()));
        } else {
            m_storeName = recvJson[JSON_STORENAME].toString();
            DataManger::GetInstance().SetToken(recvJson[JSON_DATA].toObject()[JSON_TOKEN].toString());
            DataManger::GetInstance().SetStoreId(m_storeId);
            DataManger::GetInstance().SetPosIpAddress(_GetIpAddress());
            DataManger::GetInstance().SetPartnerId(ConfigManger::GetInstance().GetPartnerId());
            emit hideAlert();
            emit setStoreInfo(m_storeId);
            emit setCashierInfo(m_cashierName);

            //***********************登陆时获取门店的营业状态 begin ************************//
            /*
            QJsonObject storeStatusData = recvJson[JSON_DATA].toObject();
            QLOG_INFO()<<"FlowControl::_Login:"<<storeStatusData;
            if(1==storeStatusData["appStoreStatus"].toInt() || 1==storeStatusData["eleStoreStatus"].toInt()) {
                QString strOpeStatus = QString::fromLocal8Bit("开店");
                emit setOpeStatus(strOpeStatus);
                emit doUpdateStoreStatus(true);
            }else {
                QString strOpeStatus = QString::fromLocal8Bit("关店");
                emit setOpeStatus(strOpeStatus);
                emit doUpdateStoreStatus(false);
            }
            */
            //***********************登陆时获取门店的营业状态 end ************************//
            m_bLoginResult= true;
            m_clearTimer->start(1000*60*60*2); // 5分钟执行一次清理任务:正式上线需要两小时清理一次；
            m_heartTimer->start(1000*60*5);
            m_pullTimer->start(1000*2);
            m_reportOMSReocrdOrderTimer->start(1000*6);
            m_notifySimPullTimer->start(10*1000);
            m_remindCasherBlinkFloatTimer->start(5*1000);
            //_AddOrderPull(QString(),QString());
            //在登陆时再次检查数据库连接是否都正常；
            if( !m_initSimProcOrderDBRet || !m_initPrintSumBillPosDBRet || !m_initGetAuthPosDBRet ) {
                result = false;
                QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---FlowControl::_Login() m_initSimProcOrderDBRet,m_initPrintSumBillPosDBRet,m_initGetAuthPosDBRet:--->>>>]")
                          <<m_initSimProcOrderDBRet <<m_initPrintSumBillPosDBRet<<m_initGetAuthPosDBRet;
                emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("尝试打开POS本地数据库(MMXB** 或 DataS**)失败"));
            } else {
                _AddOrderPull(QString(),QString());
            }
        }
    }
    if(!result) {
        QLOG_INFO() << QString("[<<<<---Login Retry--->>>>] %1 msec after login...").arg(VALUE_RELOGINTIME);
        QTimer::singleShot(VALUE_RELOGINTIME, this, &FlowControl::_Login);
    }
    QLOG_INFO() << QString("[<<<<---Login--->>>>][m_bLoginResult:%1]")<<m_bLoginResult;
    return result;
}

void FlowControl::_PullOrderData()
{
    QLOG_INFO()<<"[<<<<----FlowControl::_PullOrderData ---->>>>>]";
    if(m_orderPullList.isEmpty())
        return ;
    emit hideAlert();

    m_PullOrderDataMutex.lock();
    PullOrderInfo* info = m_orderPullList.takeFirst();

    if(info->orderId.isEmpty())
    {
        if ( _PullOrderList(info->pageSize,info->pageNumber) ){
            QLOG_INFO()<<"[<<<<----FlowControl::_PullOrderData  _PullOrderList successful---->>>>>]";
            m_orderPullList.removeOne(info);
            delete info;
        }else {
            QLOG_INFO()<<"[<<<<----FlowControl::_PullOrderData _PullOrderList failed---->>>>>]";
            m_orderPullList.removeOne(info);
            m_orderPullList.append(info);
        }
    }
    else
    {
        if (_PullOrderDetail(info->orderId) ){
             QLOG_INFO()<<"[<<<<----FlowControl::_PullOrderData  _PullOrderDetail successful---->>>>>]";
             m_orderPullList.removeOne(info);
             delete info;
        }else{
             QLOG_INFO()<<"[<<<<----FlowControl::_PullOrderData  _PullOrderDetail fail---->>>>>]";
             m_orderPullList.removeOne(info);
             m_orderPullList.append(info);
        }
    }

    m_PullOrderDataMutex.unlock();
    return ;
}

bool FlowControl::_PullOrderDetail(const QString& orderId)
{
    if(m_pullOrderSocket==NULL)
        m_pullOrderSocket =new BillSocket(this);
    QString error;
    bool result;
    QJsonObject recvJson;

    if(ConfigManger::GetInstance().GetOrderSslConfig())
    {
        m_pullOrderSocket->SetSslConfig();
        QLOG_INFO()<<"FlowControl::_PullOrderDetail  load ssl";
    }
    else{
        QLOG_INFO()<<"FlowControl::_PullOrderDetail load not ssl";
    }
    QString url = ConfigManger::GetInstance().GetOrderServerUrl()+
            ConfigManger::GetInstance().GetInterfaceName(INI_INTERFACE_PULLORDER);
    url.append(orderId);
    QString posIpAddress = _GetIpAddress();
    url.append(QString("&")+JSON_POSIPADDRESS+QString("=")+posIpAddress);
    QLOG_INFO() << QString("[<<<<---Pull Order Detail--->>>>][requestUrl:]")<<url;
    m_pullOrderSocket->SetUrl(QUrl(url));
    result = m_pullOrderSocket->GetRequest(recvJson, error);
    QLOG_INFO() << QString("[<<<<---Pull Order Detail Finsh--->>>>][result:%1][msg:%2]")
                   .arg(result).arg(error)<<recvJson;
    if(!result)
    {
        emit setNetStatus(QString::fromLocal8Bit("<font color='#ff0000'>网络不稳定,正在重试</font>"));
    }else
    {
        qDebug()<<recvJson;
        emit setNetStatus(QString::fromLocal8Bit("正常"));
        if(JSON_STATUSCODE_OK != recvJson[JSON_ERRCODE].toInt())
        {
            QString error = recvJson[JSON_ERRMSG].toString();
            QLOG_ERROR() << QString("[<<<<---Pull Order Detail Error--->>>>][msg->%1]").arg(error);
            emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("获取订单失败![%1]").arg(error));
            result=false;
        }else
        {
            //获取门店营业状态
            //QString strOpeStatus=QString::fromLocal8Bit("开店");
            //emit setOpeStatus(strOpeStatus);
            QJsonObject order = recvJson[JSON_DATA].toObject();
            _OrderAnalysis(order);
        }
    }
    /*解析json数据失败则20秒后重新拉单*/
    if(!result)
    {
        m_pullTimer->start(1000*10);
        // 如果某次拉订单列表出现失败；此函数的外层函数 _PullOrderData：会将本次拉单对象存起来，等待下次拉取;
    }else{
        m_pullTimer->start(1000*2);
    }
    qDebug()<<"[<<<<---Pull Order Detail Result--->>>>]"<<result;
    return result;
}

bool FlowControl::_PullOrderList(const int &pageSize, const int &pageNo)
{
    if(m_pullOrderListSocket==NULL)
    {
        m_pullOrderListSocket =new BillSocket(this);
    }
    QString error;
    bool result;
    QJsonObject sendJson;
    QJsonObject recvJson;
    int ordertotalSum;
    sendJson = DataManger::GetInstance().GetPullOrderListData(pageNo,pageSize);

    QLOG_INFO() << QString("[<<<<---FlowControl::_PullOrderList: Pull Order List--->>>>][requestData:]")<<sendJson;
    if(ConfigManger::GetInstance().GetOrderSslConfig())
    {
        // m_pullOrderSocket->SetSslConfig();
        m_pullOrderListSocket->SetSslConfig();
        QLOG_INFO()<<"FlowControl::_PullOrderList load ssl";
    }
    else{
        QLOG_INFO()<<"FlowControl::_PullOrderList load not ssl";
    }
    m_pullOrderListSocket->SetUrl(QUrl(ConfigManger::GetInstance().GetOrderServerUrl()+
                                   ConfigManger::GetInstance().GetInterfaceName(INI_INTERFACE_PULLORDERLIST)));
    QLOG_INFO()<<ConfigManger::GetInstance().GetOrderServerUrl()+
                 ConfigManger::GetInstance().GetInterfaceName(INI_INTERFACE_PULLORDERLIST)<< " requestData: " <<sendJson;
    result = m_pullOrderListSocket->PostRequest(sendJson, recvJson, error);
    QLOG_INFO() << QString("[<<<<---FlowControl::_PullOrderList:Pull Order List Finish.--->>>>][result:%1][msg:%2]")
                   .arg(result).arg(error)<<recvJson;
    if(!result)
    {
        emit setNetStatus(QString::fromLocal8Bit("<font color='#ff0000'>网络不稳定，正在重试</font>"));
    }else
    {
        qDebug()<<recvJson;
        emit setNetStatus(QString::fromLocal8Bit("正常"));
        if(JSON_STATUSCODE_OK != recvJson[JSON_ERRCODE].toInt())
        {
            QString error = recvJson[JSON_ERRMSG].toString();
            QLOG_ERROR() << QString("[<<<<---FlowControl::_PullOrderList:Pull Order List Error--->>>>][msg->%1]").arg(error);
            emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("获取订单失败![%1]").arg(error));
            result=false;
        }else
        {
            //获取门店营业状态
            //QString strOpeStatus=QString::fromLocal8Bit("开店");
            //emit setOpeStatus(strOpeStatus);
            QJsonArray orders = recvJson[JSON_DATA].toObject()[JSON_ORDERS].toArray();
            foreach(QJsonValue order, orders)
            {
                _OrderAnalysis(order.toObject());
            }
            ordertotalSum=recvJson[JSON_DATA].toObject()[JSON_COUNT].toInt();
            m_orderCount+=50;
            if(m_orderCount<ordertotalSum)
            {
                //避免出现存在多页数据，导致出现死锁: 先调用定时器的timeout 触发槽函数:_PullOrderData,
                //_PullOrderData:内部会有加锁并且会调用分页获取订单函数_AddOrderPull(QString(),QString(),pageNo+1,pageSize): 内部也有加锁，所以导致死锁;
                //_AddOrderPull(QString(),QString(),pageNo+1,pageSize);
                /***组装从FM外卖service端的拉单请求参数***/
                PullOrderInfo* orderPull = new PullOrderInfo();
                orderPull->orderId=QString();
                orderPull->channel=QString();
                orderPull->pageNumber=pageNo+1;
                orderPull->pageSize=pageSize;
                QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---FlowControl::_PullOrderList: Next Page Order List :pageNo:%1--->>>>]").arg(pageNo+1);
                m_orderPullList.append(orderPull);
                //避免出现存在多页数据，导致出现死锁;
            }
        }
    }
    // 如果出现拉取订单列表失败，触发下一次拉门店有效订单的时间间隔变更为20(如果一开始就获取订单列表成功:时间间隔为5s)
    if(!result)
    {
        m_pullTimer->start(1000*10);
        // 如果某次拉订单列表出现失败；此函数的外层函数 _PullOrderData: 还会将本次拉单列表存起来等待下次拉取;
    }
    QLOG_INFO()<<"[<<<<---Pull Order List Result--->>>>]"<< result;
    return result;
}

bool FlowControl::_SendHeart()
{
    QString error;
    bool result;
    QJsonObject sendJson;
    QJsonObject recvJson;

    sendJson = DataManger::GetInstance().GetHeartData(m_password,m_posId,_GetIpAddress());
    QLOG_INFO() << QString("[<<<<---Send Heart--->>>>][requestData:%1]")<<sendJson;
    m_loginSocket->SetUrl(QUrl(ConfigManger::GetInstance().GetLoginServerUrl()+
                               ConfigManger::GetInstance().GetInterfaceName(INI_INTERFACE_HEART)));
    result = m_loginSocket->PostRequest(sendJson, recvJson, error);
    QLOG_INFO() << QString("[<<<<---Send Heart Finish--->>>>][result:%1][msg:%2][recvData:%3]")
                   .arg(result).arg(error)<<recvJson;
    if(!result)
    {
        emit setNetStatus(QString::fromLocal8Bit("<font color='#ff0000'>网络不稳定，正在重试</font>"));
    }else
    {
       QLOG_INFO() << QString("[<<<<---Send Heart Finish: code:%1--->>>>]").arg(recvJson[JSON_LOGINCODE].toInt());
       if(JSON_STATUSCODE_OK != recvJson[JSON_LOGINCODE].toInt())
       {
            result = false;
            emit setNetStatus(QString::fromLocal8Bit("<font color='#ff0000'>网络不稳定，正在重试</font>"));
       }else{
           result = true;
           emit setNetStatus(QString::fromLocal8Bit("<font color='#f5f5f5'>正常</font>"));
           /* //根据心跳来展示门店营业状态 [数据延迟比较严重:需要通过OMS推门店状态给我]
           QJsonObject storeStatusData = recvJson[JSON_DATA].toObject();
           int appStoreStatus = storeStatusData[JSON_APPSTORESTS].toInt();
           int eleStoreStatus = storeStatusData[JSON_ELESTORESTS].toInt();
           QLOG_INFO() << QString("[<<<<---FlowControl::_SendHeart appStoreStatus:%1 ;eleStoreStatus:%2 --->>>>]").arg(appStoreStatus).arg(eleStoreStatus);
           if(1==appStoreStatus || 1==eleStoreStatus){
               emit doUpdateStoreStatus(true);
               emit setOpeStatus(QString::fromLocal8Bit("开店"));
           }else{
               emit doUpdateStoreStatus(false);
               emit setOpeStatus(QString::fromLocal8Bit("关店"));
           }
           */
       }
    }
    return result;
}

bool FlowControl::_ConfirmOrder(const QString &orderId)
{
    QString error;
    bool result;
    QJsonObject recvJson;
    emit showAlert(AlertForm::LOADING, QString::fromLocal8Bit("正在通信......"));
    if(ConfigManger::GetInstance().GetOrderSslConfig())
    {
        m_procOrderSocket->SetSslConfig();
        QLOG_INFO()<<"load ssl";
    }
    else{
        QLOG_INFO()<<"load not ssl";
    }
    QString url = ConfigManger::GetInstance().GetOrderServerUrl()+
            ConfigManger::GetInstance().GetInterfaceName(INI_INTERFACE_CONFIRM);
    url.append(orderId);
    QString posIpAddress = _GetIpAddress();
    url.append(QString("&")+JSON_POSIPADDRESS+QString("=")+posIpAddress);
    QLOG_INFO() << QString("[<<<<---Confirm Order Begin--->>>>][requestUrl:]")<<url;
    m_procOrderSocket->SetUrl(QUrl(url));
    result = m_procOrderSocket->GetRequest(recvJson, error);
    QLOG_INFO() << QString("[<<<<---Confirm Order Finish--->>>>][result:%1][msg:%2][recvData:%3]")
                   .arg(result).arg(error)<<recvJson;
    if(!result)
    {
        emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("接单失败![网络错误]"));
    }else
    {
        if(JSON_STATUSCODE_OK != recvJson[JSON_ERRCODE].toInt())
        {
            result = false;
            emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("接单失败![%1]").arg(recvJson[JSON_ERRMSG].toString()));
        }else
        {
            QJsonObject data = recvJson[JSON_DATA].toObject();
            int status = data[JSON_RECEIVINGSTATUS].toInt();
            if(1==status)
            {
                int orderStatus = data[JSON_ORDERSTATUS].toInt();
                OrderObject* orderObject = m_FmOrdersMap.value(orderId);
                int oldOrderStatus = orderObject->orderStatus;
                orderObject->orderStatus = orderStatus;
                emit changeOrderStatus(orderObject, oldOrderStatus);
                if (OrderObject::Confirmed == orderStatus){
                    if(!orderObject->isPush)
                    {
                        orderObject->pushOrderType = 1;
                        orderObject->pushOrderTimes = 0;
                        m_OrderEntryMutex.lock();
                        if(!m_simValidOrdersList.contains(orderObject->id))
                        {
                            m_simValidOrdersList.append(orderObject->id);
                        }
                        m_OrderEntryMutex.unlock();
                        QLOG_INFO() << QString("[<<<<---FmTakeout _ConfirmOrder:  m_simValidOrdersList.num:%1 --->>>>]")<< m_simValidOrdersList.count();
                        QLOG_INFO() << QString("[<<<<---FmTakeout _ConfirmOrder:  m_simValidOrdersList:%1 --->>>>]")<< m_simValidOrdersList;
                        QLOG_INFO() << QString("[<<<<---FmTakeout _ConfirmOrder:  _ClickOMSAssignArea --->>>>]");
                        emit doHideMainShowFloatFrom();
                        emit doLockFloatForm();
                        m_bFloatFromLockSt = true; //更新悬浮框的锁定状态 =true;
                        _ClickOMSAssignArea();
                    }
                }
            }
            else
            {
                emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("接单失败![%1]").arg(recvJson[JSON_ERRMSG].toString()));
            }
        }
    }
    return result;
}

bool FlowControl::_RefuseOrder(const QString &orderId, int refuseCode,const QString reason)
{
    QString error;
    bool result;
    QJsonObject sendJson;
    QJsonObject recvJson;

    sendJson = DataManger::GetInstance().GetRefuseOrderData(refuseCode, orderId);

    emit showAlert(AlertForm::LOADING, QString::fromLocal8Bit("正在通信......"));
    QLOG_INFO() << QString("[<<<<---Refuse Order Begin--->>>>][requestData:%1]")<<sendJson;
    result = m_procOrderSocket->PostRequest(sendJson, recvJson, error);
    QLOG_INFO() << QString("[<<<<---Refuse Order Finish--->>>>][result:%1][msg:%2][recvData:%3]")
                   .arg(result).arg(error)<<recvJson;
    if(!result)
    {
        emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("拒单失败![网络错误]"));
    }else
    {
        if(JSON_STATUSCODE_OK != recvJson[JSON_STATUSCODE].toInt())
        {
            result = false;
            emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("拒单失败![%1]").arg(recvJson[JSON_MESSAGE].toString()));
        }else
        {
            emit showAlert(AlertForm::SUCCESS, QString::fromLocal8Bit("拒单成功!"));
            // 通知主界面移动订单
            OrderObject *orderObject = m_FmOrdersMap.value(orderId);
            int oldStatus = orderObject->orderStatus;
            orderObject->orderStatus = recvJson[JSON_STATUS].toInt();
            emit changeOrderStatus(orderObject, oldStatus);

            //取消订单(星巴克只有退单)后，将此订单加入到simphony 模拟点单列表中；
            if (OrderObject::Refunded == orderObject->orderStatus){
                //if(!orderObject->isCancle)  //内存中数据存在BUG：需要中数据库中读取准确标识;
                if(!SimProcOrderDB::getInstance().isRefundOrder(orderObject->id))
                {
                    // 判断Simphony 队列中的订单是否已经存在:不存在(Simphony已经点单完成后会移除)则添加； 如果存在(说明此订单还没有模拟点单)，则需要直接向现存在Sim有效队列中的记录移除;
                    m_OrderEntryMutex.lock();
                    if(!m_simValidOrdersList.contains(orderObject->id))
                    {
                        m_simValidOrdersList.insert(0,orderObject->id);
                    }else{
                        if(!PrintSumBillPosDB::getInstance().isOrderSumBillExist(orderObject->id)){
                            m_simValidOrdersList.removeOne(orderObject->id);
                        }
                    }
                    orderObject->isCancle=true;
                    orderObject->pushOrderType=0;
                    m_OrderEntryMutex.unlock();
                    QLOG_INFO() << QString("[<<<<---FmTakeout _RefuseOrder:  m_simValidOrdersList.num:%1 --->>>>]")<< m_simValidOrdersList.count();
                    QLOG_INFO() << QString("[<<<<---FmTakeout _RefuseOrder:  m_simValidOrdersList:%1 --->>>>]")<< m_simValidOrdersList;
                    QLOG_INFO() << QString("[<<<<---FmTakeout _RefuseOrder:  _ClickOMSAssignArea --->>>>]");
                    emit doHideMainShowFloatFrom();
                    emit doLockFloatForm();
                    m_bFloatFromLockSt = true; //更新悬浮框的锁定状态 =true;
                    _ClickOMSAssignArea();
                }
            }

        }
    }

    return result;
}

bool FlowControl::_SendOrder(const QString& orderId)
{
    //TODO
//    if(m_FmOrdersMap.value(orderId)->riderName.isEmpty()&&m_FmOrdersMap.value(orderId)->delivery_type==1)
//    {
//        emit showAlert(AlertForm::MSGERROR,QString::fromLocal8Bit("配送员暂未接单，请等待"));
//        return true;
//    }
    QString error;
    bool result;
    QJsonObject sendJson;
    QJsonObject recvJson;

    sendJson = DataManger::GetInstance().GetSendOrderData(orderId);

    emit showAlert(AlertForm::LOADING, QString::fromLocal8Bit("正在通信......"));
    QLOG_INFO() << QString("[<<<<---Sendout Order Begin--->>>>][requestData:%1]")<<sendJson;
    result = m_procOrderSocket->PostRequest(sendJson, recvJson, error);
    QLOG_INFO() << QString("[<<<<---Sendout Order Finish--->>>>][result:%1][msg:%2][recvData:%3]")
                   .arg(result).arg(error)<<recvJson;
    if(!result)
    {
        emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("送出失败![网络错误]"));
    }else
    {
        if(JSON_STATUSCODE_OK != recvJson[JSON_STATUSCODE].toInt())
        {
            result = false;
            emit showAlert(AlertForm::MSGERROR,  QString::fromLocal8Bit("送出失败![%1]").arg(recvJson[JSON_MESSAGE].toString()));
        }else
        {
            emit showAlert(AlertForm::SUCCESS, QString::fromLocal8Bit("送出成功!"));

            // 通知主界面移动订单
            OrderObject *orderObject = m_FmOrdersMap.value(orderId);
            int oldStatus = orderObject->orderStatus;
            orderObject->orderStatus = recvJson[JSON_STATUS].toInt();
            // TODO  服务器端现还未开发
            //orderObject->status_desc = recvJson[JSON_STATUSDESC].toString();
            emit changeOrderStatus(orderObject, oldStatus);
        }
    }

    return result;
}

bool FlowControl::_CompleteOrder(const QString& orderId)
{
    QString error;
    bool result;
    QJsonObject sendJson;
    QJsonObject recvJson;

    sendJson = DataManger::GetInstance().GetCompleteOrderData(orderId);

    emit showAlert(AlertForm::LOADING, QString::fromLocal8Bit("正在通信......"));
    QLOG_INFO() << QString("[<<<<---Complete Order Begin--->>>>][requestData:%1]")<<sendJson;
    result = m_procOrderSocket->PostRequest(sendJson, recvJson, error);
    QLOG_INFO() << QString("[<<<<---Complete Order Finish--->>>>][result:%1][msg:%2][recvData:%3]")
                   .arg(result).arg(error)<<recvJson;
    if(!result)
    {
        emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("完成失败![网络错误]"));
    }else
    {
        if(JSON_STATUSCODE_OK != recvJson[JSON_STATUSCODE].toInt())
        {
            result = false;
            emit showAlert(AlertForm::MSGERROR,    QString::fromLocal8Bit("完成失败![%1]").arg(recvJson[JSON_MESSAGE].toString()));
        }else
        {
            emit showAlert(AlertForm::SUCCESS, QString::fromLocal8Bit("完成成功!"));

            // 通知主界面移动订单
            OrderObject *orderObject = m_FmOrdersMap.value(orderId);
            int oldStatus = orderObject->orderStatus;
            orderObject->orderStatus = recvJson[JSON_STATUS].toInt();
            emit changeOrderStatus(orderObject, oldStatus);
        }
    }

    return result;
}

bool FlowControl::_RefuseRefund(const QString& orderId)
{
    QString error;
    bool result;
    QJsonObject sendJson;
    QJsonObject recvJson;

    sendJson = DataManger::GetInstance().GetRefuseRefundData(VALUE_REFUSEREFUND_REASON,orderId);

    emit showAlert(AlertForm::LOADING, QString::fromLocal8Bit("正在通信......"));

    QLOG_INFO() << QString("[<<<<---RefuseRefund Order Begin--->>>>][requestData:]")<<sendJson;
    result = m_procOrderSocket->PostRequest(sendJson, recvJson, error);
    QLOG_INFO() << QString("[<<<<---RefuseRefund Order Finish--->>>>][result:%1][msg:%2][recvData:]")
                   .arg(result).arg(error)<<recvJson;
    if(!result)
    {
        emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("拒绝退单失败![网络错误]"));
    }else
    {
        if(JSON_STATUSCODE_OK != recvJson[JSON_STATUSCODE].toInt())
        {
            result = false;
            emit showAlert(AlertForm::MSGERROR,   QString::fromLocal8Bit("拒绝退单失败![%1]").arg(recvJson[JSON_MESSAGE].toString()));
        }else
        {
            emit showAlert(AlertForm::SUCCESS, QString::fromLocal8Bit("拒绝退单成功!"));

            // 通知主界面移动订单
            OrderObject *orderObject = m_FmOrdersMap.value(orderId);
            int oldStatus = orderObject->orderStatus;
            orderObject->orderStatus = recvJson[JSON_STATUS].toInt();
            // TODO  服务器端现还未开发
            // orderObject->status_desc = recvJson[JSON_STATUSDESC].toString();
            emit changeOrderStatus(orderObject, oldStatus);
        }
    }

    return result;
}

bool FlowControl::_RefundOrder(const QString &orderId,int reasonCode,const QString& reason,const QString& dishesListString)
{

    QLOG_INFO() << QString("[<<<<---FlowControl::_RefundOrder--->>>>][orderId:%1 reasonCode:%2 reason:%3 dishesListString:]").arg(orderId).arg(reasonCode).arg(reason).arg(dishesListString);
    QString error;
    bool result;
    QJsonObject sendJson;
    QJsonObject recvJson;
    sendJson = DataManger::GetInstance().GetRefundOrderData(reasonCode,reason,orderId,m_FmOrdersMap.value(orderId)->channel, dishesListString, m_cashierId, m_cashierName);
    emit showAlert(AlertForm::LOADING, QString::fromLocal8Bit("正在通信......"));
    QLOG_INFO() << QString("[<<<<---Refund Order Begin--->>>>][requestData:%1]")<<sendJson;
    // 如果退款原因：商品已售完，使用下面接口; // 如果退款原因：其他，都同意使用一个接口；
    m_procOrderSocket->SetUrl(QUrl(ConfigManger::GetInstance().GetOrderServerUrl() + ConfigManger::GetInstance().GetInterfaceName(INI_INTERFACE_CANCLE)));
    QLOG_INFO() << QString("[<<<<<-----_RefundOrder: orderId:%1  URL: ----->>>>>]").arg(orderId)<< m_procOrderSocket->GetUrl();

    if(ConfigManger::GetInstance().GetOrderSslConfig()) {
        m_procOrderSocket->SetSslConfig();
        QLOG_INFO()<<"load ssl";
    } else {
        QLOG_INFO()<<"load not ssl";
    }
    QLOG_INFO() << QString("[<<<<---Refund Order Request: --->>>>]")<< m_procOrderSocket->GetUrl();
    result = m_procOrderSocket->PostRequest(sendJson, recvJson, error);
    QLOG_INFO() << QString("[<<<<---Refund Order Finish--->>>>][result:%1][msg:%2][recvData:]")
                   .arg(result).arg(error)<<recvJson;
    if(!result)
    {
        emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("退单失败![网络错误]"));
        return false;
    } else {
        if(JSON_STATUSCODE_OK != recvJson[JSON_ERRCODE].toInt())
        {
            result = false;
            emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("退单失败![%1]").arg(recvJson[JSON_MESSAGE].toString()));
            return false;
        } else {
            QJsonObject data = recvJson[JSON_DATA].toObject();
            int status = data[JSON_RECEIVINGSTATUS].toInt();
            if(1==status) {
                emit showAlert(AlertForm::SUCCESS, QString::fromLocal8Bit("退单成功"));
                //m_OrderEntryMutex.lock(); //必须提前加锁，否则后期订单ID会变更;
                //获取POS退单成功,OMS服务端返回的RefundFmId ( 此字段只有星巴克APP SVC卡支付的case,才会使用到 )
                QString refundFmIdTemp = data[JSON_REFUNDFMID].toString();
                int orderStatus = data[JSON_ORDERSTATUS].toInt();
                OrderObject* orderObject = m_FmOrdersMap.value(orderId);
                int oldOrderStatus = orderObject->orderStatus;
                orderObject->orderStatus = orderStatus;
                orderObject->refundFmId = refundFmIdTemp;
                emit changeOrderStatus(orderObject, oldOrderStatus);
                emit doHideMainShowFloatFrom();
                //退货订单，将此订单添加到simphony 模拟点单列表中；
                QLOG_INFO() << QString("[<<<<---FmTakeout _RefundOrder: orderObject->id:%1 , orderObject->orderStatus:%2 --->>>>]").arg(orderObject->id).arg(orderObject->orderStatus);
                QLOG_INFO() << QString("[<<<<---FmTakeout _RefundOrder: orderObject->id:%1 , orderObject->isCancle:%2 --->>>>]").arg(orderObject->id).arg(orderObject->isCancle);
                if (OrderObject::Refunded == orderObject->orderStatus && OrderObject::SimExceptSale != oldOrderStatus && OrderObject::SimExceptRefund != oldOrderStatus) {
                    //只有退单成功 且 是录POS 成功的才进行加锁；
                    emit doLockFloatForm();
                    m_bFloatFromLockSt = true; //更新悬浮框的锁定状态 =true;
                    //能退单成功就肯定能断言，此订单是没有录过退货的
                    // 判断Simphony 队列中的订单是否已经存在:不存在(Simphony已经点单完成后会移除)则添加； 如果存在(说明此订单还拟点单)，则需要直接向现存在Sim有效队列中的记录移除;没有模
                    m_OrderEntryMutex.lock();
                    if(!m_simValidOrdersList.contains(orderObject->id))   //不存在队列中，则将其加入到队列中；
                    {
                        QLOG_INFO() << QString("[<<<<---FmTakeout _RefundOrder: orderId:%1 ;(SimProcOrderDB::getInstance().isRefundOrder:--->>>>]").arg(orderObject->id)<<SimProcOrderDB::getInstance().isRefundOrder(orderObject->id);
                        //m_simValidOrdersList.append(orderObject->id);  //insert(0,orderObject->id) //POS容易遗漏录入退货订单
                        m_simValidOrdersList.insert(0,orderObject->id);
                        orderObject->pushOrderType = 0;
                        orderObject->pushOrderTimes = 0;
                    }else{  //如果已经存在队列中，就是POS还没有录入销售订单成功；
                        m_simValidOrdersList.removeOne(orderObject->id);
                    }
                    QLOG_INFO() << QString("[<<<<---FmTakeout _RefundOrder:  m_simValidOrdersList.num:%1 --->>>>]")<< m_simValidOrdersList.count();
                    QLOG_INFO() << QString("[<<<<---FmTakeout _RefundOrder:  m_simValidOrdersList:%1 --->>>>]")<< m_simValidOrdersList;
                    QLOG_INFO() << QString("[<<<<---FmTakeout _RefundOrder:  _ClickOMSAssignArea --->>>>]");
                    m_OrderEntryMutex.unlock();
                    _ClickOMSAssignArea(); //必须执行，否则退货，点击取消后，就不会再提醒了；
                //录正向销售单报错的处理机制;
                } else if(OrderObject::SimExceptSale == oldOrderStatus) {
                    m_OrderEntryMutex.lock();
                    m_simValidOrdersList.removeOne(orderObject->id);
                    m_OrderEntryMutex.unlock();
                //正向单已经录入成功,录退单报错的的处理机制;
                } else if(OrderObject::SimExceptRefund == oldOrderStatus){
                    emit doLockFloatForm();
                    m_bFloatFromLockSt = true; //更新悬浮框的锁定状态 =true;
                    m_OrderEntryMutex.lock();
                    if(!m_simValidOrdersList.contains(orderObject->id))   //不存在队列中，则将其加入到队列中；
                    {
                        QLOG_INFO() << QString("[<<<<---FmTakeout _RefundOrder: SimExceptRefund : orderId:%1 ;(SimProcOrderDB::getInstance().isRefundOrder:--->>>>]").arg(orderObject->id)<<SimProcOrderDB::getInstance().isRefundOrder(orderObject->id);
                        m_simValidOrdersList.insert(0,orderObject->id);
                        orderObject->pushOrderType = 0;
                        orderObject->pushOrderTimes = 0;
                    }
                    QLOG_INFO() << QString("[<<<<---FmTakeout _RefundOrder:SimExceptRefund :  m_simValidOrdersList.num:%1 --->>>>]")<< m_simValidOrdersList.count();
                    QLOG_INFO() << QString("[<<<<---FmTakeout _RefundOrder:SimExceptRefund :  m_simValidOrdersList:%1 --->>>>]")<< m_simValidOrdersList;
                    QLOG_INFO() << QString("[<<<<---FmTakeout _RefundOrder:SimExceptRefund :  _ClickOMSAssignArea --->>>>]");
                    m_OrderEntryMutex.unlock();
                    _ClickOMSAssignArea(); //必须执行，否则退货，点击取消后，就不会再提醒了；
                }
                //m_OrderEntryMutex.unlock(); //必须放开锁的范围；否则会出错；
            } else {
                emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("退单失败![%1]").arg(recvJson[JSON_ERRMSG].toString()));
                return false;
            }
        }
    }
    return result;
}


void FlowControl::_ReportOMSRecordOrderInfo()
{
    QLOG_INFO()<<"[<<<<----FlowControl::_ReportOMSRecordOrderInfo ---->>>>>]";
    if(m_orderRecordRepOMSList.isEmpty())
        return ;
    m_RepOMSRecordOrderMutex.lock();
    RepOMSRecordOrderInfo* RepOMSRecOrderIn = NULL;
    QList<RepOMSRecordOrderInfo*>::iterator i;
    for (i = m_orderRecordRepOMSList.begin(); i != m_orderRecordRepOMSList.end(); ++i) {
       RepOMSRecOrderIn = (*i);   //*i 使用*运算符获取遍历容器中所指的元素;
       if (1==RepOMSRecOrderIn->status.toInt() || (2==RepOMSRecOrderIn->status.toInt() && 0==RepOMSRecOrderIn->reqResult) ) {
           break;
       } else {
           RepOMSRecOrderIn = NULL;
       }
    }

    if(!RepOMSRecOrderIn){
        QLOG_INFO()<<"[<<<<----FlowControl::_ReportOMSRecordOrderInfo  m_orderRecordRepOMSList size: ---->>>>>]"<< m_orderRecordRepOMSList.size();
        //上面的汇报OMS订单入机状态的汇报列表 遍历循环后：如果出现  RepOMSRecOrderIn == NULL;不能从List容器的头部移除已汇报成功结果【注意，必须是订单已经成功入机的订单，而非是入机失败，汇报OMS成功的订单】;
        m_RepOMSRecordOrderMutex.unlock();
        return ;
    }
    //准备https请求,准备向OMS汇报订单的入机情况;
    if(m_reportOMSRecordOrderSocket==NULL)
        m_reportOMSRecordOrderSocket =new BillSocket(this);
    QString error;
    bool result;
    QJsonObject sendJson;
    QJsonObject recvJson;
    m_reportOMSRecordOrderSocket->SetSslConfig();
    QLOG_INFO()<<"FlowControl::_ReportOMSRecordOrderInfo load ssl";
    //组装POST请求数据;
    sendJson.insert("orderNo",RepOMSRecOrderIn->orderNo);
    sendJson.insert("type",RepOMSRecOrderIn->type);
    sendJson.insert("status",RepOMSRecOrderIn->status);
    sendJson.insert("opUser",RepOMSRecOrderIn->opUser);
    sendJson.insert("recordDate",RepOMSRecOrderIn->recordDate);
    sendJson.insert("storeId",RepOMSRecOrderIn->storeId);
    sendJson.insert("remark",RepOMSRecOrderIn->remark);
    sendJson.insert("checkNo",RepOMSRecOrderIn->checkNo);

    QLOG_INFO() << QString("[<<<<---_ReportOMSRecordOrderInfo:Begin--->>>>][requestData:%1]")<<sendJson;
    m_reportOMSRecordOrderSocket->SetUrl(QUrl(ConfigManger::GetInstance().GetLoginServerUrl()+
                               ConfigManger::GetInstance().GetInterfaceName(INI_INTERFACE_REPORTOMSRECORDORDER)));
    QLOG_INFO()<<QString("[<<<<---Report OMS Record Order Entry POS Info--->>>>][requestUrl:]") << ConfigManger::GetInstance().GetLoginServerUrl() +
                 ConfigManger::GetInstance().GetInterfaceName(INI_INTERFACE_REPORTOMSRECORDORDER);
    result = m_reportOMSRecordOrderSocket->PostRequest(sendJson, recvJson, error);
    QLOG_INFO() << QString("[<<<<---Report OMS Record Order Entry POS Info Finish--->>>>][result:%1][msg:%2][orderId:%3]")
                   .arg(result).arg(error).arg(RepOMSRecOrderIn->orderNo)<<recvJson;
    if(!result) {
        emit setNetStatus(QString::fromLocal8Bit("<font color='#ff0000'>网络不稳定,正在重试</font>"));
    } else {
        emit setNetStatus(QString::fromLocal8Bit("正常"));
        if(JSON_STATUSCODE_OK != recvJson[JSON_ERRCODE].toInt()) {
            QString error = recvJson[JSON_ERRMSG].toString();
            QLOG_ERROR()<< QString("[<<<<---Report OMS Record Order Entry POS Info Error--->>>>][msg->%1]").arg(error);
            result=false;
            m_orderRecordRepOMSList.removeOne(RepOMSRecOrderIn);
            m_orderRecordRepOMSList.append(RepOMSRecOrderIn);
        } else {
            //解析汇报订单入机POS状态成功;
            result=true;
            if(1==RepOMSRecOrderIn->status.toInt()){
                //只有订单成功入机的订单，才能将此订单从 List容器中移除;否则必须保留在此容器中 避免重复多次向OMS汇报;
                QLOG_INFO()<< QString("[<<<<---Report OMS Record Order Entry POS Info successful,Remove orderId:%1--->>>>][msg->%2]").arg(RepOMSRecOrderIn->orderNo).arg(RepOMSRecOrderIn->remark);
                m_orderRecordRepOMSList.removeOne(RepOMSRecOrderIn);
                delete RepOMSRecOrderIn;
            } else {
                //订单入机失败的订单，不能从 List容器中移除;否则 同笔订单的入机异常情况，会出现多次 或一直向oms回报的情况;
                RepOMSRecOrderIn->reqResult=1;
                QLOG_INFO()<< QString("[<<<<---Report OMS Record Order Entry POS Info successful,Reserve orderId:%1--->>>>][msg->%2]").arg(RepOMSRecOrderIn->orderNo).arg(RepOMSRecOrderIn->remark);
            }
        }
    }
    m_RepOMSRecordOrderMutex.unlock();
}




QString FlowControl::_GetJsonStr(const QJsonObject &json)
{
    return QString(QJsonDocument(json).toJson(QJsonDocument::Compact)).replace("\"","");
}

QJsonObject FlowControl::_PackHttpReplyJson(const int status, const QString &msg, const QJsonObject &data,const int& iscontinue)
{
    QJsonObject rObj;
    rObj.insert("statusCode", status);
    rObj.insert("msg", msg);
    rObj.insert("iscontinue",iscontinue);
    rObj.insert("data", data);
    return rObj;
}

void FlowControl::onPullDishes()
{
    if(!m_bLoginResult)
    {
        emit showAlert(AlertForm::MSGERROR,    QString::fromLocal8Bit("门店还未登录"));
        return ;
    }
    QString error;
    bool result;
    QJsonObject sendJson;
    QJsonObject recvJson;

    m_dishesMap.clear();

    sendJson = DataManger::GetInstance().GetStoreChannelInfoData();
    emit showAlert(AlertForm::LOADING, QString::fromLocal8Bit("正在获取平台列表......"));
    QLOG_INFO() << QString("[<<<<---PullDishes:GetStoreChannelInfo Begin--->>>>][requestData:%1]")<<sendJson;
    result = m_pullDishesSocket->PostRequest(sendJson, recvJson, error);
    QLOG_INFO() << QString("[<<<<---PullDishes:GetStoreChannelInfo Finish--->>>>][result:%1][msg:%2][recvData:%3]")
                   .arg(result).arg(error)<<recvJson;
    if(!result)
    {
        emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("获取平台列表失败![网络错误]"));
    }else
    {
        //recvJson = QJsonDocument::fromJson("{\"statusCode\":100,\"msg\":\"s\",\"channels\":[ {\"code\":\"bdwm\",\"name\":\"百度外卖\",\"status\":1},{\"code\":\"mtwm\",\"name\":\"美团外卖\",\"status\":0},{\"code\":\"eleme2\",\"name\":\"饿了么\",\"status\":1}]}").object();


        if(JSON_STATUSCODE_OK != recvJson[JSON_STATUSCODE].toInt())
        {
            emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("获取平台列表失败![%1]").arg(recvJson[JSON_MESSAGE].toString()));
        }else
        {
            // 分别获取每个平台的菜品信息
            QJsonArray jaChannels = recvJson[JSON_SHOPSTATUS].toArray();
            foreach(QJsonValue v, jaChannels)
            {
                QJsonObject channel =  v.toObject();
                QString channelName = channel["name"].toString();
                QString channelCode = channel["code"].toString();

                sendJson = DataManger::GetInstance().GetPullDishesData(channelCode);
                emit showAlert(AlertForm::LOADING, QString::fromLocal8Bit("正在获取[%1]产品信息......").arg(channelName));
                QLOG_INFO() << QString("[<<<<---PullDishes:Dishes %1  Begin--->>>>][requestData:%2]").arg(channelName)<<sendJson;
                result = m_pullDishesSocket->PostRequest(sendJson, recvJson, error);
                QLOG_INFO() << QString("[<<<<---PullDishes:Dishes Finish--->>>>][result:%1][msg:%2][recvData:%3]")
                               .arg(result).arg(error)<<recvJson;
                if(!result)
                {
                    emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("获取[%1]产品信息失败![网络超时]").arg(channelName));
                    break;
                }else
                {
                    if(JSON_STATUSCODE_OK != recvJson[JSON_STATUSCODE].toInt())
                    {
                        //result = false;
                        //emit showAlert(AlertForm::ERROR, QString("获取[%1]产品信息失败![%2]").arg(channelName, recvJson[JSON_MESSAGE].toString()));
                        //break;
                    }else
                    {
                        QMultiMap<QString , dishesObject> tmpMap;
                        QJsonArray categoriesJA =recvJson["categories"].toArray();
                        foreach(QJsonValue jv, categoriesJA)
                        {
                            QJsonObject jo = jv.toObject();
                            QString categoryName = jo["name"].toString();
                            QString categoryRank = QString::number(jo["rank"].toInt());
                            QJsonArray dishesJA = jo["dishes"].toArray();
                            foreach(QJsonValue jv1, dishesJA)
                            {
                                QJsonObject jo1 = jv1.toObject();
                                dishesObject dishesObj;
                                dishesObj.FetchDataFromJson(jo1);
                                tmpMap.insert(categoryName+":"+categoryRank, dishesObj);
                            }
                        }
                        m_dishesMap.insert(channelName+":"+channelCode, tmpMap);
                    }
                }
            }
            if(!m_dishesMap.isEmpty())
            {
                emit hideAlert();
                emit iniDishesData(m_dishesMap);
            }else
            {
                emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("未获取到产品信息!"));
            }
        }
    }
}

void FlowControl::onUpdDishes(QString channelCode, QMap<QString, int> dishes)
{
    QString error;
    bool result;
    QJsonObject sendJson;
    QJsonObject recvJson;

    sendJson = DataManger::GetInstance().GetUpdDishesData(channelCode, dishes);

    emit showAlert(AlertForm::LOADING, QString::fromLocal8Bit("正在同步产品销售状态......"));

    QLOG_INFO() << QString("[<<<<---UpdDishes:Begin--->>>>][requestData:%1]")<<sendJson;
    result = m_pullDishesSocket->PostRequest(sendJson, recvJson, error);
    QLOG_INFO() << QString("[<<<<---UpdDishes:Finish--->>>>][result:%1][message:%2][recvData:%3]")
                   .arg(result).arg(error)<<recvJson;
    if(!result)
    {
        emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("同步产品销售状态失败![网络错误]"));
    }else
    {
        if(JSON_STATUSCODE_OK != recvJson[JSON_STATUSCODE].toInt())
        {
            result = false;
            emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("同步产品销售状态失败![%1]").arg(recvJson[JSON_MESSAGE].toString()));
        }else
        {
            emit hideAlert();
            emit processDishiesSuccssful(channelCode, dishes);
        }
    }
}

void FlowControl::onUpdDishesForRef(QString channelCode, QMap<QString, int> dishes)
{
    QString error;
    bool result;
    QJsonObject sendJson;
    QJsonObject recvJson;

    sendJson = DataManger::GetInstance().GetUpdDishesData(channelCode, dishes);

    QLOG_INFO() << QString("[<<<<---UpdDishesForRef:Begin--->>>>][requestData:%1]")<<sendJson;
    result = m_pullDishesSocket->PostRequest(sendJson, recvJson, error);
    QLOG_INFO() << QString("[<<<<---UpdDishesForRef:Finish--->>>>][result:%1][msg:%2][recvData:%3]")
                   .arg(result).arg(error)<<recvJson;
}

void FlowControl::onSetStoreOperatingStatus(const QString &channelCode, const QString &channelName, int business_status)
{
    //TODO
    Q_UNUSED(channelName);
    return ;
    QString error;
    bool result;
    QJsonObject sendJson;
    QJsonObject recvJson;

    sendJson = DataManger::GetInstance().GetOperatingStatusData(channelCode, business_status);
    emit showAlert(AlertForm::LOADING, QString::fromLocal8Bit("正在设置门店营业状态......"));
    QLOG_INFO() << QString("[<<<<---SetStoreOperatingStatus:Begin--->>>>][requestData:%1]")<<sendJson;
    m_pullDishesSocket->SetUrl(QUrl(ConfigManger::GetInstance().GetStoreServerUrl()+
                               ConfigManger::GetInstance().GetInterfaceName(INI_INTERFACE_UPDATESTATE)));
    qDebug()<<QUrl(ConfigManger::GetInstance().GetStoreServerUrl()+
                   ConfigManger::GetInstance().GetInterfaceName(INI_INTERFACE_UPDATESTATE));
    result = m_pullDishesSocket->PostRequest(sendJson, recvJson, error);
    QLOG_INFO() << QString("[<<<<---SetStoreOperatingStatus:Finish--->>>>][result:%1][msg:%2][recvData:%3]")
                   .arg(result).arg(error)<<recvJson;
    if(!result)
    {
        emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("设置门店营业状态失败![网络错误]"));
    }else
    {
        if(JSON_STATUSCODE_OK != recvJson[JSON_STATUSCODE].toInt())
        {
            emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("设置门店营业状态失败![%1]").arg(recvJson[JSON_MESSAGE].toString()));
        }else
        {
            emit hideAlert();
            emit setStoreOperatingStatusFinsh(channelCode);
        }
    }
}

void FlowControl::onDailyReport()
{
    if(!m_bLoginResult)
    {
        emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("门店未登录"));
        return;
    }
    QString error;
    bool result;
    QJsonObject sendJson;
    QJsonObject recvJson;
    QString m_business=QDateTime::currentDateTime().toString("yyyyMMdd");

    sendJson = DataManger::GetInstance().GetDayReportData(m_business);

    emit showAlert(AlertForm::LOADING, QString::fromLocal8Bit("正在通信......"));

    QLOG_INFO() << QString("[<<<<---Get DailyReport:Begin--->>>>][requestData:%1]")<<sendJson;
    result = m_procOrderSocket->PostRequest(sendJson, recvJson, error);
    QLOG_INFO() << QString("[<<<<---Get DailyReport:Finish--->>>>][result:%1][msg:%2][recvData:%3]")
                   .arg(result).arg(error)<<recvJson;
    if(!result)
    {
        emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("获取入账日结失败![网络错误]"));
    }else
    {
        if(JSON_STATUSCODE_OK != recvJson[JSON_STATUSCODE].toInt())
        {
            result = false;
            emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("获取入账日结失败![%1]").arg(recvJson[JSON_MESSAGE].toString()));
        }else
        {
            recvJson.insert(JSON_STORENAME,m_storeName);
            recvJson.insert(JSON_POSNO,m_posId);
            recvJson.insert(JSON_STOREID,m_storeId);
            recvJson.insert(JSON_USERID,m_cashierId);
            recvJson.insert(JSON_USERNAME,m_cashierName);
            recvJson.insert(JSON_BUSINESSDATE,m_business);
            emit hideAlert();
            emit showDailyReportData(recvJson);
        }
    }
}

void FlowControl::_CrondClearExpireOrder()
{
    //QDateTime currentDateTime= QDateTime::currentDateTime();  //--按秒数来验证ok--
    QDate currentDate= QDate::currentDate();
    //QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---_CrondClearExpireOrder: 清理内存中订单数据的清理日期：%1 --->>>>]").arg(currentDateTime.toString("yyyy-MM-dd hh:mm:ss")); //--按秒数来验证OK--
    QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---_CrondClearExpireOrder: 清理内存中订单数据的清理日期：%1 --->>>>]").arg(currentDate.toString("yyyy-MM-dd"));
    OrderObject *order=NULL;
    m_OrderEntryMutex.lock();
    foreach (order, m_FmOrdersMap.values()) {
        //QDateTime createDateTime = QDateTime::fromString(order->createTime,"yyyy-MM-dd hh:mm:ss"); //--按秒数来验证ok--
        QDate createDate = QDate::fromString( (order->createTime).mid(0,10),"yyyy-MM-dd");
        //QLOG_INFO()<<QString("[<<<<---_CrondClearExpireOrder-> order->createTime:%1--->>>>]").arg(order->createTime); //--按秒数来验证ok--
        QLOG_INFO()<<QString("[<<<<---_CrondClearExpireOrder-> order  createDate:%1--->>>>]").arg(createDate.toString("yyyy-MM-dd"));
        //qint64 seconds = createDateTime.secsTo(currentDateTime);  //--按秒数来验证ok--
        qint64 days = createDate.daysTo(currentDate);
        //QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---_CrondClearExpireOrder: ClearExpireOrder: 相差多少秒:%1--->>>>]").arg(seconds); //--按秒数来验证ok--
        QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---_CrondClearExpireOrder: ClearExpireOrder: 相差多少天:%1--->>>>]").arg(days);
        //创建订单时间，超过当前时间 三十分就进行清理；
        //if(seconds>=60*5)  //--按秒数来验证ok--
        if(days>=1)
        {
            QLOG_INFO()<<QString("[<<<<---_CrondClearExpireOrder: ClearExpireOrder: Emit Signal:Clear Order  orderID:%1--->>>>]").arg(order->id);
            emit clearorder(order->id,order->orderStatus);
            m_FmOrdersMap.value(order->id)->deleteLater();
            m_FmOrdersMap.remove(order->id);
            // 任何情况情况下都不能清理 Simphony获取的有效队列【除非已经被simphony处理过的数据】;目前已经在POS 触发的Action1:_ResponseSimReqFristOrderData 中做数据清理了
            // m_simValidOrdersList.removeOne(order->id);
        }
    }
    m_OrderEntryMutex.unlock();

    SimProcOrderDB::getInstance().deleteOrderRecord(QDate::currentDate().addDays(-7).toString("yyyyMMdd"));
}

bool FlowControl::_ResponseHttpRequest(const QJsonObject &content,QJsonObject &data, QString& error)
{
    QLOG_INFO()<<__FUNCTION__;
    bool result = true;
    /****校验Http请求参数有效性: 校验参数->actionId不存在****/
    if(!content.contains("actionId")) {
        error =QString::fromLocal8Bit("解析Http请求参数:参数中没有actionId");
        result = false;
    }/****校验Http请求参数有效性: 校验参数->actionId存在****/
    else {
        int actionId;
        if(content["actionId"].isString()){
            actionId=content["actionId"].toString().toInt();
        } else {
            actionId=content["actionId"].toInt();
        }
        QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---Http请求[action:%1] --->>>>]").arg(actionId);
        /****校验请求参数actionId的具体数值:****/
        switch (actionId) {
        case 1://simphony拉取订单
            result=_ResponseSimphony01Request(content,data,error);
            break;
        case 2://simphony确认接单
            result=_ResponseSimphony02Request(content,data,error);
            break;
        case 3://simphony取消接单
            result=_ResponseSimphony03Request(content,data,error);
            break;
        case 4://simphony汇报小票号信息回复
            result=_ResponseSimphony04Request(content,data,error);
            break;
        case 5://simphony更新订单数据到POS本地数据库以便POS打印小票及汇总单信息 回复
            result=_ResponseSimphony05Request(content,data,error);
            break;
        case 6://simphony汇报SIM录单异常 回复
            result=_ResponseSimphony06Request(content,data,error);
            break;
        case 11://FM OMS推送订单
            result=_ResponseOMS11Request(content,data,error);
            break;
        case 12://推送门店营业状态
            result=_ResponseOMS12Request(content,data,error);
            break;
        case 21://盒马生鲜 推送订单
            result=_ResponseHM21Request(content,data,error);
            break;
        default:
            error =QString::fromLocal8Bit("解析Http请求actionId值不在规定的接口文档内");
            result = false;
            break;
        }
    }
    return result;
}

bool FlowControl::_ResponseSimphony01Request(const QJsonObject &content, QJsonObject &data, QString &error)
{
    QLOG_INFO()<<__FUNCTION__;
    bool result=true;
    if(!m_bLoginResult&&content.contains("storeId")) {
        result=_ResponseSimReqTryLogin(content,error);
    }

    if(result/*&&content.contains("orderId")*/){
        result=_ResponseSimReqFristOrderData(content, data,error,content["orderId"].toString());
    } else {
        result = false;
        if(error.isEmpty()) {
            error=QString::fromLocal8Bit("Response Simphony_Script Request 01: Login Store Failed");
        }
    }
    return result;
}

bool FlowControl::_ResponseSimphony02Request(const QJsonObject &content, QJsonObject &data, QString &error)
{
    Q_UNUSED(content);
    Q_UNUSED(data);
    Q_UNUSED(error);
    return true;
}
bool FlowControl::_ResponseSimphony03Request(const QJsonObject &content, QJsonObject &data, QString &error)
{
    Q_UNUSED(content);
    Q_UNUSED(data);
    Q_UNUSED(error);
    return true;
}
bool FlowControl::_ResponseSimphony04Request(const QJsonObject &content, QJsonObject &data, QString &error)
{
    QLOG_INFO()<<__FUNCTION__;
    bool result=true;
    if(m_bLoginResult&&content.contains("orderId")){
        QString orderId=content["orderId"].toString();
        QString posCheckNo=content["posSaleId"].toString();
        if(posCheckNo.isEmpty()) {
            posCheckNo=m_orderIdToPosCheckNoMap.value(orderId);
        }
        if(!posCheckNo.isEmpty()&&!orderId.isEmpty()) {
            if(!m_orderIdToPosCheckNoMap.contains(orderId)) {
                QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---Simphony_Script请求[ACTION:04:汇报小票号] 订单:%1 , 汇报小票号:%2:--->>>>]").arg(orderId,posCheckNo);
                m_orderIdToPosCheckNoMap.insert(orderId,posCheckNo);
            }

            OrderObject* order_p =  m_FmOrdersMap.value(orderId);
            if (!order_p) {
                QLOG_ERROR()<<QString::fromLocal8Bit("[<<<<---%1订单并不存在m_FmOrdersMap[键值对]中;m_FmOrdersMap.size()=%2--->>>>]").arg(orderId).arg(m_FmOrdersMap.size());
                error=QString::fromLocal8Bit("Request Action04: %1 Delivery Order Don't Exist In m_FmOrdersMap[key-map] m_FmOrdersMap.size()=%2").arg(orderId).arg(m_FmOrdersMap.size());
                emit doUnLockFloatFrom();//****************解锁悬浮框**************//
                m_bFloatFromLockSt = false; //更新悬浮框的锁定状态 =false;
                return false;
            }

            if(m_simValidOrdersList.contains(orderId)) {
                /***** 汇报POS小票号是否成功；begin:*********/
                bool bRetReportCheckNo = false;
                if(order_p->pushOrderType==1) {
                    SimProcOrderDB::getInstance().updatePushOrderStatus(orderId,1);
                    order_p->isPush= true;
                } else if(0 == order_p->pushOrderType) {
                    SimProcOrderDB::getInstance().updateRefundOrderStatus(orderId,1);
                    order_p->isCancle = true;
                }
                bRetReportCheckNo = SimProcOrderDB::getInstance().updatePosOrderCheckNo(orderId,posCheckNo);
                /***** 解析 汇报POS小票号是否成功:bRetReportCheckNo:true->成功********/
                QJsonObject rObj, cObj;
                rObj.insert("fm_cmd", "");
                rObj.insert("fm_ver", "1.0");
                cObj.insert("pay_id", "002");
                cObj.insert("pay_str", QString::fromLocal8Bit("非码外卖"));
                cObj.insert("paid_trans_id",orderId);
                if(bRetReportCheckNo){  //已经汇报完小票号，因此必须从 m_simValidOrdersList 列表中移除;
                    cObj.insert("reqResult",1); // 汇报POS小票号结果：[1:成功；0:失败]
                    rObj.insert("pay_id", cObj);
                    data = rObj;
                    m_OrderEntryMutex.lock();
                    m_simValidOrdersList.removeOne(orderId);
                    m_OrderEntryMutex.unlock();
                } /***** 解析 汇报POS小票号是否成功:bRetReportCheckNo:true->成功*****/
                else{
                    result=false;
                    error=QString::fromLocal8Bit("Report POS Check Num Failed");
                    // 即使汇报小票号失败，同样也必须将此订单从 m_simValidOrdersList 列表中移除:【汇报小票号的前提条件就是:POS已经结单完成】；
                    cObj.insert("reqResult",0); // 汇报POS小票号结果：[1:成功；0:失败]
                    rObj.insert("pay_id", cObj);
                    data = rObj;
                    m_OrderEntryMutex.lock();
                    m_simValidOrdersList.removeOne(orderId);
                    m_OrderEntryMutex.unlock();
                }

                //新增业务逻辑,针对汇报小票号成功的订单需要;添加到 向OMS汇报入机情况的队列中;
                m_RepOMSRecordOrderMutex.lock();
                RepOMSRecordOrderInfo* repOMSRecordOrder = NULL;
                if(!m_orderRecordRepOMSList.isEmpty()){
                    QList<RepOMSRecordOrderInfo*>::iterator i;
                    for (i = m_orderRecordRepOMSList.begin(); i != m_orderRecordRepOMSList.end(); ++i) {
                       repOMSRecordOrder = (*i);   //*i 使用*运算符获取遍历容器中所指的元素;
                       if (orderId == repOMSRecordOrder->orderNo) {
                           break;
                       } else {
                           repOMSRecordOrder = NULL;
                       }
                    }
                }
                if (!repOMSRecordOrder){
                    repOMSRecordOrder = new RepOMSRecordOrderInfo();
                    repOMSRecordOrder->reqResult = 0;
                } else {
                    //不管之前入机是什么报错,目前入机成功，必须再次汇报;
                    m_orderRecordRepOMSList.removeOne(repOMSRecordOrder); //剔除已经存在的，更新完数据后，在添加进来;
                    repOMSRecordOrder->reqResult = 0;
                }
                repOMSRecordOrder->orderNo = orderId;
                repOMSRecordOrder->type = (6 == order_p->orderStatus)?QString::fromLocal8Bit("6"):QString::fromLocal8Bit("3");
                repOMSRecordOrder->status = QString::fromLocal8Bit("1");
                repOMSRecordOrder->opUser = m_cashierName;
                repOMSRecordOrder->recordDate = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");;
                repOMSRecordOrder->storeId = m_storeId;
                repOMSRecordOrder->remark = QString::fromLocal8Bit("入机成功");
                repOMSRecordOrder->checkNo = posCheckNo;
                QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---FlowControl::_ResponseSimphony04Request:m_orderRecordRepOMSList.append() orderId:%1 orderStatus:%2 checkNo:%3--->>>>]").arg(orderId).arg(repOMSRecordOrder->type).arg(posCheckNo);
                m_orderRecordRepOMSList.append(repOMSRecordOrder);
                m_RepOMSRecordOrderMutex.unlock();
            }
            /* 汇报完小票号后，就必须将其从 m_simValidOrdersList  列表中移除;
            else {
            } */
        } else {
            result=false;
            error=QString::fromLocal8Bit("Request Action04: Delivery OrderId Or Check Num Can't Empty");
        }
    } else {
        result=false;
        error=QString::fromLocal8Bit("Request Action04: Request Pragram Error");
    }
    emit doUnLockFloatFrom();//****************解锁悬浮框**************//
    m_bFloatFromLockSt = false; //更新悬浮框的锁定状态 =false;
    return result;
}


bool FlowControl::_ResponseSimphony05Request(const QJsonObject &content, QJsonObject &data, QString &error)
{
    QLOG_INFO()<<__FUNCTION__;
    bool result=true;
    if(m_bLoginResult&&content.contains("orderId")){
        QString orderId=content["orderId"].toString();
        QString posCheckNo=content["posSaleId"].toString();
        if(posCheckNo.isEmpty())
        {
            error=QString::fromLocal8Bit("Request Action05: %1 Delivery Order: Check Num Can't Empty").arg(orderId);
            return false;
        }
        if(!posCheckNo.isEmpty()&&!orderId.isEmpty())
        {
            OrderObject* order_p =  m_FmOrdersMap.value(orderId);
            if (!order_p){
                QLOG_ERROR()<<QString::fromLocal8Bit("[<<<<---%1订单并不存在m_FmOrdersMap[键值对]中;m_FmOrdersMap.size()=%2--->>>>]").arg(orderId).arg(m_FmOrdersMap.size());
                error=QString::fromLocal8Bit("Request Action05: %1 Delivery Order Don't Exist In m_FmOrdersMap[key-map] m_FmOrdersMap.size()=%2").arg(orderId).arg(m_FmOrdersMap.size());
                return false;
            }
            //更新小票号;
            if(!m_orderIdToPosCheckNoMap.contains(orderId))
            {
                QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---Simphony_Script请求[ACTION:05: 更新POS本地数据库打印信息] %1订单已经成功推送给simphony:--->>>>]").arg(orderId);
                m_orderIdToPosCheckNoMap.insert(orderId,posCheckNo);
            } else {
                if(OrderObject::Refunded==order_p->orderStatus){
                    if(posCheckNo != m_orderIdToPosCheckNoMap.value(order_p->id)){
                        m_orderIdToPosCheckNoMap.remove(order_p->id);
                        m_orderIdToPosCheckNoMap.insert(orderId,posCheckNo);
                    }
                }
            }

            if(m_simValidOrdersList.contains(orderId))
            {
                /***** 更新 POS本地数据库的打印信息是否成功；begin:*********/
                int retSyncOrderPrintInfo = 0;  //默认是同步POS本地数据失败;
                bool bRet = PrintSumBillPosDB::getInstance().isOrderAndCknoSumBillExist(orderId,posCheckNo);
                if (bRet){
                    retSyncOrderPrintInfo = 1;
                } /*****POS本地数据库不存在 orderId &&posCheckNo*********/
                else{
                    bRet = PrintSumBillPosDB::getInstance().insertOrderSumBill(order_p,posCheckNo);
                    if (bRet){
                      retSyncOrderPrintInfo = 1;
                    }
                } /***** 更新 POS本地数据库的打印信息是否成功；end:********/
                /***** 解析 同步更新POS本地数据库是否成功:retSyncOrderPrintInfo:1->成功********/
                if(retSyncOrderPrintInfo){
                    // 还没汇报完小票号，因此还不能从 m_simValidOrdersList 列表中移除;
                    QJsonObject rObj, cObj;
                    rObj.insert("fm_cmd", "");
                    rObj.insert("fm_ver", "1.0");
                    cObj.insert("pay_id", "002");
                    cObj.insert("pay_str", QString::fromLocal8Bit("FmTakeout"));
                    cObj.insert("reqResult",retSyncOrderPrintInfo); //同步POS本地数据库打印信息结果：[1:同步成功；0:同步失败]
                    cObj.insert("paid_trans_id",orderId);
                    rObj.insert("pay_id", cObj);
                    data = rObj;
                } /***** 解析 同步更新POS本地数据库是否成功:retSyncOrderPrintInfo:0->失败*****/
                else{
                    result=false;
                    error=QString::fromLocal8Bit("Request Action05:Sync POS Local DataBase-PrintInfo Failed");
                }
            } else {
                m_OrderEntryMutex.lock();
                m_simValidOrdersList.append(orderId);
                m_OrderEntryMutex.unlock();
            }
        } else {
            result=false;
            error=QString::fromLocal8Bit("Request Action05: Delivery OrderId And Check Num Can't Empty");
        }
    } else {
        result=false;
        error=QString::fromLocal8Bit("Request Action05: Pragram Error");
    }
    return result;
}



bool FlowControl::_ResponseSimphony06Request(const QJsonObject &content, QJsonObject &data, QString &error)
{
    QLOG_INFO()<<__FUNCTION__;
    bool result=true;
    if(m_bLoginResult&&content.contains("orderId")){
        QString orderId=content["orderId"].toString();
        QString simExceptCode=content["simExceptCode"].toString();
        QString simExceptMsg=content["simExceptMsg"].toString();

        if(!simExceptCode.isEmpty()&&!orderId.isEmpty()) {
            //*********** 新增一种优化case: 门店店员正在操作POS,从而阻塞插件程序录外卖订单,此时必须解锁悬浮框，从而减少Simphony队列中first出现OMS退单的请求; begin ***********//
            //此时的订单号时固定给的620620 [action:6,simExceptCode=20]
            if( 20 == simExceptCode.toInt() ){
                error=QString::fromLocal8Bit("Request Action06: Partner is serving Offline Customer ");
                QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---_ResponseSimphony06Request::%1--->>>>>]").arg(error);
                emit doUnLockFloatFrom(); //****************解锁悬浮框*****************//
                m_bFloatFromLockSt = false; //更新悬浮框的锁定状态 =false;
                QJsonObject rObj, cObj;
                rObj.insert("fm_cmd", "");
                rObj.insert("fm_ver", "1.0");
                cObj.insert("pay_id", "002");
                cObj.insert("pay_str", QString::fromLocal8Bit("FmTakeout"));
                cObj.insert("reqResult",1); //响应SIM汇报异常结果：[1:处理异常成功；0:处理异常失败]
                cObj.insert("paid_trans_id",orderId);
                rObj.insert("pay_id", cObj);
                data = rObj;

                //新增业务逻辑,针对汇报异常的订单需要;添加到 向OMS汇报入机情况的队列中;
                if(!m_simValidOrdersList.empty()){
                    m_RepOMSRecordOrderMutex.lock();
                    RepOMSRecordOrderInfo* repOMSRecordOrder = NULL;
                    if(!m_orderRecordRepOMSList.isEmpty()) {
                        QList<RepOMSRecordOrderInfo*>::iterator i;
                        for (i = m_orderRecordRepOMSList.begin(); i != m_orderRecordRepOMSList.end(); ++i) {
                            repOMSRecordOrder = (*i);   //*i 使用*运算符获取遍历容器中所指的元素;
                            if (m_simValidOrdersList.first() == repOMSRecordOrder->orderNo) {
                                break;
                            } else {
                                repOMSRecordOrder = NULL;
                            }
                        }
                    }
                    if (!repOMSRecordOrder){
                        repOMSRecordOrder = new RepOMSRecordOrderInfo();
                        repOMSRecordOrder->reqResult = 0;
                    } else {
                        if(simExceptMsg == repOMSRecordOrder->remark && 1==repOMSRecordOrder->reqResult){
                            m_orderRecordRepOMSList.removeOne(repOMSRecordOrder);
                            //repOMSRecordOrder->reqResult = 1; //此时reqResult已经是1了;
                        } else {
                            m_orderRecordRepOMSList.removeOne(repOMSRecordOrder);
                            repOMSRecordOrder->reqResult = 0;
                        }
                    }
                    repOMSRecordOrder->orderNo = m_simValidOrdersList.first();
                    OrderObject* order_temp =  m_FmOrdersMap.value(repOMSRecordOrder->orderNo);
                    if (!order_temp){
                        QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---%1订单并不存在m_FmOrdersMap[键值对]中;m_FmOrdersMap.size()=%2--->>>>]").arg(orderId).arg(m_FmOrdersMap.size());
                        repOMSRecordOrder->type = QString::fromLocal8Bit("0");
                    }else{
                        repOMSRecordOrder->type = order_temp->orderStatus==6?QString::fromLocal8Bit("6"):QString::fromLocal8Bit("3");
                    }
                    repOMSRecordOrder->status = QString::fromLocal8Bit("2");
                    repOMSRecordOrder->opUser = m_cashierName;
                    repOMSRecordOrder->recordDate = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");;
                    repOMSRecordOrder->storeId = m_storeId;
                    repOMSRecordOrder->remark = simExceptMsg;
                    //repOMSRecordOrder->checkNo = QString::fromLocal8Bit("0");
                    QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---FlowControl::_ResponseSimphony06Request:m_orderRecordRepOMSList.append() orderId:%1 simExceptMsg:%2--->>>>]").arg(orderId).arg(simExceptMsg);
                    m_orderRecordRepOMSList.append(repOMSRecordOrder);
                    m_RepOMSRecordOrderMutex.unlock();
                }
                return true;
            }
            //*********** 新增一种优化case: 门店店员正在操作POS,从而阻塞插件程序录外卖订单,此时必须解锁悬浮框，从而减少Simphony队列中first出现OMS退单的请求; end ***********//

            //**************** 根据订单编号找到 非码订单Map容器中订单的详细信息; begin ****************//
            OrderObject* order_p =  m_FmOrdersMap.value(orderId);
            if (!order_p) {
                QLOG_ERROR()<<QString::fromLocal8Bit("[<<<<---%1订单并不存在m_FmOrdersMap[键值对]中;m_FmOrdersMap.size()=%2--->>>>]").arg(orderId).arg(m_FmOrdersMap.size());
                error=QString::fromLocal8Bit("Request Action06: %1 Delivery Order Don't Exist In m_FmOrdersMap[key-map]; m_FmOrdersMap.size()=%2").arg(orderId).arg(m_FmOrdersMap.size());
                emit doUnLockFloatFrom();//****************解锁悬浮框*****************//
                m_bFloatFromLockSt = false; //更新悬浮框的锁定状态 =false;
                return false;
            }
            //**************** 根据订单编号找到 非码订单Map容器中订单的详细信息; end ****************//

            // 判断SIM是否存在错误码: 0:会在汇报完小票号发送此错误码的请求给插件以便做一些特别事件: 解锁悬浮框；1:SIM录单出异常:转移订单tab至异常单、请求sim的有效订单列表、解锁悬浮框:
            int retProcSimExceptCode =0;
            // 特殊处理录单异常的详细case:
            if(simExceptCode.toInt()) {
                QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---_ResponseSimphony06Request:: OrderId:%1,simExceptCode:%2 录单异常--->>>>>]").arg(orderId).arg(simExceptCode.toInt());
                //异常错误码10的case:: 常见的正常业务场景下的异常 这些异常不应该阻塞订单的多次尝试录入，如果没有尝试多次录入的机会将会出现POS机少录订单不出小票的case:更多的详细请参考Simphony脚本中错误码为10情况，
                if(10 == simExceptCode.toInt()){
                    error=QString::fromLocal8Bit("Request Action06 :simExceptCode==10: Catch Sim Refund Auth Exception And Report Success");
                    retProcSimExceptCode = 1;
                    result=true;
                }
                //异常错误码非10的case::
                //simExceptCode ==5: POS录单过程中 同步本地数据库小票信息出现异常时触发多次录单的异常必须捕捉,此时必须解锁悬浮框;[action:6,simExceptCode=5]
                //simExceptCode ==1: POS录单过程中 POS机中没有相应的SKU 的异常必须捕捉,此时必须解锁悬浮框;[action:6,simExceptCode=1]
                else {
                    if(m_simValidOrdersList.contains(orderId)) {
                                        m_OrderEntryMutex.lock();
                                        m_simValidOrdersList.removeOne(orderId);
                                        m_OrderEntryMutex.unlock();
                                        int oldStatus = order_p->orderStatus;
                                        if(6 == oldStatus || OrderObject::SimExceptRefund == order_p->orderStatus){
                                            order_p->orderStatus = OrderObject::SimExceptRefund;
                                        }else{
                                            order_p->orderStatus = OrderObject::SimExceptSale;
                                        }
                                        emit changeOrderStatus(order_p,oldStatus);
                                        error=QString::fromLocal8Bit("Request Action06: Catch Sim Recorded Order Exception And Report Success");
                                        retProcSimExceptCode = 1;
                                        result=true;
                                    }
                }
            } else { //录单正常//
                QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---_ResponseSimphony06Request:: OrderId:%1 录单成功--->>>>>]").arg(orderId);
                error=QString::fromLocal8Bit("Request Action06: Catch Sim Recorded Order Exception And Report Success");
                retProcSimExceptCode = 1;
                result=true;
            }
            //**************** 组装响应SIM录单异常响应********************//
            QJsonObject rObj, cObj;
            rObj.insert("fm_cmd", "");
            rObj.insert("fm_ver", "1.0");
            cObj.insert("pay_id", "002");
            cObj.insert("pay_str", QString::fromLocal8Bit("FmTakeout"));
            cObj.insert("reqResult",retProcSimExceptCode); //响应SIM汇报异常结果：[1:处理异常成功；0:处理异常失败]
            cObj.insert("paid_trans_id",orderId);
            rObj.insert("pay_id", cObj);
            data = rObj;
            //************* 新增业务逻辑,针对汇报异常的订单需要;添加到 向OMS汇报入机情况的队列中;  Begin*************//
            m_RepOMSRecordOrderMutex.lock();
            RepOMSRecordOrderInfo* repOMSRecordOrder = NULL;
            if(!m_orderRecordRepOMSList.isEmpty()){
                QList<RepOMSRecordOrderInfo*>::iterator i;
                for (i = m_orderRecordRepOMSList.begin(); i != m_orderRecordRepOMSList.end(); ++i) {
                    repOMSRecordOrder = (*i);   //*i 使用*运算符获取遍历容器中所指的元素;
                    if (orderId == repOMSRecordOrder->orderNo) {
                        break;
                    } else {
                        repOMSRecordOrder = NULL;
                    }
                }
            }
            if (!repOMSRecordOrder){
                repOMSRecordOrder = new RepOMSRecordOrderInfo();
                repOMSRecordOrder->reqResult = 0;
            } else {
                if(simExceptMsg == repOMSRecordOrder->remark && 1==repOMSRecordOrder->reqResult){
                    m_orderRecordRepOMSList.removeOne(repOMSRecordOrder);
                    //repOMSRecordOrder->reqResult=1; //此时reqResult已经是1了;
                } else {
                    m_orderRecordRepOMSList.removeOne(repOMSRecordOrder);
                    repOMSRecordOrder->reqResult=0;
                }
            }
            repOMSRecordOrder->orderNo = orderId;
            repOMSRecordOrder->type = order_p->orderStatus==6?QString::fromLocal8Bit("6"):QString::fromLocal8Bit("3");
            repOMSRecordOrder->status = QString::fromLocal8Bit("2");
            repOMSRecordOrder->opUser = m_cashierName;
            repOMSRecordOrder->recordDate = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");;
            repOMSRecordOrder->storeId = m_storeId;
            repOMSRecordOrder->remark = simExceptMsg;
            //repOMSRecordOrder->checkNo = QString::fromLocal8Bit("0");
            QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---FlowControl::_ResponseSimphony06Request:m_orderRecordRepOMSList.append() orderId:%1 simExceptMsg:%2--->>>>]").arg(orderId).arg(simExceptMsg);
            m_orderRecordRepOMSList.append(repOMSRecordOrder);
            m_RepOMSRecordOrderMutex.unlock();
            //************* 新增业务逻辑,针对汇报异常的订单需要;添加到 向OMS汇报入机情况的队列中;  end*************//
        } else {
            result=false;
            error=QString::fromLocal8Bit("Request Action06: Delivery OrderId And Sim Exception ErrorCode Can't Empty");
        }
    } else {
        result=false;
        error=QString::fromLocal8Bit("Request Action06: Request Pragram Error");
    }
    //****************解锁悬浮框*****************//
    emit doUnLockFloatFrom();
    m_bFloatFromLockSt = false; //更新悬浮框的锁定状态 =false;
    return result;
}


bool FlowControl::_ResponseOMS11Request(const QJsonObject &content, QJsonObject &data, QString &error)
{
    Q_UNUSED(data);
    QLOG_INFO()<<__FUNCTION__;
    bool result=true;
    if(!m_bLoginResult){
        error = QString::fromLocal8Bit("FMOMS未登录");
        return false;
    }
    else{
        if(content[JSON_ORDER_ID].toString().isEmpty())
        {
            error =QString::fromLocal8Bit("订单号不能为空");
            return false;
        } else {
            if(!m_simValidOrdersList.isEmpty()){
                QString simValidOrderListFirstOne = m_simValidOrdersList.first();
                //缩小锁住订单的条件范围: 服务端推单给插件程序且插件程序拒绝本次订单状态发生变化的请求
                if(content[JSON_ORDER_ID].toString() == simValidOrderListFirstOne && m_bFloatFromLockSt){
                    error =QString::fromLocal8Bit("当前订单正在录POS系统，请耐心等待");
                    return false;
                }
            }
        }

        // 接受到非码oms插过来的订单，进行向队列中进行添加；
        result =  _TryAddOrderPull(content[JSON_ORDER_ID].toString(),content[JSON_CHANNEL].toString());
        /***组装从FM外卖service端的拉单请求参数***/
        if (result) {
            error = QString("success");
            result = true;
        }else {
            error = QString("failed");
            result = false;
        }
    }
    return result;
}

bool FlowControl::_ResponseOMS12Request(const QJsonObject &content, QJsonObject &data, QString &error)
{
    QLOG_INFO()<<__FUNCTION__;
    Q_UNUSED(data);
    //判断当前POS插件是否登录成功: 如果没有登录成功，尝试在次登录;
    bool result = true;
    if(!m_bLoginResult&&content.contains("storeId")) {
        result=_ResponseSimReqTryLogin(content,error);
    }
    //如果登录成功 or 插件正在尝试登录中:则return true 并返回相应的错误信息;
    if(result){
        if(!content["storeId"].toString().compare(m_storeId)) {
            QJsonObject storeStatusData = content["data"].toObject();
            QLOG_INFO()<<"FlowControl::_ResponseOMS12Request:"<<storeStatusData;
            if(1==storeStatusData["appStoreStatus"].toInt() || 1==storeStatusData["eleStoreStatus"].toInt()) {
                QString strOpeStatus=QString::fromLocal8Bit("开店");
                emit setOpeStatus(strOpeStatus);
                emit doUpdateStoreStatus(true);
            }else {
                QString strOpeStatus=QString::fromLocal8Bit("关店");
                emit setOpeStatus(strOpeStatus);
                emit doUpdateStoreStatus(false);
            }
            error=QString("success");
            result = true;
        } else {
            error=QString::fromLocal8Bit("门店信息不匹配");
            result = false;
        }
    }
    return result;
}



bool FlowControl::_ResponseHM21Request(const QJsonObject &content, QJsonObject &data, QString &error)
{
    QLOG_INFO()<<__FUNCTION__;
    //判断当前POS插件是否登录成功: 如果没有登录成功，尝试在次登录;
    bool result=true;
    if(!m_bLoginResult&&content.contains("storeId")) {
        result=_ResponseSimReqTryLogin(content,error);
    }
    //如果登录成功 or 插件正在尝试登录中:则return true 并返回相应的错误信息;
    if(result){
        //<1>:更新 OrderObject 中的数据;
        //获取门店营业状态
        //QString strOpeStatus=QString::fromLocal8Bit("开店");
        //emit setOpeStatus(strOpeStatus);
        //增加筛选条件,判断当前POS系统录单的订单是否还没录单完成:如果该订单录单没有完成,不返回100,务必让服务的等待;
        if(content[JSON_ORDER_ID].toString().isEmpty()) {
            error =QString::fromLocal8Bit("订单号不能为空");
            return false;
        } else {
            if(!m_simValidOrdersList.isEmpty()){
                QString simValidOrderListFirstOne = m_simValidOrdersList.first();
                //缩小锁住订单的条件范围: 服务端推单给插件程序且插件程序拒绝本次订单状态发生变化的请求
                if(content[JSON_ORDER_ID].toString() == simValidOrderListFirstOne && m_bFloatFromLockSt){
                    error =QString::fromLocal8Bit("当前订单正在录POS系统，请耐心等待");
                    return false;
                }
            }
        }

        QJsonObject hmOrderJson =  content["orderDetail"].toObject();
        QLOG_INFO()<<"FlowControl::_ResponseHM21Request:"<<hmOrderJson;
        if(!hmOrderJson.isEmpty()){
            result = true;
            error=QString::fromLocal8Bit("_ResponseHM21Request Action:21:accept HM Order Success");
             _OrderAnalysis(hmOrderJson);
        }else{
            result = false;
            error=QString::fromLocal8Bit("_ResponseHM21Request Action:21:accept HM Order empty");
        }
        //<2>:向simphony整合订单数据:准备向POS录单【_OrderAnalysis(hmOrderJson);函数会触发simphony录单动作(退单的情况也会存入队列中)】
        //result=_ResponseSimReqFristOrderData(content, data,error,content["orderId"].toString());
    } else {
        result = false;
        if(error.isEmpty()) {
            error=QString::fromLocal8Bit("Response Simphony_Script Request 01: Login Store Failed");
        }
    }
    return result;
}


bool FlowControl::_ResponseSimReqTryLogin(const QJsonObject &content,QString &error)
{
    QLOG_INFO()<<__FUNCTION__;
    m_storeId=content["storeId"].toString();
    m_posId=content["posId"].toString();
    m_cashierId=content["operatorId"].toString();
    m_cashierName=content["operatorName"].toString();
    if(m_bFirstRecvInfo) {
        error = QString::fromLocal8Bit("FMOMS Plug-in Program Try Login On");
        emit doLogin();
    }
    return true;
}

bool FlowControl::_ResponseSimReqFristOrderData(const QJsonObject &content, QJsonObject &data, QString &error, const QString &orderId)
{
    QLOG_INFO()<<__FUNCTION__<<error<<orderId;

    m_storeId=content["storeId"].toString();
    m_posId=content["posId"].toString();
    m_cashierId=content["operatorId"].toString();
    m_cashierName=content["operatorName"].toString();
    emit setCashierInfo(m_cashierName); //POS上收银员切换账号后,插件上右下角的收银员信息也及时更新;

    QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---Simphony_Script请求[ACTION:01: 获取订单数据] 开始获取 OrderId:%1 给simphony:--->>>>>]").arg(orderId);
    bool result=true;
    if(!m_bLoginResult) {
        error = QString::fromLocal8Bit("FMOMS Plug-in Program Not Login On");
        return false;
    }

    if(m_simValidOrdersList.isEmpty()) {
        error = QString::fromLocal8Bit("No New Delivery Order Need To Pull.");
        result = true;
    } else {
        error.clear();
        QString orderId=m_simValidOrdersList.first();
        QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---Simphony_Script请求[ACTION:01:]FMOMS已登录，且有订单待拉取:orderId:%1--->>>>>]").arg(orderId);

        OrderObject* orderObject = m_FmOrdersMap.value(orderId);
        if(!orderObject){
            error = QString::fromLocal8Bit("Delivery Order had been clear by _CrondClearExpireOrder.");
            m_OrderEntryMutex.lock();
            m_simValidOrdersList.removeFirst();
            m_OrderEntryMutex.unlock();
            result = false;
        }
        if(MAXPUTTIMES==orderObject->pushOrderTimes) {
            orderObject->pushOrderTimes = 0;
        } else {
            orderObject->pushOrderTimes=orderObject->pushOrderTimes+1;
        }

        //防止POS出现多次录单：退货单(销售单应该不会)；
        bool  bIsPushOrder = SimProcOrderDB::getInstance().isPushedOrder(orderObject->id);
        bool  bIsRefundOrder = SimProcOrderDB::getInstance().isRefundOrder(orderObject->id);
        if(bIsPushOrder && bIsRefundOrder) {
            QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---Simphony_Script请求[ACTION:01:] bIsPushOrder: ;bIsRefundOrder: ;--->>>>>]")<<bIsPushOrder<<bIsRefundOrder;
            //error = QString::fromLocal8Bit("该订单已经被POS系统录入完成");
            error = QString::fromLocal8Bit("This Delivery Order Have Been Recorded In POS System Successfully");
            m_OrderEntryMutex.lock();
            m_simValidOrdersList.removeOne(orderObject->id);
            m_OrderEntryMutex.unlock();
            return true;
        }

        QJsonObject rObj, cObj;
        if(orderObject->pushOrderType==1) {
            rObj.insert("fm_cmd", "put_order");
        } else {
            rObj.insert("fm_cmd", "refund_order");
        }
        rObj.insert("fm_ver", "1.0");
        cObj.insert("pay_id", "002");
        cObj.insert("pay_str", QString::fromLocal8Bit("FmTakeout"));
        int tempOrderType,tempOrderPayType,tempSbkAppPayType=0;
        QString tempSbkAppPayValue="0";
        // 转换成星巴克规定的订单类型;
        //星巴克的订单类型：1:新订单; 2:预订单; 3:客诉单;
        if(3 == orderObject->getOrderType()) {
            tempOrderType = 12;
            tempOrderPayType = 21;
        }
        // OMS提供的数据://订单渠道: 星巴克APP,百度外卖,饿了么APP,美团外卖 ;
        else if("MOD" == orderObject->channel) {
            tempOrderType = 9;
            tempOrderPayType = 84;
            //星巴克App端支付方式: 1:支付宝; 2:微信; 3:银联; 4:SVC卡;
            if(4 == orderObject->payWay){
                tempSbkAppPayType = 14 ;
                //svc卡支付时传交易流水号协定:
                if(OrderObject::Refunded == orderObject->orderStatus ||OrderObject::SimExceptRefund == orderObject->orderStatus){
                    tempSbkAppPayValue = orderObject->refundFmId.isEmpty()?QString("0"):orderObject->refundFmId;
                }else{
                    tempSbkAppPayValue = orderObject->payfmId;
                }
                //tempSbkAppPayValue = orderObject->payfmId;
            }else if(1 == orderObject->payWay){
                tempSbkAppPayType = 78;
                tempSbkAppPayValue = (orderObject->thirdPartyBatch).length()?orderObject->thirdPartyBatch :QString("0");
            }else if(2 == orderObject->payWay){
                tempSbkAppPayType = 77;
                tempSbkAppPayValue = (orderObject->thirdPartyBatch).length()?orderObject->thirdPartyBatch :QString("0");
            }else{
                tempSbkAppPayType = -1;
                tempSbkAppPayValue = "-1";
            }
        }else if("BAIDU" == orderObject->channel){
            tempOrderType = 11;
            tempOrderPayType = 83;
            tempSbkAppPayValue = orderObject->id;
        }else if("ELE" == orderObject->channel){
            tempOrderType = 11;
            tempOrderPayType = 83;
            tempSbkAppPayValue = orderObject->id;
        }else if("MEITUAN" == orderObject->channel){
            tempOrderType = 11;
            tempOrderPayType = 83;
            tempSbkAppPayValue = orderObject->id;

        }else if("HM" == orderObject->channel){
            tempOrderType = 14;
            tempOrderPayType = 85;
            tempSbkAppPayValue = orderObject->id;
        }else{
            tempOrderType = 11;
            tempOrderPayType = 83;
            tempSbkAppPayValue = orderObject->id;
        }
        // 如果是退单,更新订单的来源类型;
        if (orderObject->pushOrderType == 0) {
            if("ELE" == orderObject->channel) {
                tempOrderType = 16;
            } else if("MOD" == orderObject->channel) {
                tempOrderType = 17;
            }else{
                tempOrderType = 13; // 退货订单类型:13 已经过期; 后期还需要考虑MOP的正向订单类型/退货订单类型;
            }
        }
        cObj.insert("orderOriginType", tempOrderType);
        cObj.insert("orderPayType", tempOrderPayType);
        cObj.insert("sbkAppPayType", tempSbkAppPayType);
        cObj.insert("sbkAppPayValue", tempSbkAppPayValue);
        cObj.insert("orderTransFlowNo", (orderObject->thirdPartyBatch).length()?orderObject->thirdPartyBatch :QString("0") ); //第三方交易流水号
        cObj.insert("packFree", (orderObject->packageFee>0 && orderObject->packageFee<10000)?orderObject->packageFee:0);
        cObj.insert("packDiscount", (orderObject->packDiscount>0 && orderObject->packDiscount<10000)?orderObject->packDiscount:0);
        cObj.insert("deliveryFree", (orderObject->deliveryPrice>0 && orderObject->deliveryPrice<10000)?orderObject->deliveryPrice:0);
        //防止出现 deliveryPrice: NUll
        cObj.insert("deliveryDiscount", (orderObject->deliveryDiscount>0 && orderObject->deliveryDiscount<10000)?orderObject->deliveryDiscount:0);
        cObj.insert("orderDiscount", orderObject->orderDiscount);
        cObj.insert("waybillId", (orderObject->waybillId).length()?orderObject->waybillId:QString("0") );
        cObj.insert("pos_sale_id", orderObject->posCheckNo);
        cObj.insert("order_status",orderObject->orderStatus);//订单的状态
        cObj.insert("pay_ebcode", orderObject->channel);
        cObj.insert("order_index", orderObject->orderIndex);
        cObj.insert("customer_name", orderObject->customerName);
        cObj.insert("customer_phone", orderObject->phone);
        cObj.insert("customer_address", orderObject->addressDetail);
        cObj.insert("delivery_time", orderObject->deliveryTime);
        cObj.insert("create_time",orderObject->createTime);
        cObj.insert("remark", orderObject->memo);
        cObj.insert("has_invoice",orderObject->needInvoice);
        cObj.insert("invoice_title",orderObject->invoiceTitle);
        cObj.insert("pay_ebcode_str", orderObject->channel);
        //TODO
        cObj.insert("products_fee", orderObject->productPrice);    // 商品金额
        cObj.insert("service_fee", /*orderObject->service_fee*/0);  // 平台佣金
        cObj.insert("discount_fee", /*orderObject->disPlateformFee*/0);  //平台优惠总额
        //只有这个字段（discount_fee）传个Simphony(代表平台优惠给POS系统),对应的字段是dis_shop_fee :平台优惠总额 只能通过 dis_shop_fee 字段传递给 POS;
        cObj.insert("dis_shop_fee", abs(orderObject->disPlateformFee)); // 商家承担优惠金额（实际传递的是: 平台优惠金额 orderObject->disPlateformFee）;
        //只有星巴克App 才挂MSR的虚拟卡号;目前饿了么也要挂MSR的虚拟卡号;卡号是空 则 MSR_NO='-1' 卡号不入机;
        QString temp_MSR_NO;
        temp_MSR_NO = (orderObject->msr_no.length()==0)?orderObject->customerId:orderObject->msr_no;
        temp_MSR_NO = (temp_MSR_NO.length()==0)?QString::fromLocal8Bit("-1"):temp_MSR_NO;

        cObj.insert("msr_card_no", temp_MSR_NO); // MSR卡号
        cObj.insert("dis_platform_fee", /*orderObject->dis_platform_fee*/0); // 平台承担优惠金额
        cObj.insert("shop_fee", /*orderObject->total_fee-orderObject->send_fee-orderObject->service_fee-orderObject->dis_shop_fee*/0);         // 商户能够拿到的钱(去除平台佣金)
        cObj.insert("invoice_amount",orderObject->totalPrice);
        if("ELE" == orderObject->channel){
            cObj.insert("thirdPartyOrderId",orderObject->thirdPartyOrderId);
        }else if("HM" == orderObject->channel){
            cObj.insert("thirdPartyOrderId",orderObject->thirdPartyOrderId);
        } else {
            cObj.insert("thirdPartyOrderId","0");
        }
        cObj.insert("paid_trans_id",orderObject->id);
        //cObj.insert("fm_id",orderObject->fm_id);
        /************************************************************************************/
        int hasCashbox = 0 ,hasRefundAuth = 0;
        hasCashbox = GetCaboxAReAuth::getInstance().getUserHasCashBox(m_cashierId);
        hasRefundAuth =  GetCaboxAReAuth::getInstance().getUserRefundAuth(m_cashierId);
        QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---Simphony_Script请求[ACTION:01:] 获取当前用户是否绑定钱箱:hasCashbox:%1; 当前用户是否拥有退货权限:hasRefundAuth:%2:--->>>>>]").arg(hasCashbox).arg(hasRefundAuth);
        cObj.insert("hasCashbox",hasCashbox);
        cObj.insert("hasRefundAuth",hasRefundAuth);
        /************************************************************************************/
        rObj.insert("pay_id", cObj);
        QJsonArray products;
        /**********************************************************************************/
        // 循环订单的最外层商品列表；
        /**********************************************************************************/
        for(int i=0; i < orderObject->proList.count(); i++) {
            dishesObject* dish=orderObject->proList.at(i);
            // promotion优惠计数器变量;
            int promotionTempNo = 0;
            //默认属性直接跳过;
            if (dish->code.contains("Default",Qt::CaseInsensitive)) {
                continue;
            }
            /**********************************************************************************/
            //针对同一商品，多份数量需要将其，拆分成单份;[如果不拆分，将导致多份商品中配料价格出现 漏钱:POS中的账将会出现少金额]
            /**********************************************************************************/
            for (int temp_qty = 0; temp_qty < dish->qty; temp_qty++) {
                //声明临时栈对象: 单个主商品 + 子商品列表 + 子商品;
                QJsonObject tObj;
                QJsonArray subProduct;
                QJsonObject sObj;
                tObj.insert("consume_num", 1);
                tObj.insert("pid", dish->code);
                tObj.insert("original_price", dish->price);
                /**********************************************************************************/
                // 处理原始的配料信息;
                /**********************************************************************************/
                if(!dish->sub_products.isEmpty()) {
                    for(int j=0; j < dish->sub_products.count(); j++) {
                        dishesObject* subDish=dish->sub_products.at(j);
                        //默认属性直接跳过;
                        if(!subDish->code.isEmpty() && !subDish->code.contains("Default",Qt::CaseInsensitive) ) {
                            sObj.insert("consume_num", subDish->qty);
                            sObj.insert("pid", subDish->code);
                            sObj.insert("original_price", subDish->price);
                            subProduct.insert(0, sObj);
                        }
                    }
                }
                /**********************************************************************************/
                // 处理商品的属性(热 -> 特别热)的额外配料信息;
                /**********************************************************************************/
                if(dish->options.length()){
                    sObj.insert("consume_num", 1);
                    sObj.insert("pid", dish->options);
                    sObj.insert("original_price", 0);
                    subProduct.insert(0, sObj);
                }
                /**********************************************************************************/
                // 处理商品的优惠金额信息;针对单个商品多数量情况：需要将这部分优惠折扣金额放在前面 拆分数量的商品上[多少个折扣券，放在前几个商品上，一个上面下对应一个折扣项];
                //单项商品的折扣数量最多不超过55个(60个会导致POS死机);当个优惠价格不超200元;
                /**********************************************************************************/
                int promotionSum = (dish->promotionQty>0 && dish->promotionQty<55)?dish->promotionQty:0;
                int promotionPrice = (dish->promotionPrice>10 && dish->promotionPrice<20000)?dish->promotionPrice:0;
                //QLOG_INFO() << QString("[---begin promotionTempNo---]")<<promotionTempNo;
                //QLOG_INFO() << QString("[---promotionSum---]")<<promotionSum;
                if(promotionTempNo < promotionSum){
                    if(promotionSum && promotionPrice && dish->promotionSku.length()){
                        sObj.insert("consume_num", 1);
                        sObj.insert("pid", dish->promotionSku);
                        sObj.insert("original_price", promotionPrice);
                        subProduct.insert(subProduct.count(), sObj);
                        promotionTempNo++;
                        //QLOG_INFO() << QString("[---end promotionTempNo---]")<<promotionTempNo;
                    }
                }

                // 汇总插入子商品[sub_products];
                //QLOG_INFO() << QString("[---subProduct---]")<<subProduct;
                if(subProduct.size()){
                    tObj.insert("sub_products",subProduct);
                } // end 整合子商品结束；
                //products.insert(i, tObj); //防止default*的主商品码出现,上面代码出现continue;导致 i出现跳数，插入时出现崩溃;
                products.push_back(tObj);
                //QLOG_INFO() << QString("[---tObj---]")<<tObj;
            }
        }

        rObj.insert("products", products);
        data= rObj;
    }
    return result;
}


QString FlowControl::_Penny2Dollar(int penny)
{
    double dollar = (double)penny/100;
    return QString::number(dollar,'f',1);
}

void FlowControl::onGetBusinessStatus()
{
    QLOG_INFO()<<__FUNCTION__;
    if(!m_bLoginResult)
    {
        emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("门店还未登录"));
        return ;
    }
    QString error;
    bool result;
    QJsonObject sendJson;
    QJsonObject recvJson;

    sendJson = DataManger::GetInstance().GetStoreChannelInfoData();
    m_pullDishesSocket->SetUrl(QUrl(ConfigManger::GetInstance().GetStoreServerUrl()+
                               ConfigManger::GetInstance().GetInterfaceName(INI_INTERFACE_GETSTORESTATE)));
    QLOG_INFO()<<ConfigManger::GetInstance().GetStoreServerUrl()+ ConfigManger::GetInstance().GetInterfaceName(INI_INTERFACE_GETSTORESTATE);
    emit showAlert(AlertForm::LOADING, QString::fromLocal8Bit("正在获取平台营业状态......"));
    QLOG_INFO() << QString("[---GetStoreChannelInfo---]. [requestData:%1]")<<sendJson;
    result = m_pullDishesSocket->PostRequest(sendJson, recvJson, error);
    QLOG_INFO() << QString("GetStoreChannelInfo finsh. [result:%1][msg:%2][recvData:%3]")
                   .arg(result).arg(error)<<recvJson;
    if(!result) {
        emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("获取平台营业状态失败![网络错误]"));
    } else {
        if(JSON_STATUSCODE_OK != recvJson[JSON_STATUSCODE].toInt()) {
            emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("获取平台营业状态失败![%1]").arg(recvJson[JSON_MESSAGE].toString()));
        } else {
            QJsonArray array=recvJson[JSON_DATA].toArray();
            QStringList strListChannels;
            foreach(QJsonValue v, array) {
                QJsonObject channel =  v.toObject();
                QString channelName = channel["channelname"].toString();
                QString channelCode = channel["channel"].toString();
                QString channelStatus = QString::number(channel["state"].toInt());
                qDebug()<<channelName<<"-"<<channelCode<<"-"<<channelStatus;
                strListChannels.append(channelCode+":"+channelName+":"+channelStatus);
            }

            if(!strListChannels.isEmpty()) {
                emit hideAlert();
                // 通知界面显示
                // emit initChannelsData(strListChannels);
            } else {
                emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("未获取到平台信息!"));
            }
         }
    }
}

void FlowControl::onProcessOrder(const QString &operation, const QString &orderId)
{
    if(!operation.compare(OPERATION_GETDELIVERS))
    {
        //_GetDelivers(orderId);
        _ConfirmOrder(orderId);
    }else if(!operation.compare(OPERATION_CONFRIM))
    {
        _ConfirmOrder(orderId);
    }
    else if(!operation.compare(OPERATION_SENDOUT))
    {
        _SendOrder(orderId);
    }else if(!operation.compare(OPERATION_COMPLETE))
    {
        _CompleteOrder(orderId);
    }else if(!operation.compare(OPERATION_REFUSEREFUND))
    {
        _RefuseRefund(orderId);
    }else if(!operation.compare(OPERATION_REFUNDORDER))
    {
        _RefundOrder(orderId,5,QString::fromLocal8Bit("同意退款"),QString());
    }
}

void FlowControl::onGetOrderDetails(const QString& orderId)
{
    emit hideAlert();
    emit showOrderDetails(m_FmOrdersMap.value(orderId));
}

void FlowControl::onSerachOrder(const QString &text)
{
    QLOG_INFO() << QString::fromLocal8Bit("[<<<<---FlowControl::onSerachOrder:输入的数字串:%1 --->>>>]").arg(text);
    QMap<QString,QString> orderMap;
    if(!text.isEmpty())
    {
        QMap<QString, OrderObject*>::iterator order;
        for(order = m_FmOrdersMap.begin(); order!=m_FmOrdersMap.end(); order++)
        {
            QString orderId = order.key();
            QString phoneId = order.value()->consigneePhone;
            QString thirdPartyOrderId = order.value()->thirdPartyOrderId;
            while (!orderId.at(0).isDigit())
            {
              orderId = orderId.mid(1);
            }
            if(orderId.startsWith(text))
            {
                orderMap.insert(QString::fromLocal8Bit("订单号:")+orderId,QString::fromLocal8Bit("三方订单号:")+thirdPartyOrderId);
            }
            //移除手机号检索
            /*
            if(phoneId.startsWith(text))
            {
                orderMap.insert(QString::fromLocal8Bit("订单号:")+orderId,QString::fromLocal8Bit("手机号:")+phoneId);
            }
            */
            //新增第三方订单号检索;
            if(thirdPartyOrderId.startsWith(text))
            {
                orderMap.insert(QString::fromLocal8Bit("订单号:")+orderId,QString::fromLocal8Bit("三方订单号:")+thirdPartyOrderId);
            }
        }
    }
    emit showSearchOrderResult(orderMap);
}

void FlowControl::onProcessRejectOrder(const QString &orderId, const int &reasonCode,const QString &reason)
{
    _RefuseOrder(orderId, reasonCode,reason);
}
void FlowControl::onProcessRepealOrder(const QString &orderId, const int &reasonCode,const QString &reason,const QString& dishesListString)
{
    QLOG_INFO() << QString("[<<<<---FlowControl::onProcessRepealOrder: --->>>>]");

    _RefundOrder(orderId,reasonCode,reason,dishesListString);
}
