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

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

FlowControl::FlowControl()
{
    m_bFirstRecvInfo = true;
    m_timestamp = "0";
    m_loginSocket = NULL;
    m_pullOrderSocket = NULL;
    m_procOrderSocket = NULL;

    FmPlugin::GetInstance().SetRemoteInfo(ConfigManger::GetInstance().GetDbServerIp(), ConfigManger::GetInstance().GetDbServerPort());
}

void FlowControl::onGetNewStoreInfo(const QString &operator_id, const QString &pos_id, const QString &store_id, const QString &business_date)
{
    m_storeId = store_id;
    m_posId = pos_id;
    m_cashierId = operator_id;
    m_bDate = QDateTime::fromString(business_date, "yyyyMMdd");

    if(m_bFirstRecvInfo)
    {
        m_bFirstRecvInfo = false;

        m_loginSocket = new BillSocket(this);
        m_pullOrderSocket = new BillSocket(this);
        m_procOrderSocket = new BillSocket(this);

        _Login();
    }else
    {
        emit setStoreInfo(m_storeId);
        emit setCashierInfo(m_cashierId);
    }
}

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, "登录失败![网络错误]");
    }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);
            emit setCashierInfo(m_cashierId);
            _PullOrder();
        }
    }

    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);
    QLOG_INFO() << QString("pull order finsh. [result:%1][msg:%2]")
                   .arg(result).arg(error);
    if(!result)
    {
        emit setNetStatus("<font color='#ff0000'>异常</font>");
    }else
    {
        emit setNetStatus("正常");
        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;
                orderObject = m_ordersMap.value(jsonObject[JSON_ORDERID].toString());
                if(orderObject == NULL)
                {
                    //新数据
                    orderObject = new OrderObject(this);
                    orderObject->FromJson(jsonObject);
                    m_ordersMap.insert(orderObject->order_id, orderObject);
                    QLOG_INFO() << QString("new order[%1:%2].[data:%3]")
                                   .arg(orderObject->order_id, orderObject->status_desc)
                                   .arg(_GetJsonStr(jsonObject));
                    emit changeOrderStatus(orderObject);
                }else
                {
                    //旧数据有更新
                    int oldStatus = orderObject->status;
                    QString oldcourier = orderObject->courier_name;
                    orderObject->FromJson(jsonObject);
                    QLOG_INFO() << QString("old order[%1:%2].[data:%3]")
                                   .arg(orderObject->order_id, orderObject->status_desc)
                                   .arg(_GetJsonStr(jsonObject));
                    if(oldStatus != orderObject->status)
                    {
                       emit changeOrderStatus(orderObject, oldStatus);
                    }
                    if(oldcourier!=orderObject->courier_name)
                    {
                    // 打印
                        QLOG_INFO() << QString("[---begin print---].");
                        if(FmPrinter::GetInstance().DoPrint(ConfigManger::GetInstance().GetPrinterName(), orderObject))
                        {
                            QLOG_INFO() << QString("print sucessful");
                        }else
                        {
                            QLOG_INFO() << QString("print failed");
                        }
                    }
                }

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

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

    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();
            emit showDeliverPickForm(orderId, deliverList);
        }
    }

    return result;
}

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

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

    emit showAlert(AlertForm::LOADING, "正在通信......");
    QLOG_INFO() << QString("[---confirm order---]. [requestData:%1]").arg(_GetJsonStr(sendJson));
    result = m_procOrderSocket->Request(sendJson, recvJson, error);
    QLOG_INFO() << QString("confirm 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
        {
            OrderObject *orderObject = m_ordersMap.value(orderId);

            emit showAlert(AlertForm::LOADING, "正在写入销售单......");
            // 写入销售单
            // TODO
//            QLOG_INFO() << QString("[---begin entry order---].");
//            if(!FmPlugin::GetInstance().DoOrderEntry(orderObject, error))
//            {
//                while(!FmPlugin::GetInstance().DoOrderEntry(orderObject, error, true))
//                {
//                    QLOG_INFO() << QString("entry order failed[%1]").arg(error);
//                }
//            }
            QLOG_INFO() << QString("[entry order success].");

            QString remark(orderObject->remark), deliveryTime;
            remark = remark.isEmpty()? "" : QString("\r\n[备注: %1]").arg(remark);
            deliveryTime = QString("\r\n[期望送达时间: %1]").arg(QDateTime::fromTime_t(orderObject->delivery_time).toString("MM/dd hh:mm"));
            emit showAlert(AlertForm::SUCCESS, QString("接单成功!%1%2").arg(remark).arg(deliveryTime));

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

    return result;
}

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();
            // TODO  服务器端现还未开发
            //orderObject->status_desc = recvJson[JSON_STATUSDESC].toString();
            emit changeOrderStatus(orderObject, oldStatus);
        }
    }

    return result;
}

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

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

    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);
            int oldStatus = orderObject->status;
            orderObject->status = 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, "正在通信......");
    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();
            // TODO  服务器端现还未开发
            //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(VALUE_REFUSEREFUND_REASON,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();
            // TODO  服务器端现还未开发
            //orderObject->status_desc = recvJson[JSON_STATUSDESC].toString();
            emit changeOrderStatus(orderObject, oldStatus);
        }
    }

    return result;
}

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

    sendJson = DataManger::GetInstance().GetRefundOrderData("1",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
        {
            // 通知主界面移动订单
            OrderObject *orderObject = m_ordersMap.value(orderId);
            int oldStatus = orderObject->status;
            orderObject->status = recvJson[JSON_STATUS].toInt();
            // TODO  服务器端现还未开发
            //orderObject->status_desc = recvJson[JSON_STATUSDESC].toString();
            emit changeOrderStatus(orderObject, oldStatus);

            QString tmpstr;
            // 撤回销售单
            QLOG_INFO() << QString("[---begin refund order---].");
            if(!FmPlugin::GetInstance().RefundOrder(orderId,error))
            {
                tmpstr = QString("\r\n[撤回销售单失败]");
                QLOG_INFO() << QString("entry order failed[%1]").arg(error);
            }else
            {
                tmpstr = QString("\r\n[撤回销售单成功]");
            }

            emit showAlert(AlertForm::SUCCESS, QString("退单成功!%1").arg(tmpstr));
        }
    }

    return result;
}

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

void FlowControl::onProcessOrder(const QString &operation, const QString &orderId, const DeliverObject &deliverObj)
{
    if(!operation.compare(OPERATION_GETDELIVERS))
    {
        //_GetDelivers(orderId);
        _ConfirmOrder(orderId, deliverObj);
    }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);
    }else if(!operation.compare(OPERATION_COMPLETE))
    {
        _CompleteOrder(orderId);
    }else if(!operation.compare(OPERATION_REFUSEREFUND))
    {
        _RefuseRefund(orderId);
    }else if(!operation.compare(OPERATION_REFUNDORDER))
    {
        _RefundOrder(orderId);
    }
}

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

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

        for(order = m_ordersMap.begin(); order!=m_ordersMap.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("订单号:"+orderId,"手机号:"+phoneId);
            }
            if(phoneId.startsWith(text))
            {
                orderMap.insert("订单号:"+orderId,"手机号:"+phoneId);
            }
        }
    }
    emit showSearchOrderResult(orderMap);
}


