 #include "flowControl.h"
#include "fmPlugin.h"
#include "fmPrinter.h"
#include "QsLog.h"
#include "DTools/dataManger.h"
#include "preDefine.h"
#include "DTools/configManger.h"
#include "Model/cashierObject.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QTimer>
#include <QDir>
#include <QApplication>
#include "DTools/orderstatus.h"

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

FlowControl::FlowControl()
{
    m_loginSocket = NULL;
    m_pullOrderSocket = NULL;
    m_procOrderSocket = NULL;
    netErrorIndex = 0;

    QTimer::singleShot(10000,this, &FlowControl::_PostBill);
}

bool FlowControl::_GetStoreInfo()
{
    QString error;
    bool result;

    emit showAlert(AlertForm::LOADING, "正在获取门店信息......");
    QLOG_INFO() << QString("[---get storeInfo---]");
    result = FmPlugin::GetInstance().GetStoreInfo(m_storeId, m_posId, m_cashierId, m_bDate, error);
    QLOG_INFO() << QString("get storeInfo finsh. [result:%1][msg:%2][storeId:%3,posId:%4,cashierId:%5,bdate:%6]")
                   .arg(result).arg(error, m_storeId, m_posId, m_cashierId, m_bDate.toString("yyyy-MM-dd"));
    if(!result)
    {
        emit showAlert(AlertForm::ERROR, "获取门店信息失败!");
    }

    return result;
}

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

    sendJson = DataManger::GetInstance().GetLoginData(m_storeId, SERVER_PASSWORD, m_posId, m_cashierId);

    emit showAlert(AlertForm::LOADING, "正在登录......");
    QLOG_INFO() << QString("[---login---][requestData:%1]").arg(_GetJsonStr(sendJson));
    result = m_loginSocket->Request(sendJson, recvJson, error);
    QLOG_INFO() << QString("login finsh. [result:%1][msg:%2][recvData:%3]")
                   .arg(result).arg(error, _GetJsonStr(recvJson));
    if(!result)
    {
        emit showAlert(AlertForm::ERROR, "登录失败![网络错误]");
        if(neterror)//如果之前网络是正常的，则开始语音提示网络错误
        {
            emit startNetErrorRemind();
        }
        neterror=false;
    }else
    {
        if(JSON_STATUSCODE_OK != recvJson[JSON_STATUSCODE].toInt())
        {
            result = false;
            emit showAlert(AlertForm::ERROR, QString("登录失败![%1]").arg(recvJson[JSON_MESSAGE].toString()));
        }else
        {
            m_timestamp = recvJson[JSON_TIMESTAMPS].toString();
            DataManger::GetInstance().SetToken(recvJson[JSON_TOKEN].toString());
            emit hideAlert();
            emit setStoreInfo(m_storeId);
            m_storeName = recvJson[JSON_STORENAME].toString();
            FmPrinter::GetInstance().setStoreName(m_storeName);
            _PullOrder();
            // TODO(用于鲜丰演示)
            //_SynStock();
        }
    }

    if(!result)
    {
        QLOG_INFO() << QString("%1 msec after login...").arg(VALUE_RELOGINTIME);
        QTimer::singleShot(VALUE_RELOGINTIME, this, &FlowControl::_Login);
    }

    return result;
}

