#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 <QHostInfo>


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

FlowControl::FlowControl()
{
    m_bLoginResult =false;
    m_bFirstRecvInfo = true;

    m_loginSocket = NULL;
    m_pullOrderSocket = 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_pullTimer->setSingleShot(true);
    m_loginTimer=new QTimer(this);

    connect(m_loginTimer,&QTimer::timeout,this,&FlowControl::_ClickToLogin);
    connect(m_pullTimer,&QTimer::timeout,this,&FlowControl::_PullOrder);
    connect(m_clearTimer,&QTimer::timeout,this,&FlowControl::_ClearOrder);
    connect(m_heartTimer,&QTimer::timeout,this,&FlowControl::_SendHeart);
    connect(this,&FlowControl::doPullOrder,this,&FlowControl::_GetOrder);
    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);

    /*** 启动Http服务:用来响应Simphony_Script获取订单的请求***/
    m_tcpServerManage = new JQHttpServer::TcpServerManage(10);
    m_tcpServerManage->setHttpAcceptedCallback( [this]( const QPointer< JQHttpServer::Session > &session )
    {
        qDebug() << "reply" << QThread::currentThreadId();
        // 回调发生在新的线程内，不是主线程。
        /***解析FM外卖插件HTTP服务与Simphony_Script请求的会话连接是否断开: 会话连接未断开***/
        if(!session.isNull())
        {
            QString recvData = QString::fromUtf8(session->requestRawData());
            QLOG_INFO() << QString::fromLocal8Bit("[<<<<---Receive Simphony_Script Request: %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();
            /***解析Simphony_Script Request json格式: 解析失败***/
            if(jsonError.error != QJsonParseError::NoError)
            {
                status = 0;
                msg = jsonError.errorString();
            }
            /***解析Simphony_Script Request json格式: 解析成功***/
            else {
                /***？？？？？***/
                if(_GetReplyJson(recvObject,data, msg))
                {
                    status = 100;
                }
                /***？？？？？***/
                else{
                    status = 0;
                }
                /***？？？？？***/
                if(!m_ordersEntryList.isEmpty())
                {
                    iscontinue=1;
                }
            }
            /***将FM外卖插件中的合法有效数据返回给上面Simphony_Script发过来的请求***/
            replyObject = _PackHttpReplyJson(status, msg, data,iscontinue);
            QLOG_INFO() << QString::fromLocal8Bit("[<<<<---FM外卖插件回应Simphony_Script拉单请求后的返回结果:--->>>>]") << replyObject;
            /***？？？？？？？？？？？？？？？？？？***/
            session->replyJsonObject(replyObject);
        }
        /***解析FM外卖插件HTTP服务与Simphony_Script请求的会话连接是否断开: 会话连接断开***/
        else{
            QLOG_INFO() << QString::fromLocal8Bit("[<<<<---FM外卖插件Http服务与Simphony_Script请求会话断开连接:--->>>>]");
        }
    } );

    /***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服务 绑定端口失败:--->>>>]");
    }

    /***打开Sqlite数据库并登陆外卖插件***/
    SimProcOrderDB::getInstance();
    _ClickOMSAssignArea();
    m_loginTimer->start(20*1000);
}


QString FlowControl::_GetIpAddress()
{
    /***？？？？需要验证IP地址是通过配置文件还是直接通过机器获取？？？？***/
    QString ipAddress;
    ipAddress=ConfigManger::GetInstance().GetIpAddress();
    QHostInfo info = QHostInfo::fromName(QHostInfo::localHostName());
    foreach(QHostAddress address,info.addresses())
    {
        if(address.protocol() == QAbstractSocket::IPv4Protocol)
        {
            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)
{
    /***组装从FM外卖service端的拉单请求参数***/
    PullOrderInfo orderPull;
    orderPull.orderId=orderId;
    orderPull.channel=channel;
    orderPull.pageNumber=pageNumber;
    orderPull.pageSize=pageSize;
    m_orderPullList.append(orderPull);
}

void FlowControl::_GetOrder(const QString &orderId, const QString &channel)
{
    /***组装从FM外卖service端的拉单请求参数***/
    _AddOrderPull(orderId,channel);
    /***开始拉单***/
    _PullOrder();
}

void FlowControl::_ClickOMSAssignArea()
{
    QPoint point=ConfigManger::GetInstance().GetOMSBtnPostion();
    SetCursorPos(point.x(),point.y());
    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());
}

void FlowControl::_ClickToLogin()
{
    if(!m_bLoginResult||!m_ordersEntryList.isEmpty())
    {
        QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---触发按钮点击事件：FM外卖插件20s后再次尝试登陆--->>>>]");
        _ClickOMSAssignArea();
    }
}