bool FlowControl::_PullOrder()
{
    QString error;
    bool result;
    QJsonObject sendJson;
    QJsonObject recvJson;
    int syncTime = VALUE_PULLSYNCTIME;

    sendJson = DataManger::GetInstance().GetPullOrderData(m_timestamp);

    QLOG_INFO() << QString("[---pull order---][requestData:%1]").arg(_GetJsonStr(sendJson));
    result = m_pullOrderSocket->Request(sendJson, recvJson, error);
    qDebug() << "---------------------------------------------------------------";
    qDebug() << recvJson;
    qDebug() << "---------------------------------------------------------------";
    QLOG_INFO() << QString("pull order finsh. [result:%1][msg:%2]")
                   .arg(result).arg(error);
    if(!result)
    {
        netErrorIndex++;
        emit setNetStatus("<font color='#ff0000'>异常</font>");
        if(netErrorIndex > 50)
        {
            if(neterror)//如果之前网络正常，则开始语音提示网络错误
            {
                emit startNetErrorRemind();
            }
            neterror=false;
        }
    }else
    {
        netErrorIndex = 0;
        emit setNetStatus("正常");
        if(!neterror)//如果之前网络异常，现在正常，则停止语音提示
        {
            emit stopNetErrorRemind();
        }
        neterror=true;
        if(JSON_STATUSCODE_OK != recvJson[JSON_STATUSCODE].toInt())
        {
            QString error = recvJson[JSON_MESSAGE].toString();
            QLOG_ERROR() << QString("pull orders error.[msg->%1]").arg(error);
            emit showAlert(AlertForm::ERROR, QString("获取订单失败![%1]").arg(error));
        }else
        {
            // 获取门店营业状态
            QString strOpeStatus("正常");
            QJsonArray opeStatus = recvJson[JSON_SHOPSTATUS].toArray();
            foreach(QJsonValue status, opeStatus)
            {
                QJsonObject jsonObject =  status.toObject();
                if(jsonObject[JSON_SHOPSTATUSDESC].toString().compare("营业中"))
                {
                    strOpeStatus = QString("<font color='#ff0000'>异常</font>");
                    break;
                }
            }
            emit setOpeStatus(strOpeStatus);
            // 获取订单信息
            QJsonArray orders = recvJson[JSON_ORDERS].toArray();
            foreach(QJsonValue order, orders)
            {
                QJsonObject jsonObject = order.toObject();
                OrderObject *orderObject = NULL;
                QString orderId=jsonObject[JSON_ORDERID].toString();
                orderObject = m_ordersMap.value(jsonObject[JSON_ORDERID].toString());
                if(orderObject == NULL)
                {
                    //新数据
                    orderObject = new OrderObject(this);
                    orderObject->FromJson(jsonObject);
                    orderObject->remark.remove("|");

                    //将 非码Mall 改为 鲜丰App
                    if(!orderObject->channelName.compare("非码Mall"))
                    {
                        orderObject->channelName = "鲜丰App";
                    }
                    //------------------------------


                    m_ordersMap.insert(orderObject->order_id, orderObject);
                    if(!orderObject->order_view_id.isEmpty())
                    {
                        m_view2Id.insert(orderObject->order_view_id, orderObject->order_id);
                    }

                    QLOG_INFO() << QString("new order[%1:%2].[data:%3]")
                                   .arg(orderObject->order_id, orderObject->status_desc)
                                   .arg(_GetJsonStr(jsonObject));

                    emit changeOrderStatus(orderObject);

                    if(!Orderstatus::getInstance().isorderexit(orderId))
                    {
                        Orderstatus::getInstance().statusinsert(orderId,0);
                    }
                    if(orderObject->status==2&&!Orderstatus::getInstance().isprint(orderId)&&orderObject->order_type!=3)
                    {
                        emit startRemind(0);
                        QLOG_INFO()<<QString("[---begin to tip---]");
                        // 打印
                        QLOG_INFO() << QString("[---begin print---]");
                        QSettings tmpIni(QString("%1/%2").arg(QApplication::applicationDirPath()).arg("printerConfig_tmp.ini"), QSettings::IniFormat);
                        int num = tmpIni.value(QString("%1/num").arg(orderObject->channel), 1).toInt();
                        for(int i=0; i<num; i++)
                        {
                            if(FmPrinter::GetInstance().DoPrint(ConfigManger::GetInstance().GetPrinterName(), orderObject))
                            {
                                QLOG_INFO() << QString("print sucessful");
                                Orderstatus::getInstance().printupdate(orderId,1);
                            }else
                            {
                                emit showAlert(AlertForm::ERROR, QString("打印冲突，请稍后手动打印或重启收银程序"));
                                QLOG_INFO() << QString("print failed");
                            }
                        }
                    }
                }else
                {
                    //旧数据有更新
                    int oldStatus = orderObject->status;
                    orderObject->FromJson(jsonObject);
                    orderObject->remark.remove("|");

                    //将 非码Mall 改为 鲜丰App
                    if(!orderObject->channelName.compare("非码Mall"))
                    {
                        orderObject->channelName = "鲜丰App";
                    }
                    //------------------------------


                    QLOG_INFO() << QString("\r\n\r\n old order[%1:%2].[data:%3]")
                                   .arg(orderObject->order_id, orderObject->status_desc)
                                   .arg(_GetJsonStr(jsonObject));

                    if((oldStatus != orderObject->status)  &&  (orderObject->status == 3))
                    {
                        emit showAlert(AlertForm::ERROR, QString("[%1][%2]号订单[%3]已被取消!").arg(orderObject->channelName).arg(orderObject->order_index).arg(orderObject->order_id));
                    }
                    if(oldStatus != orderObject->status)
                    {
                        emit changeOrderStatus(orderObject, oldStatus);
                    }

                    if(orderObject->delivery_status==2 && orderObject->status==2)
                    {
                        emit changeOrderStatus(orderObject, oldStatus);
                    }
                }

                if(orderObject->status==20||orderObject->status==21)
                {
                    if(FmPrinter::GetInstance().DoPrint(ConfigManger::GetInstance().GetPrinterName(), orderObject))
                    {
                        QLOG_INFO() << QString("print sucessful");
                    }else
                    {
                        emit showAlert(AlertForm::ERROR, QString("打印冲突，请稍后手动打印或重启收银程序"));
                        QLOG_INFO() << QString("print failed");
                    }
                }

                // 订单完成后两小时写销售单
//                if(orderObject->status == 6 || orderObject->status == 200)
//                {
//                    bool bWrite = true;
//                    // 检查转换信息是否正常、不正常则不写销售单（防止数据出问题影响门店正常数据）
//                    foreach(ProductObject* pro, orderObject->proList)
//                    {
//                        if(pro->sub_products.isEmpty())
//                        {
//                            if(pro->unit_ratio <= 0)
//                            {
//                                bWrite = false;
//                                break;
//                            }
//                        }else
//                        {
//                            foreach(ProductObject* cpro, pro->sub_products)
//                            {
//                                if(cpro->unit_ratio <= 0)
//                                {
//                                    bWrite = false;
//                                    break;
//                                }
//                            }
//                        }
//                    }

//                    if(bWrite)
//                    {
//                        QLOG_INFO() << QString("will entry %1").arg(orderObject->order_id);
//                        //TODO
//                        QTimer::singleShot(1000*60*60*2, [orderObject, this](){
//                              QLOG_INFO() << QString("订单[%1]进入队列").arg(orderObject->order_id);
//                              m_mutex.lock();
//                              m_billList.append(orderObject);
//                              m_mutex.unlock();
//                        });

//                    }else
//                    {
//                        //_ReportBillEntryResult(orderObject->order_id, 0, QString("销售单数据有误"));
//                        QLOG_INFO() << QString("销售单数据有误 %1").arg(orderObject->order_id);
//                    }
//                }
                m_timestamp = orderObject->timestamp;
              }
            syncTime = recvJson[JSON_SYNCTIME].toInt()*1000;
        }
    }

    QLOG_INFO() << QString("%1 msec after pull order...").arg(syncTime);
    QTimer::singleShot(syncTime, this, &FlowControl::_PullOrder);

    return result;
}