void FlowControl::_OrderAnalysis(const QJsonObject& jsonObject)
{
    OrderObject *orderObject = NULL;
    orderObject = m_simValidOrderMapQueue.value(jsonObject[JSON_ID].toString());
    /***<1>:待Simphony拉取的有效订单队列中不存在此订单：整合数据并插入到此订单队列中 ***/
    if(orderObject == NULL)
    {
        orderObject = new OrderObject(this);
        orderObject->FromJson(jsonObject);
        orderObject->isPush = false;
        orderObject->isCancle = false;

        m_simValidOrderMapQueue.insert(orderObject->id, orderObject);
        QLOG_INFO() << QString("[<<<<---Simphony Valid Order MapQueue:Insert New Order[%1:%2]--->>>>][data:]")
                       .arg(orderObject->id,orderObject->getOrderStatusDec())<<jsonObject;
        if(!SimProcOrderDB::getInstance().isOrderExit(orderObject->id))
        {
            SimProcOrderDB::getInstance().insertSimProcOrder(orderObject->id,QDate::currentDate().toString("yyyy-MM-dd"));
            if((OrderObject::NewOrder==orderObject->orderStatus||OrderObject::Confirmed==orderObject->orderStatus))
            {
                emit startRemind(0);
            }
        }
        emit changeOrderStatus(orderObject);
    }
    /***<2>:待Simphony拉取的有效订单队列中存在此订单:更新订单队列中此订单的订单状态***/
    else
    {
        int oldStatus = orderObject->orderStatus;
        orderObject->FromJson(jsonObject);
        QLOG_INFO() << QString("[<<<<---Simphony Valid Order MapQueue:Update OldOrder Status[%1:%2]--->>>>].[data:%3]")
                       .arg(orderObject->id,orderObject->getOrderStatusDec())<<jsonObject;
        if(oldStatus != orderObject->orderStatus)
        {
            emit changeOrderStatus(orderObject, oldStatus);
        }
    }

    orderObject->updateTime=QDateTime::currentDateTime().toTime_t();
    if(OrderObject::RequestRefund==orderObject->orderStatus)
    {
        emit startRemind(1);
    }
    if(SimProcOrderDB::getInstance().isPushedOrder(orderObject->id))
    {
        orderObject->isPush = true;
    }
    if(SimProcOrderDB::getInstance().isRefundOrder(orderObject->id))
    {
        orderObject->isCancle = true;
    }
    QString posOrderCheckNo=m_orderIdToPosSalesIdMap.value(orderObject->id);
    if(posOrderCheckNo.isEmpty())
    {
        SimProcOrderDB::getInstance().getPosOrderCheckNo(orderObject->id,posOrderCheckNo);
    }
    orderObject->posCheckNo=posOrderCheckNo;
    switch (orderObject->orderStatus){
    case OrderObject::NewOrder:
    case OrderObject::Confirmed:
    case OrderObject::Sendout:
    case OrderObject::ToSend:
    case OrderObject::Finished:
    case OrderObject::RequestRefund:
    /***case:新订单、确认订单、已配送订单、待配送订单、完成订单、请求退单: 订单还没push到POS[POS没有模拟点单或没有返回小票号]***/
        if(!orderObject->isPush)
        {
            orderObject->putType = 1;
            orderObject->putTimes = 0;
            m_OrderEntryMutex.lock();
            if(!m_ordersEntryList.contains(orderObject->id))
            {
                m_ordersEntryList.append(orderObject->id);
            }
            m_OrderEntryMutex.unlock();
            _ClickOMSAssignArea();
        }
        break;
    case OrderObject::AgreeRefund:
    case OrderObject::Refunded:
    case OrderObject::Cancled:
    /***case:同意退单、退单、取消订单: 此退单还没push到POS[POS没有确认退单或没有返回确认退单的小票号]***/
        if(!orderObject->isCancle)
        {
            /***case:校验此订单是否已经push到POS：订单还没push到POS[POS没有模拟点单或没有返回小票号]***/
            if(!orderObject->isPush)
            {
                m_OrderEntryMutex.lock();
                m_ordersEntryList.removeOne(orderObject->id);
                m_OrderEntryMutex.unlock();
            }
            /***case:校验此订单是否已经push到POS：订单已经push到POS***/
            else{
                /***case:校验此订单push到POS后的小票号是否空：[POS已模拟点单且返回小票号]***/
                if(!posOrderCheckNo.isEmpty())
                {
                    orderObject->putType = 0;
                    orderObject->putTimes = 0;
                    m_OrderEntryMutex.lock();
                    if(!m_ordersEntryList.contains(orderObject->id))
                    {
                        m_ordersEntryList.append(orderObject->id);
                    }
                    _ClickOMSAssignArea();
                    m_OrderEntryMutex.unlock();
                }
                /***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_procOrderSocket = new BillSocket(this);
    m_pullDishesSocket = new BillSocket(this);
    m_pullOrderListSocket = new BillSocket(this);
    _GetStoreInfo();
    _Login();
    m_bFirstRecvInfo =false;
    return ;
}


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;
}

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();
    }
    qDebug()<<ConfigManger::GetInstance().GetLoginServerUrl()+
              ConfigManger::GetInstance().GetInterfaceName(INI_INTERFACE_ILOGIN);
    m_loginSocket->SetUrl(QUrl(ConfigManger::GetInstance().GetLoginServerUrl()+
                               ConfigManger::GetInstance().GetInterfaceName(INI_INTERFACE_ILOGIN)));
    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_STATUSCODE].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().SetPartnerId(ConfigManger::GetInstance().GetPartnerId());
            emit hideAlert();
            emit setStoreInfo(m_storeId);
            emit setCashierInfo(m_cashierId);
            m_bLoginResult= true;
            m_clearTimer->start(1000*60*60*24*2);
            m_heartTimer->start(1000*60*5);
            m_pullTimer->start(1000*10);
            emit doPullOrder(QString(),QString());
        }
    }
    if(!result)
    {
        QLOG_INFO() << QString("[<<<<---Login Retry--->>>>] %1 msec after login...").arg(VALUE_RELOGINTIME);
        QTimer::singleShot(VALUE_RELOGINTIME, this, &FlowControl::_Login);
    }
    return result;
}

void FlowControl::_PullOrder()
{
    if(m_orderPullList.isEmpty())
        return ;
    emit hideAlert();
    PullOrderInfo info=m_orderPullList.takeFirst();
    if(info.orderId.isEmpty())
    {
        _PullOrderList(info.pageSize,info.pageNumber);
    }
    else
    {
        _PullOrderDetail(info.orderId);
    }
    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()<<"load ssl";
    }
    else{
        QLOG_INFO()<<"load not ssl";
    }
    QString url = ConfigManger::GetInstance().GetOrderServerUrl()+
            ConfigManger::GetInstance().GetInterfaceName(INI_INTERFACE_PULLORDER);
    url.append(orderId);
    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数据失败则10秒后重新拉单*/
    if(!result)
    {
        m_pullTimer->start(1000*10);
        _AddOrderPull(orderId);
    }
    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("[<<<<---Pull Order List--->>>>][requestData:]")<<sendJson;
    if(ConfigManger::GetInstance().GetOrderSslConfig())
    {
        m_pullOrderSocket->SetSslConfig();
        QLOG_INFO()<<"load ssl";
    }
    else{
        QLOG_INFO()<<"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);
    result = m_pullOrderListSocket->PostRequest(sendJson, recvJson, error);
    QLOG_INFO() << QString("[<<<<---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("[<<<<---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)
            {
                _AddOrderPull(QString(),QString(),pageNo+1,pageSize);
                _PullOrder();
            }
        }
    }
    if(!result)
    {
        m_pullTimer->start(1000*10);
        _AddOrderPull(QString(),QString(),pageNo,pageSize);
    }
    qDebug()<<"[<<<<---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 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()));
        }
    }
    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);
    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_simValidOrderMapQueue.value(orderId);
                int oldOrderStatus = orderObject->orderStatus;
                orderObject->orderStatus = orderStatus;
                emit changeOrderStatus(orderObject, oldOrderStatus);
            }
            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_simValidOrderMapQueue.value(orderId);
            int oldStatus = orderObject->orderStatus;
            orderObject->orderStatus = recvJson[JSON_STATUS].toInt();
            emit changeOrderStatus(orderObject, oldStatus);
        }
    }

    return result;
}

bool FlowControl::_SendOrder(const QString& orderId)
{
    //TODO
//    if(m_simValidOrderMapQueue.value(orderId)->riderName.isEmpty()&&m_simValidOrderMapQueue.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_simValidOrderMapQueue.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_simValidOrderMapQueue.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:%1]")<<sendJson;
    result = m_procOrderSocket->PostRequest(sendJson, recvJson, error);
    QLOG_INFO() << QString("[<<<<---RefuseRefund 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_simValidOrderMapQueue.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)
{
    QString error;
    bool result;
    QJsonObject sendJson;
    QJsonObject recvJson;

    sendJson = DataManger::GetInstance().GetRefundOrderData(reasonCode,reason,orderId,m_simValidOrderMapQueue.value(orderId)->channel);

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

    QLOG_INFO() << QString("[<<<<---Refund Order Begin--->>>>][requestData:%1]")<<sendJson;
    if(ConfigManger::GetInstance().GetOrderSslConfig())
    {
        m_procOrderSocket->SetSslConfig();
        QLOG_INFO()<<"load ssl";
    }
    else{
        QLOG_INFO()<<"load not ssl";
    }
    m_procOrderSocket->SetUrl(QUrl(ConfigManger::GetInstance().GetOrderServerUrl()+
                                   ConfigManger::GetInstance().GetInterfaceName(INI_INTERFACE_CANCLE)));
    result = m_procOrderSocket->PostRequest(sendJson, recvJson, error);
    QLOG_INFO() << QString("[<<<<---Refund 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_MESSAGE].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_simValidOrderMapQueue.value(orderId);
                int oldOrderStatus = orderObject->orderStatus;
                orderObject->orderStatus = orderStatus;
                emit changeOrderStatus(orderObject, oldOrderStatus);
            }
            else
            {
                emit showAlert(AlertForm::MSGERROR, QString::fromLocal8Bit("退单失败![%1]").arg(recvJson[JSON_ERRMSG].toString()));
            }
        }
    }

    return result;
}

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);
    //if(!data.isEmpty()){
        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
    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_BUSINESSDATE,m_business);
            emit hideAlert();
            emit showDailyReportData(recvJson);
        }
    }
}