void FlowControl::_PostBill()
{
    if(m_billList.isEmpty())
    {
        QTimer::singleShot(10000, this, &FlowControl::_PostBill);
        return;
    }
    OrderObject* orderObject = m_billList.first();
    if(orderObject->status == 6 || orderObject->status == 200)
    {
       QString error, bill_data, fee_data;
       for(int i=0; i<5; i++)
       {
           QLOG_INFO() << QString("第%1次尝试写入订单%2").arg(i+1).arg(orderObject->order_id);
           bool bServerFailed = false;
           if(FmPlugin::GetInstance().DoOrderEntry(orderObject,"","",bill_data, fee_data,error, bServerFailed))
           {
               QLOG_INFO() << QString("销售单数据%1   配送费数据%2").arg(bill_data,fee_data);
               QLOG_INFO() << QString("_PullOrder DoOrderEntry successful %1 %2").arg(orderObject->order_id).arg(error);
               this->_ReportBillEntryResult(orderObject->order_id, 1, QString("成功"));
               m_mutex.lock();
               m_billList.removeOne(orderObject);
               QLOG_INFO() << QString("订单%1移出队列").arg(orderObject->order_id);
               m_mutex.unlock();

               break;
           }else
           {
               QLOG_INFO() << QString("销售单数据%1   配送费数据%2").arg(bill_data,fee_data);
               QLOG_INFO() << QString("_PullOrder DoOrderEntry failed %1 %2").arg(orderObject->order_id, error);
               this->_ReportBillEntryResult(orderObject->order_id, 0, error);

               if(bServerFailed)
               {
                   m_mutex.lock();
                   m_billList.removeOne(orderObject);
                   QLOG_INFO() << QString("订单%1移出队列").arg(orderObject->order_id);
                   m_mutex.unlock();
                   break;
               }
           }
           QEventLoop loop;
           QTimer::singleShot(1000*60, &loop, &QEventLoop::quit);
           loop.exec();
       }
    }else
    {
       QLOG_INFO() << QString("cancle entry %1").arg(orderObject->order_id);
       m_mutex.lock();
       m_billList.removeOne(orderObject);
       QLOG_INFO() << QString("订单%1移出队列").arg(orderObject->order_id);
       m_mutex.unlock();
    }

    QTimer::singleShot(10000, this, &FlowControl::_PostBill);
}