void FlowControl::_ClearOrder()
{
    QDateTime currentDateTime= QDateTime::currentDateTime();
    OrderObject *order=NULL;
    m_OrderEntryMutex.lock();
    foreach (order, m_simValidOrderMapQueue.values()) {
        QDateTime createDateTime=QDateTime::fromTime_t(order->updateTime);
        qint64 days=createDateTime.daysTo(currentDateTime);
        if(days>=2)
        {
            QLOG_INFO()<<QString("[<<<<---ClearOrder: orderID:%1--->>>>]").arg(order->id);
            emit clearorder(order->id,order->orderStatus);
            m_simValidOrderMapQueue.value(order->id)->deleteLater();
            m_ordersEntryList.removeOne(order->id);

            delete m_simValidOrderMapQueue.take(order->id);
        }
    }
    m_OrderEntryMutex.unlock();
    SimProcOrderDB::getInstance().deleteOrderRecord(QDate::currentDate().addMonths(-1).toString("yyyyMMdd"));
}

bool FlowControl::_GetReplyJson(const QJsonObject &content,QJsonObject &data, QString& error)
{
    QLOG_INFO()<<__FUNCTION__;
    bool result = true;
    if(!content.contains("actionId"))
    {
        error =QString::fromLocal8Bit("未知的请求");
        result = false;
    }
    else{
        int actionId;
        if(content["actionId"].isString())
        {
            actionId=content["actionId"].toString().toInt();
        }
        else{
            actionId=content["actionId"].toInt();
        }
        switch (actionId) {
        case 1://simphony拉取订单
            result=_Get01ReplyJson(content,data,error);
            break;
        case 2://simphony确认接单
            result=_Get02ReplyJson(content,data,error);
            break;
        case 3://simphony取消接单
            result=_Get03ReplyJson(content,data,error);
            break;
        case 4://simphony消息回复
            result=_Get04ReplyJson(content,data,error);
            break;
        case 11://推送订单
            result=_Get11ReplyJson(content,data,error);
            break;
        case 12://推送门店营业状态
            result=_Get12ReplyJson(content,data,error);
            break;
        default:
            error =QString::fromLocal8Bit("未知的请求");
            result = false;
            break;
        }
    }
    return result;
}

bool FlowControl::_Get01ReplyJson(const QJsonObject &content, QJsonObject &data, QString &error)
{
    QLOG_INFO()<<__FUNCTION__;
    bool result=true;
    if(!m_bLoginResult&&content.contains("storeId"))
    {
        result=_GetLoginReplyJson(content,error);
    }
    if(result/*&&content.contains("orderId")*/){
        result=_GetQueryReplyJson(data,error,content["orderId"].toString());
    }
    else{
        result = false;
        if(error.isEmpty())
        {
            error=QString::fromLocal8Bit("请求参数错误");
        }
    }
    return result;
}
bool FlowControl::_Get02ReplyJson(const QJsonObject &content, QJsonObject &data, QString &error)
{
    return true;
    //TODO
    /*QLOG_INFO()<<__FUNCTION__;
    bool result = true;
    if(m_bLoginResult&&content.contains("orderId")){
        QString orderId=content["orderId"].toString();
        if(m_simValidOrderMapQueue.contains(orderId))
        {
            emit doStartOperateTimer();
            emit doConfirmOrder(orderId);
            orderOperation.orderId=orderId;
            orderOperation.operation=1;
            semaphore.acquire(1);
            if(m_bOperateResult)
            {
                error=QString::fromLocal8Bit("接单成功");
            }
            else{
                error=QString::fromLocal8Bit("响应超时");
            }
            result=m_bOperateResult;
            semaphore.release(1);
        }
        else{
            result=false;
            error=QString::fromLocal8Bit("订单不存在");
        }
    }
    else{
        result=false;
        error=QString::fromLocal8Bit("请求参数错误");
    }
    return result;*/
}
bool FlowControl::_Get03ReplyJson(const QJsonObject &content, QJsonObject &data, QString &error)
{
    return true;
    //TODO
    /*QLOG_INFO()<<__FUNCTION__;
    bool result = true;
    if(m_bLoginResult&&content.contains("orderId")){
        QString orderId=content["orderId"].toString();
        if(m_simValidOrderMapQueue.contains(orderId))
        {
            emit doStartOperateTimer();
            emit doRefundOrder(orderId,-1,QString::fromLocal8Bit("同意退款"));
            orderOperation.orderId=orderId;
            orderOperation.operation=0;
            semaphore.acquire(1);
            if(m_bOperateResult)
            {
                error=QString::fromLocal8Bit("取消成功");
            }
            else{
                error=QString::fromLocal8Bit("响应超时");
            }
            result=m_bOperateResult;
            memset(&orderOperation,0, sizeof(orderOperation));
            semaphore.release(1);

        }
        else{
            result=false;
            error=QString::fromLocal8Bit("订单不存在");
        }
    }
    else{
        result=false;
        error=QString::fromLocal8Bit("请求参数错误");
    }
    return result;*/
}
bool FlowControl::_Get04ReplyJson(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 posSaleId=content["posSaleId"].toString();
        if(posSaleId.isEmpty())
        {
            posSaleId=m_orderIdToPosSalesIdMap.value(orderId);
        }
        if(!posSaleId.isEmpty()&&!orderId.isEmpty())
        {
            if(!m_orderIdToPosSalesIdMap.contains(orderId))
            {
                QLOG_INFO()<<QString::fromLocal8Bit("%1订单已经成功推送给simphony").arg(orderId);
                m_orderIdToPosSalesIdMap.insert(orderId,posSaleId);
            }
            OrderObject* order_p =  m_simValidOrderMapQueue.value(orderId);

            if (!order_p){
                QLOG_ERROR()<<QString::fromLocal8Bit("%1订单并不存在m_orderMap[键值对]中;m_simValidOrderMapQueue.size()=%2").arg(orderId).arg(m_simValidOrderMapQueue.size());
                result=false;
                error=QString::fromLocal8Bit("%1订单并不存在m_orderMap[键值对]中;m_simValidOrderMapQueue.size()=%2").arg(orderId).arg(m_simValidOrderMapQueue.size());
                return result;
            }

            if(m_ordersEntryList.contains(orderId))
            {

                if(order_p->putType==1)
                {
                    SimProcOrderDB::getInstance().updatePushOrderStatus(orderId,1);
                    SimProcOrderDB::getInstance().updatePosOrderCheckNo(orderId,posSaleId);
                }
                else
                {
                    SimProcOrderDB::getInstance().updateRefundOrderStatus(orderId,1);
                }
                m_OrderEntryMutex.lock();
                m_ordersEntryList.removeOne(orderId);
                m_OrderEntryMutex.unlock();
            }
            else{
                order_p->isCancle = false;
                order_p->isPush = true;
                order_p->putType = 0;
                order_p->putTimes=0;

                m_OrderEntryMutex.lock();
                if(!m_ordersEntryList.contains(orderId))
                {
                    m_ordersEntryList.append(orderId);
                }
                m_OrderEntryMutex.unlock();
            }
        }
        else{
            result=false;
            error=QString::fromLocal8Bit("订单号或者短号不能为空");
        }
    }
    else{
        result=false;
        error=QString::fromLocal8Bit("请求参数错误");
    }
    return result;
}
bool FlowControl::_Get11ReplyJson(const QJsonObject &content, QJsonObject &data, QString &error)
{
    QLOG_INFO()<<__FUNCTION__;
    bool result=true;
    if(!m_bLoginResult){
        error = QString("FMOMS未登录");
        return false;
    }
    else{
        if(content[JSON_ORDER_ID].toString().isEmpty())
        {
            error =QString::fromLocal8Bit("订单号不能为空");
            return false;
        }
        emit doPullOrder(content[JSON_ORDER_ID].toString(),content[JSON_CHANNEL].toString());
        error = QString("success");
        result = true;
    }
        return result;
}
bool FlowControl::_Get12ReplyJson(const QJsonObject &content, QJsonObject &data, QString &error)
{
    if(!content["storeId"].toString().compare(m_storeId))
    {
        QJsonArray array=content["data"].toArray();
        emit setStoreStatusChanged(array);
        error=QString("success");
        return true;
    }
    else{
        error=QString::fromLocal8Bit("门店信息不匹配");
    }
    return false;
}