bool FlowControl::_GetDelivers(const QString &orderId)
{
    QString error;
    bool result;
    QJsonObject sendJson;
    QJsonObject recvJson;
    OrderObject *orderObj;

    orderObj = m_ordersMap.value(orderId);
    sendJson = DataManger::GetInstance().GetPullDeliverData(m_storeId, orderObj->channel,orderId);

    emit showAlert(AlertForm::LOADING, "正在获取配送员信息......");
    QLOG_INFO() << QString("[---get delivers---]. [requestData:%1]").arg(_GetJsonStr(sendJson));
    result = m_procOrderSocket->Request(sendJson, recvJson, error);
    QLOG_INFO() << QString("get delivers finsh. [result:%1][msg:%2][recvData:%3]")
                   .arg(result).arg(error, _GetJsonStr(recvJson));
    if(!result)
    {
        emit showAlert(AlertForm::ERROR, "获取配送员失败![网络错误]");
    }else
    {
        if(JSON_STATUSCODE_OK != recvJson[JSON_STATUSCODE].toInt())
        {
            result = false;
            emit showAlert(AlertForm::ERROR, QString("获取配送员失败![%1]").arg(recvJson[JSON_MESSAGE].toString()));
        }else
        {
            QList<DeliverObject> deliverList;
            QJsonArray delivers = recvJson[JSON_DELIVERS].toArray();
            foreach(QJsonValue deliver, delivers)
            {
                QJsonObject jsonObject = deliver.toObject();
                DeliverObject deliverObject;
                deliverObject.FetchDataFromJson(jsonObject);
                deliverList.append(deliverObject);
            }
            emit hideAlert();
            //如果配送员为空则直接调用配送接口
            if(deliverList.isEmpty())
            {
                _SendOrder(orderId,DeliverObject());
            }
            else{
                emit showDeliverPickForm(orderId, deliverList);
            }
        }
    }

    return result;
}

bool FlowControl::_ConfirmOrder(const QString &orderId, const DeliverObject &deliverObj)
{
    Q_UNUSED(orderId)
    Q_UNUSED(deliverObj)

    return true;
}

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

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

    emit showAlert(AlertForm::LOADING, "正在通信......");
    QLOG_INFO() << QString("[---refuse order---]. [requestData:%1]").arg(_GetJsonStr(sendJson));
    result = m_procOrderSocket->Request(sendJson, recvJson, error);
    QLOG_INFO() << QString("refuse order finsh. [result:%1][msg:%2][recvData:%3]")
                   .arg(result).arg(error, _GetJsonStr(recvJson));
    if(!result)
    {
        emit showAlert(AlertForm::ERROR, "拒单失败![网络错误]");
    }else
    {
        if(JSON_STATUSCODE_OK != recvJson[JSON_STATUSCODE].toInt())
        {
            result = false;
            emit showAlert(AlertForm::ERROR, QString("拒单失败![%1]").arg(recvJson[JSON_MESSAGE].toString()));
        }else
        {
            emit showAlert(AlertForm::SUCCESS, "拒单成功!");

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

    return result;
}

bool FlowControl::_SendOrder(const QString& orderId, const DeliverObject &deliverObj)
{
    QString error;
    bool result;
    QJsonObject sendJson;
    QJsonObject recvJson;

    sendJson = DataManger::GetInstance().GetSendOrderData(orderId,deliverObj.id, deliverObj.name,deliverObj.phone);

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

            // 通知主界面移动订单
            OrderObject *orderObject = m_ordersMap.value(orderId);
            orderObject->bAppointSender = true;
            int oldStatus = orderObject->status;
            orderObject->status = recvJson[JSON_STATUS].toInt();
            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, "正在通信......");
    QLOG_INFO() << QString("[---complete order---]. [requestData:%1]").arg(_GetJsonStr(sendJson));
    result = m_procOrderSocket->Request(sendJson, recvJson, error);
    QLOG_INFO() << QString("complete order finsh. [result:%1][msg:%2][recvData:%3]")
                   .arg(result).arg(error, _GetJsonStr(recvJson));
    if(!result)
    {
        emit showAlert(AlertForm::ERROR, "完成失败![网络错误]");
    }else
    {
        if(JSON_STATUSCODE_OK != recvJson[JSON_STATUSCODE].toInt())
        {
            result = false;
            emit showAlert(AlertForm::ERROR, QString("完成失败![%1]").arg(recvJson[JSON_MESSAGE].toString()));
        }else
        {
            emit showAlert(AlertForm::SUCCESS, "完成成功!");

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

    return result;
}

bool FlowControl::_ReportBillEntryResult(const QString &orderId, int status, const QString &error)
{  
    bool result;
    QJsonObject sendJson;
    QJsonObject recvJson;

    sendJson = DataManger::GetInstance().GetReportOERData(orderId, status, error);

    QLOG_INFO() << QString("[---report bill result---]. [requestData:%1]").arg(_GetJsonStr(sendJson));
    QString error1;
    result = m_procOrderSocket->Request(sendJson, recvJson, error1);
    QLOG_INFO() << QString("report bill result finsh. [result:%1][msg:%2][recvData:%3]")
                   .arg(result).arg(error1, _GetJsonStr(recvJson));

    return result;
}

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

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

    emit showAlert(AlertForm::LOADING, "正在通信......");
    QLOG_INFO() << QString("[---chargeoff order---]. [requestData:%1]").arg(_GetJsonStr(sendJson));
    QString error1;
    result = m_procOrderSocket->Request(sendJson, recvJson, error1);
    QLOG_INFO() << QString("chargeoff order finsh. [result:%1][msg:%2][recvData:%3]")
                   .arg(result).arg(error1, _GetJsonStr(recvJson));

    if(!result)
    {
        emit showAlert(AlertForm::ERROR, "核销失败![网络错误]");
    }else
    {
        if(JSON_STATUSCODE_OK != recvJson[JSON_STATUSCODE].toInt())
        {
            result = false;
            emit showAlert(AlertForm::ERROR, QString("核销失败![%1]").arg(recvJson[JSON_MESSAGE].toString()));
        }else
        {
            emit showAlert(AlertForm::SUCCESS, "核销成功!");

            if(m_ordersMap.value(orderId)->order_type == 3)
            {
                // 打印
                QLOG_INFO() << QString("[---begin print---]");
                QSettings tmpIni(QString("%1/%2").arg(QApplication::applicationDirPath()).arg("printerConfig_tmp.ini"), QSettings::IniFormat);
                int num = tmpIni.value(QString("%1/num").arg(m_ordersMap.value(orderId)->channel), 1).toInt();
                for(int i=0; i<num; i++)
                {
                    if(FmPrinter::GetInstance().DoPrint(ConfigManger::GetInstance().GetPrinterName(), m_ordersMap.value(orderId)))
                    {
                        QLOG_INFO() << QString("print sucessful");
                        Orderstatus::getInstance().printupdate(orderId,1);
                    }else
                    {
                        emit showAlert(AlertForm::ERROR, QString("打印冲突，请稍后手动打印或重启收银程序"));
                        QLOG_INFO() << QString("print failed");
                    }
                }
            }

            // 通知主界面移动订单
            OrderObject *orderObject = m_ordersMap.value(orderId);
            int oldStatus = orderObject->status;
            orderObject->status = recvJson[JSON_STATUS].toInt();
            orderObject->status_desc = recvJson[JSON_STATUSDESC].toString();
            emit changeOrderStatus(orderObject, oldStatus);
         }
    }
    return result;
}

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

    sendJson = DataManger::GetInstance().GetRefuseRefundData("菜品已送出",orderId);

    emit showAlert(AlertForm::LOADING, "正在通信......");
    QLOG_INFO() << QString("[---refuseRefund order---]. [requestData:%1]").arg(_GetJsonStr(sendJson));
    result = m_procOrderSocket->Request(sendJson, recvJson, error);
    QLOG_INFO() << QString("refuseRefund order finsh. [result:%1][msg:%2][recvData:%3]")
                   .arg(result).arg(error, _GetJsonStr(recvJson));
    if(!result)
    {
        emit showAlert(AlertForm::ERROR, "拒绝退单失败![网络错误]");
    }else
    {
        if(JSON_STATUSCODE_OK != recvJson[JSON_STATUSCODE].toInt())
        {
            result = false;
            emit showAlert(AlertForm::ERROR, QString("拒绝退单失败![%1]").arg(recvJson[JSON_MESSAGE].toString()));
        }else
        {
            emit showAlert(AlertForm::SUCCESS, "拒绝退单成功!");

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

    return result;
}

bool FlowControl::_GetCashiers(QList<CashierObject> &cashiersList)
{
    QString strCashiers, error;
    bool result;

    emit showAlert(AlertForm::LOADING, "正在查询收银员信息.....");
    QLOG_INFO() << QString("[---get cashiers---].");
    result = FmPlugin::GetInstance().GetOnDutyCashiers(cashiersList, error);
    foreach (CashierObject cashier, cashiersList)
    {
        strCashiers.append(QString("|%1,%2,%3,%4|").arg(cashier.id, cashier.name, cashier.shiftId, cashier.shiftName));
    }
    QLOG_INFO() << QString("get cashiers finsh. [result:%1][msg:%2][data:%3]").arg(result).arg(error, strCashiers);
    if(!result)
    {
        emit showAlert(AlertForm::ERROR, "查询收银员信息失败!");
    }
    return result;
}

bool FlowControl::_SynStock()
{
    QList<StockObject> stockList;
    QString strStock, error;
    int synInterval = VALUE_SYNSTOCKINTERVAL;
    bool result;

    QLOG_INFO() << QString("[---get stockInfo---].");
    result = FmPlugin::GetInstance().GetStockInfo(stockList, error);
    foreach (StockObject stock, stockList)
    {
        strStock.append(QString("|%1,%2,%3|").arg(stock.id, stock.upc).arg(QString::number(stock.num)));
    }
    QLOG_INFO() << QString("get stockInfo finsh. [result:%1][msg:%2][data:%3]").arg(result).arg(error, strStock);
    if(result)
    {
        // 获取库存信息成功则推送到服务器
        QJsonObject sendJson;
        QJsonObject recvJson;
        sendJson = DataManger::GetInstance().GetSynStockData(stockList);
        QLOG_INFO() << QString("[---push stockInfo---]. [requestData:%1]").arg(_GetJsonStr(sendJson));
        result = m_syncStockSocket->Request(sendJson, recvJson, error);
        QLOG_INFO() << QString("push stockInfo finsh. [result:%1][msg:%2][recvData:%3]")
                       .arg(result).arg(error, _GetJsonStr(recvJson));
        if(result)
        {
            if(JSON_STATUSCODE_OK == recvJson[JSON_STATUSCODE].toInt())
            {
                synInterval = recvJson[JSON_SYNCTIME].toInt()*1000;
            }
        }
    }

    QLOG_INFO() << QString("%1 msec after synStock...").arg(synInterval);
    QTimer::singleShot(synInterval, this, &FlowControl::_SynStock);

    return result;
}

bool FlowControl::_CheckCashiers()
{
    bool result = false;

    QList<CashierObject> cashiersList;
    if(_GetCashiers(cashiersList))
    {
        foreach (CashierObject cashier, cashiersList)
        {
            if(!cashier.id.compare(m_cashierObject.id))
            {
                m_cashierObject = cashier;
                result = true;
                break;
            }
        }
        if(result == false)
        {
            emit showAlert(AlertForm::ERROR, "当前收银员已下班请重新选择!");
        }
    }

    return result;
}



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

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

    sendJson = DataManger::GetInstance().GetRefundOrderData(reason,orderId);

    emit showAlert(AlertForm::LOADING, "正在通信......");
    QLOG_INFO() << QString("[---refund order---]. [requestData:%1]").arg(_GetJsonStr(sendJson));
    result = m_procOrderSocket->Request(sendJson, recvJson, error);
    QLOG_INFO() << QString("refund order finsh. [result:%1][msg:%2][recvData:%3]")
                   .arg(result).arg(error, _GetJsonStr(recvJson));
    if(!result)
    {
        emit showAlert(AlertForm::ERROR, "完成失败![网络错误]");
    }else
    {
        if(JSON_STATUSCODE_OK != recvJson[JSON_STATUSCODE].toInt())
        {
            result = false;
            emit showAlert(AlertForm::ERROR, QString("退款失败![%1]").arg(recvJson[JSON_MESSAGE].toString()));
        }else
        {
            emit showAlert(AlertForm::SUCCESS, "退款成功!");

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

    return result;
}


void FlowControl::onFlowStart()
{
    m_timestamp = "0";
    m_loginSocket = new BillSocket(this);
    m_pullOrderSocket = new BillSocket(this);
    m_procOrderSocket = new BillSocket(this);
    m_syncStockSocket = new BillSocket(this);

    if(_GetStoreInfo())
    {
        _Login();
    }
    return;
}

void FlowControl::onConnectDb(const QString &host, const QString &username, const QString &password, const QString &dbname)
{
    QString error; bool result;
    QLOG_INFO() << QString("[---connect database---]. [host:%1][username:%2][password:%3][dbname:%4]")
                   .arg(host, username, password, dbname);
    result = FmPlugin::GetInstance().ConnectDb(host, username, password, dbname, error);
    QLOG_INFO() << QString("connect finsh. [result:%1][msg:%2]").arg(result).arg(error);
    emit connectDbFinsh(result, error);
    return;
}

void FlowControl::onProcessOrder(const QString &operation, const QString &orderId, const DeliverObject &deliverObj)
{
    // 如果是自提订单则核销
    if(m_ordersMap.value(orderId)->order_type == 3)
    {
       _ChargeOffOrder(orderId);
    }else if(!operation.compare(OPERATION_GETDELIVERS))
    {
        _GetDelivers(orderId);
    }else if(!operation.compare(OPERATION_CONFRIM))
    {
        _ConfirmOrder(orderId, deliverObj);
    }else if(!operation.compare(OPERATION_REFUSE))
    {
        _RefuseOrder(orderId, 2);
    }else if(!operation.compare(OPERATION_SENDOUT))
    {

            _SendOrder(orderId,deliverObj);

    }else if(!operation.compare(OPERATION_COMPLETE))
    {
        // 如果是自提订单则核销
        if(m_ordersMap.value(orderId)->order_type == 3)
        {
           _ChargeOffOrder(orderId);
        }else
        {
            _CompleteOrder(orderId);
        }
    }else if(!operation.compare(OPERATION_REFUSEREFUND))
    {
        _RefuseRefund(orderId);
    }
}

void FlowControl::onGetOnDutyCashiers()
{
    QList<CashierObject> cashiersList;
    if(_GetCashiers(cashiersList))
    {
        emit hideAlert();
        emit showCashierPickForm(cashiersList);
    }
}

void FlowControl::onUpdateCashier(const CashierObject &cashier)
{
    m_cashierObject = cashier;
}

void FlowControl::onGetOrderDetails(const QString &orderId)
{
    //    if(_CheckCashiers())
    //    {
    emit hideAlert();
    QString lOrderId;
    if(m_view2Id.contains(orderId))
    {
        lOrderId = m_view2Id.value(orderId);
    }else
    {
        lOrderId = orderId;
    }
    emit showOrderDetails(m_ordersMap.value(lOrderId));
    //    }
}

void FlowControl::onReEntryOrder(const QString &orderId)
{
//    emit showAlert(AlertForm::LOADING, "正在补录到天天饮食......");

//    QLOG_INFO() << QString("[---order reEntry begin---]");
//    // 写入销售单
//    OrderObject *orderObject = m_ordersMap.value(orderId);
//    QString error;
//    if(!FmPlugin::GetInstance().DoOrderEntry(orderObject, m_cashierObject.id, m_cashierObject.name,
//                                             m_cashierObject.shiftId, m_cashierObject.shiftName, error))
//    {
//        QLOG_ERROR() << QString("order reEntry failed,[%1]").arg(error);
//        emit showAlert(AlertForm::ERROR, "<font color=\"#FF0000\">补录天天饮食失败,请联系管理员或者进群咨询(205821431)</font>");
//    }else
//    {
//        QFile file(QString("%1/orders/%2").arg(QApplication::applicationDirPath(), orderObject->order_id));
//        file.remove();
//        QLOG_INFO() << QString("order reEentry success.");
//        emit showAlert(AlertForm::SUCCESS, "补录天天饮食成功");
//    }
}

void FlowControl::onSerachOrder(const QString &text)
{
    qDebug() << "开始搜索" <<text;
    QStringList orderIdList;
    if(!text.isEmpty())
    {

        QMap<QString, OrderObject*>::iterator order;
        for(order = m_ordersMap.begin(); order!=m_ordersMap.end(); order++)
        {
            QString orderId = order.key();
            qDebug() << orderId;

            if(orderId.startsWith(text))
            {
                orderIdList.append(order.key());
            }
        }

    }
    if(orderIdList.isEmpty())
    {
        emit showAlert(AlertForm::LOADING, "正在获取订单信息......");

        QString error;
        bool result;
        QJsonObject sendJson;
        QJsonObject recvJson;

        sendJson = DataManger::GetInstance().GetPullSingleOrder(text);

        emit showAlert(AlertForm::LOADING, "正在通信......");
        QLOG_INFO() << QString("[---PullSingleOrder---]. [requestData:%1]").arg(_GetJsonStr(sendJson));
        result = m_procOrderSocket->Request(sendJson, recvJson, error);
        QLOG_INFO() << QString("PullSingleOrder finsh. [result:%1][msg:%2][recvData:%3]")
                       .arg(result).arg(error, _GetJsonStr(recvJson));
        if(!result)
        {
            emit showAlert(AlertForm::ERROR, "拉取订单失败![网络错误]");
        }else
        {
            if(JSON_STATUSCODE_OK != recvJson[JSON_STATUSCODE].toInt())
            {
                result = false;
                emit showAlert(AlertForm::ERROR, QString("拉取订单失败![%1]").arg(recvJson[JSON_MESSAGE].toString()));
            }else
            {
                //新数据
                OrderObject *orderObject = new OrderObject(this);
                orderObject->FromJson(recvJson["order"].toObject());
                orderObject->remark.remove("|");

                //将 非码Mall 改为 鲜丰App
                if(!orderObject->channelName.compare("非码Mall"))
                {
                    orderObject->channelName = "鲜丰App";
                }

                m_ordersMap.insert(orderObject->order_id, orderObject);
                emit changeOrderStatus(orderObject);
                orderIdList.append(orderObject->order_id);
                emit showSearchOrderResult(orderIdList);
            }
        }
    }else
    {
        emit showSearchOrderResult(orderIdList);
    }
    qDebug() << "开始搜索333333333333333";
}

void FlowControl::onRefund(const QString &orderId, const QString &reason)
{
    _RefundOrder(orderId,reason);
}