bool FlowControl::_GetLoginReplyJson(const QJsonObject &content,QString &error)
{
    QLOG_INFO()<<__FUNCTION__;
    m_storeId=content["storeId"].toString();
    m_posId=content["posId"].toString();
    m_cashierId=content["operatorId"].toString();
    if(m_bFirstRecvInfo)
    {
        error = QString::fromLocal8Bit("FMOMS正在登录");
        emit doLogin();
    }
    return true;
}

bool FlowControl::_GetQueryReplyJson(QJsonObject &data, QString &error, const QString &orderId)
{
    QLOG_INFO()<<__FUNCTION__<<error<<orderId;
    bool result=true;
    if(!m_bLoginResult)
    {
        error = QString::fromLocal8Bit("FMOMS 未登录");
        return false;
    }
    if(m_ordersEntryList.isEmpty())
    {
        error = QString::fromLocal8Bit("没有新订单待拉取");
        result = true;
    }
    else
    {
        error.clear();
        QString orderId=m_ordersEntryList.first();
        int pullNum=MAXPUTTIMES;
        foreach (auto value, m_ordersEntryList) {
            int num = m_simValidOrderMapQueue.value(value)->putTimes;
            if(pullNum>num)
            {
                pullNum=num;
                orderId=value;
            }
        }
        OrderObject* orderObject = m_simValidOrderMapQueue.value(orderId);
        if(MAXPUTTIMES==orderObject->putTimes)
        {
            orderObject->putTimes = 0;
        }
        orderObject->putTimes=orderObject->putTimes+1;
        QJsonObject rObj, cObj;
        if(orderObject->putType==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("非码外卖"));
        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->discount_fee*/0); // 优惠总额
        cObj.insert("dis_shop_fee", /*orderObject->dis_shop_fee*/0); // 商家承担优惠金额
        cObj.insert("dis_platform_fee", /*orderObject->dis_platform_fee*/0); // 平台承担优惠金额
        cObj.insert("send_fee", orderObject->deliveryPrice);         // 配送费
        cObj.insert("shop_fee", /*orderObject->total_fee-orderObject->send_fee-orderObject->service_fee-orderObject->dis_shop_fee*/0);         // 商户能够拿到的钱(去除平台佣金)
        cObj.insert("package_fee", orderObject->totalPrice);   // 打包费
        cObj.insert("invoice_amount",orderObject->totalPrice);
        cObj.insert("paid_trans_id",orderObject->id);
        //cObj.insert("fm_id",orderObject->fm_id);
        rObj.insert("pay_id", cObj);
        QJsonArray products;
        for(int i=0; i < orderObject->proList.count(); i++)
        {
            QJsonObject tObj;
            dishesObject* dish=orderObject->proList.at(i);
            tObj.insert("consume_num", orderObject->proList.at(i)->qty);
            tObj.insert("pid", orderObject->proList.at(i)->code);
            tObj.insert("original_price", orderObject->proList.at(i)->price);
            if(!dish->sub_products.isEmpty())
            {
                QJsonArray subProduct;
                for(int j=0; j < dish->sub_products.count(); j++)
                {
                    QJsonObject sObj;
                    dishesObject* subDish=dish->sub_products.at(j);
                    if(!subDish->code.isEmpty())
                    {
                        sObj.insert("consume_num", subDish->qty);
                        sObj.insert("pid", subDish->code);
                        sObj.insert("original_price", subDish->price);
                        subProduct.insert(0, sObj);
                    }
                }
                tObj.insert("sub_products",subProduct);
            }
            products.insert(i, 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)));
    qDebug()<<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,-1,QString::fromLocal8Bit("同意退款"));
    }
}

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

void FlowControl::onSerachOrder(const QString &text)
{
    QMap<QString,QString> orderMap;
    if(!text.isEmpty())
    {
        QMap<QString, OrderObject*>::iterator order;

        for(order = m_simValidOrderMapQueue.begin(); order!=m_simValidOrderMapQueue.end(); order++)
        {
            QString orderId = order.key();
            QString phoneId = order.value()->phone;
            while (!orderId.at(0).isDigit())
            {
              orderId = orderId.mid(1);
            }
            if(orderId.startsWith(text))
            {
                orderMap.insert(QString::fromLocal8Bit("订单号:")+orderId,QString::fromLocal8Bit("手机号:")+phoneId);
            }
            if(phoneId.startsWith(text))
            {
                orderMap.insert(QString::fromLocal8Bit("订单号:")+orderId,QString::fromLocal8Bit("手机号:")+phoneId);
            }
        }
    }
    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)
{
    _RefundOrder(orderId,reasonCode,reason);
}
