#include "fmPlugin.h"
#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>
#include <QVariant>
#include <QDebug>
#include <QSettings>
#include <QCoreApplication>
#include <QFile>
#include <QUrl>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QTimer>
#include <QJsonDocument>
#include <QDir>
#include <QJsonArray>
#include <QNetworkReply>
#include "DTools/configManger.h"

bool HTTP::post(const QNetworkRequest &request, const QByteArray &appendData, QByteArray &target, const int &timeout, QString &error)
{
    error = "";
    target.clear();
    if(QNetworkAccessManager::Accessible != manage_.networkAccessible())
    {
        manage_.setNetworkAccessible(QNetworkAccessManager::Accessible);
    }

    QEventLoop eventLoop;
    QNetworkReply *reply = manage_.post(request , appendData);
    QObject::connect(&manage_, SIGNAL(networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility)), &eventLoop, SLOT(quit()));
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), &eventLoop, SLOT(quit()));
    // 加用定时器防止网络出现异常长时间不返回导致的阻塞
    QTimer::singleShot(timeout, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();

   if(reply->error() != QNetworkReply::NoError)
   {
       error = reply->errorString();
       return false;
   }

   target = reply->readAll();
   if(target.size() == 0)
   {
       error = "timeout";
       return false;
   }

   reply->deleteLater();
   return true;
}

FmPlugin &FmPlugin::GetInstance()
{
    static FmPlugin fmPlugin;
    return fmPlugin;
}

bool FmPlugin::ConnectDb(const QString &host, const QString &username, const QString &password, const QString &dbname, QString &error)
{
    // TODO(用于鲜丰演示)
    return true;

    // 清除之前的连接
    QSqlDatabase::removeDatabase(m_db.connectionName());

    m_db = QSqlDatabase::addDatabase("QODBC");
    m_db.setConnectOptions(QString("SQL_ATTR_LOGIN_TIMEOUT=5;SQL_ATTR_CONNECTION_TIMEOUT=5"));
    m_db.setDatabaseName(QString("Driver={sql server}; server=%1; database=%2; uid=%3; pwd=%4")
                         .arg(host).arg(dbname).arg(username).arg(password));

    if(m_db.open())
    {
        error = QString("success");
        m_db.close();

        return true;
    }else
    {
        error = m_db.lastError().text();

        return false;
    }
}

bool FmPlugin::GetStoreInfo(QString &storeId, QString &posId, QString &cashierId, QDateTime &dateTime, QString &error)
{
    QString apppath=QCoreApplication::applicationDirPath();
    QString inipath=apppath+QString("/storeInfo.ini");
    qDebug()<<inipath;
    QSettings set(inipath, QSettings::IniFormat);
    storeId = set.value("info/storeId").toString();
    m_storeId = storeId;
    posId = set.value("info/posId").toString();
    cashierId = QString("001");

    return true;
}

bool FmPlugin::GetOnDutyCashiers(QList<CashierObject> &cashiersList, QString &error)
{
    CashierObject obj;
    obj.id = "001";
    obj.name = "鲜丰测试";
    cashiersList.append(obj);
    return true;


    if(!m_db.open())
    {
        error = m_db.lastError().text();
        return false;
    }
    // 获取在班收银员信息
    QSqlQuery query = QSqlQuery(m_db);
    QString queryCashiers("select * from v_km_cashshift;");
    query.prepare(queryCashiers);
    if (!query.exec())
    {
        error = query.lastError().text();
        m_db.close();
        return false;
    }
    while(query.next())
    {
        CashierObject cashierObj;
        cashierObj.id           = query.value(0).toString();
        cashierObj.name         = query.value(1).toString();
        cashierObj.shiftId      = query.value(2).toString();
        cashierObj.shiftName    = query.value(3).toString();
        cashiersList.append(cashierObj);
    }

    error = QString("success");
    m_db.close();
    return true;
}

bool FmPlugin::DoOrderEntry(const OrderObject *orderObject, const QString &cashierId, const QString &cashierName, QString &bill_data, QString &fee_data, QString &error, bool& bServerFailed)
{
    Q_UNUSED(cashierId)Q_UNUSED(cashierName)

    QString apppath=QCoreApplication::applicationDirPath();
    // 检查这单之前是否写过
    QString remark_file_path = QString("%1/orders/%2/%3_%4").arg(apppath, QDateTime::fromTime_t(orderObject->create_time).toString("yyyy-MM-dd"), orderObject->channel ,orderObject->order_id);
    QFile file(remark_file_path);
    if(file.exists())
    {
        error = "aready writed to haiding";
        return true;
    }

    QString inipath=apppath+QString("/config.ini");
    QSettings set(inipath, QSettings::IniFormat);
    QUrl url_bill, url_fee, url_vip;
    url_bill = set.value("HdServer/url_bill").toUrl();
    url_fee = set.value("HdServer/url_fee").toUrl();
    url_vip = set.value("HdServer/url_vip").toUrl();

    HTTP http;
    QByteArray recvArray;

    QNetworkRequest request_vip ,requset_bill, request_fee;
    request_vip.setUrl(url_vip);
    request_vip.setRawHeader("Content-Type","application/json;charset=utf-8");
    request_vip.setRawHeader("Accept", "application/json;charset=utf-8");
    QString authorData = "Basic " + QString("admin:www.hd123.com").toLocal8Bit().toBase64();
    request_vip.setRawHeader("Authorization", authorData.toLocal8Bit());

    requset_bill.setUrl(url_bill);
    requset_bill.setRawHeader("Content-Type","application/json;charset=utf-8");
    requset_bill.setRawHeader("Accept", "application/json;charset=utf-8");

    request_fee.setUrl(url_fee);
    request_fee.setRawHeader("Content-Type","application/json;charset=utf-8");
    request_fee.setRawHeader("Accept", "application/json;charset=utf-8");

    // 查询会员号
    QString memberCode("");
    if(http.post(request_vip, _GetVipQueryData(orderObject->phone, QDateTime::fromTime_t(orderObject->create_time).toString("yyyy-MM-ddThh:mm:ss.zzz+0800")), recvArray, 10000, error))
    {
        QJsonObject recvJson;
        recvJson = QJsonDocument::fromJson(recvArray).object();
        memberCode = recvJson["response"].toObject()["member"].toObject()["id"].toString();
    }

    // 写入销售单
    bill_data = _GetOrderEntryData(orderObject, memberCode);
    if(http.post(requset_bill, _GetOrderEntryData(orderObject, memberCode), recvArray, 20000, error))
    {
        QJsonObject recvJson;
        recvJson = QJsonDocument::fromJson(recvArray).object();
        qDebug() << recvJson;
        QString uuid = recvJson["uuid"].toString();
        if(uuid.isEmpty())
        {
            error = recvJson["echoMessage"].toString();
            bServerFailed = true;
            return false;
        }
        recvArray.clear();

        // 写入配送费&服务费&包装费
        fee_data = _GetFeeData(orderObject, uuid);
        if(http.post(request_fee, _GetFeeData(orderObject, uuid), recvArray, 20000, error))
        {
            QJsonObject recvJson;
            recvJson = QJsonDocument::fromJson(recvArray).object();
            if(recvJson["echoCode"].toString() != "0")
            {
                error = recvJson["echoMessage"].toString();
                return false;
            }

            // 记录为文件形式下次直接跳过
            QDir().mkpath(remark_file_path.mid(0, remark_file_path.lastIndexOf("/")));
            file.open(QFile::WriteOnly);
            file.close();
            return true;
        }else
        {
            error =  QString("配送费服务器,%1").arg(error);
        }
    }else
    {

        error =  QString("销售单服务器,%1").arg(error);
    }

    return false;
}

bool FmPlugin::GetStockInfo(QList<StockObject> &stockList, QString &error)
{
    if(!m_db.open())
    {
        error = m_db.lastError().text();
        return false;
    }
    StockObject stock;
    QSqlQuery query = QSqlQuery(m_db);
    QString queryStock("select * from v_km_clearfood;");
    query.prepare(queryStock);
    if (!query.exec())
    {
        error = query.lastError().text();
        m_db.close();
        return false;
    }
    while(query.next())
    {
        stock.id = query.value(0).toString();
        stock.num = query.value(2).toInt();
        stockList.append(stock);
    }
    error = QString("success");
    m_db.close();
    return true;
}

bool FmPlugin::_InsertInto_p_t_fmwm_custinfo(int &custid)
{
    QSqlQuery query =  QSqlQuery(m_db);
    // 插入顾客信息表
    QString queryInsert("insert into p_t_fmwm_custinfo(cphone, ccust_n, ssex, saddr) \
                        values(?,?,?,?) select @@identity;");
            query.prepare(queryInsert);
    query.bindValue(0, m_orderObject->phone);
    query.bindValue(1, m_orderObject->customer);
    query.bindValue(2, "");
    query.bindValue(3, m_orderObject->address);
    if(!query.exec())
    {
        return false;
    }
    query.next();
    custid = query.value(0).toInt();
    return true;
}

bool FmPlugin::_InsertInto_d_t_food_fmbill0(const QString& cashierId, const QString& cashierName, const QString& shiftId, const QString& shiftName, int custid)
{
    QSqlQuery query = QSqlQuery(m_db);
    // 查询营业日
    QDateTime dbussiness;
    QString queryDateTime("select sys_var_value from sys_t_system where sys_var_id='dBusiness';");
    query.prepare(queryDateTime);
    if (!query.exec())
    {
        m_lastError = query.lastError().text();
        return false;
    }
    query.next();
    dbussiness = query.value(0).toDateTime();

    // 插入到临时表
    QString queryInsert("insert into d_t_food_fmbill0(cbill_c,cbranch_c,dBusiness,"
                        "ccashier_c, ccashier_n, cshift_c, cshift_n,"
                        "iguestnum,dtbilltime,dtsettletime,noughtamt,npayamt,"
                        "ndisamt,sbilltype,fmwmbillid,sprovider,nfreight,icustid)"
                        "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);");
    query.prepare(queryInsert);
    query.bindValue(0, m_orderObject->order_id);
    query.bindValue(1, m_storeId);
    query.bindValue(2, dbussiness);
    query.bindValue(3, cashierId);
    query.bindValue(4, cashierName);
    query.bindValue(5, shiftId);
    query.bindValue(6, shiftName);
    query.bindValue(7, m_orderObject->remark.mid(m_orderObject->remark.lastIndexOf(':')+1).toInt());
    query.bindValue(8, QDateTime::fromTime_t(m_orderObject->create_time));
    query.bindValue(9, QDateTime::fromTime_t(m_orderObject->create_time));
    query.bindValue(10, _Penny2Dollar(m_orderObject->shop_fee));
    query.bindValue(11, _Penny2Dollar(m_orderObject->shop_fee));
    query.bindValue(12, _Penny2Dollar(m_orderObject->discount_fee));
    query.bindValue(13, QString("\351\200\201\351\244\220\345\215\225"));// 送餐单
    query.bindValue(14, m_orderObject->order_id);
    query.bindValue(15, m_orderObject->channelName);
    //query.bindValue(16, m_orderObject->pay_type.compare("在线支付") ? "0" : _Penny2Dollar(m_orderObject->send_fee));
    query.bindValue(17, custid);
    if(!query.exec())
    {
        m_lastError = query.lastError().text();
        return false;
    }
    return true;
}

bool FmPlugin::_InsertInto_d_t_food_fmbills0()
{
    QSqlQuery query = QSqlQuery(m_db);
    // 插入商品详情
    QString queryInsert("insert into d_t_food_fmbills0(cbill_c,cfoodbill,"
                        "cfood_c,cfood_n,nqty,nprc,namt)"
                        "values(?,?,?,?,?,?,?);");
    query.prepare(queryInsert);
    for(int i=0; i<m_orderObject->proList.count(); i++)
    {
        query.bindValue(0, m_orderObject->order_id);
        query.bindValue(1, QString("%1").arg(QString::number(i+1),4,QChar('0')));
        query.bindValue(2, m_orderObject->proList.at(i)->pid);
        query.bindValue(3, m_orderObject->proList.at(i)->name);
        query.bindValue(4, QString::number(m_orderObject->proList.at(i)->productAmount));
        query.bindValue(5, _Penny2Dollar(m_orderObject->proList.at(i)->price));
        query.bindValue(6, _Penny2Dollar(m_orderObject->proList.at(i)->price*m_orderObject->proList.at(i)->productAmount));
        if(!query.exec())
        {
            m_lastError = query.lastError().text();
            return false;
        }
    }
    return true;
}

bool FmPlugin::_InsertInto_d_t_bill_fmpay0()
{
    QSqlQuery query = QSqlQuery(m_db);
    // 插入支付详情
    QString queryInsert("insert into d_t_bill_fmpay0(cbill_c,"
                        "cbillpay,cpay_c,cpay_n,npayamt)"
                        "values(?,?,?,?,?);");
    query.prepare(queryInsert);
    query.bindValue(0, m_orderObject->order_id);
    query.bindValue(1, "01");
    QString cpay_c, cpay_n;
    if(!m_orderObject->pay_type.compare("在线支付"))
    {
        if(!m_orderObject->channel.compare("mtwm"))
        {
            cpay_c = QString("14");
            cpay_n = QString("\347\276\216\345\233\242\345\244\226\345\215\226");//美团外卖
        }else if(!m_orderObject->channel.compare("fmwd"))
        {
            cpay_c = QString("13");
            cpay_n = QString("\345\276\256\344\277\241\345\244\226\345\215\226");//微店外卖
        }
    }else
    {
        cpay_c = QString("01");
        cpay_n = QString("\347\216\260\351\207\221");//现金
    }
    query.bindValue(2, cpay_c);
    query.bindValue(3, cpay_n);
    query.bindValue(4, _Penny2Dollar(m_orderObject->shop_fee));
    if(!query.exec())
    {
        m_lastError = query.lastError().text();
        return false;
    }
    return true;
}

bool FmPlugin::_Exec_pr_fmwm()
{
    QSqlQuery query = QSqlQuery(m_db);
    query.prepare("exec pr_fmwm ?, ? output;");
    query.bindValue(0, m_orderObject->order_id);
    query.bindValue(1, 0, QSql::Out);
    if(!query.exec())
    {
        m_lastError = query.lastError().text();
        return false;
    }
    if(query.boundValue(1).toInt() != 1)
    {
        m_lastError = QString("pr_fmwm result[%1]").arg(query.boundValue(1).toInt());
        return false;
    }
    return true;
}

double FmPlugin::_Penny2Dollar(int penny)
{
    double dollar = (double)penny/100;
    return dollar;
}

QByteArray FmPlugin::_GetVipQueryData(const QString &phone, const QString &time)
{
    QJsonObject rObj , cObj, cObj1 , ccObj;
    ccObj.insert("namespace", "");
    ccObj.insert("id", "");
    ccObj.insert("fullName", "");
    cObj.insert("time", time);
    cObj.insert("operator", ccObj);
    cObj.insert("terminalId", "");
    cObj.insert("store", "FM001");
    cObj1.insert("type", "mobile");
    cObj1.insert("id", phone);
    rObj.insert("operCtx", cObj);
    rObj.insert("accout", cObj1);
    return QJsonDocument(rObj).toJson(QJsonDocument::Compact);
}

QByteArray FmPlugin::_GetOrderEntryData(const OrderObject *orderObject, const QString &memberCode)
{
    QJsonObject rObj;
    rObj.insert("uuid", orderObject->order_view_id.isEmpty()?orderObject->order_id:orderObject->order_view_id);

    // 京东的服务费由客户端来算出
    // 计算规则 （订单商品金额的总和-商家承担优惠）*0.08
    QString serviceFee;
    if(orderObject->channel=="jdwm")
    {
        serviceFee = QString::number(_Penny2Dollar((orderObject->product_fee-orderObject->dis_shop_fee)*0.08),'f',2);
    }else
    {
        serviceFee = QString::number(_Penny2Dollar(orderObject->service_fee),'f',2);
    }

    rObj.insert("senderCode", m_storeId);
    rObj.insert("senderWrh", "-");
    rObj.insert("receiverCode", m_recCodeMap.value(orderObject->channel));
    rObj.insert("contactor", orderObject->customer);
    rObj.insert("phoneNumber", orderObject->phone);
    rObj.insert("deliverAddress", orderObject->address);
    rObj.insert("remark", QDateTime::currentDateTime().toString("yyyy-MM-ddThh:mm:ss.zzz+0800"));
    rObj.insert("ocrDate", QDateTime::fromTime_t(orderObject->create_time).toString("yyyy-MM-ddThh:mm:ss.zzz+0800"));
    rObj.insert("membercode", memberCode);
    rObj.insert("filler", "非码接口");
    rObj.insert("seller", orderObject->channelName);
    rObj.insert("souceOrderCls", "");
    rObj.insert("negInvFlag", 0);

    typedef struct PRODUCT_ELEMET
    {
        QString skuId;
        float qty;
        float ss_fee;
        float ys_fee;
        float note; // 成本金额
    }Product_elemet;

    QMap<QString, Product_elemet>_proMap;
    QJsonArray products;
    for(int i=0; i < orderObject->proList.count(); i++)
    {
       ProductObject *pObj = orderObject->proList.at(i);
       if(!pObj->sub_products.isEmpty())
       {
           //qDebug() << "有子商品";
           // 组合商品应收的钱
           float zh_ys_fee = _Penny2Dollar(pObj->price*pObj->productAmount);
           //qDebug() << "组合应收" <<zh_ys_fee << pObj->price << pObj->productAmount;
           // 组合商品实际收到的钱
           float zh_ss_fee = zh_ys_fee*(1-(float)orderObject->dis_shop_fee/orderObject->product_fee);
           // 组合的成本
           float zh_cb_fee =0;
           foreach(ProductObject *cpObj, pObj->sub_products)
           {
               float ratio = (float)cpObj->unit_ratio/100;
                zh_cb_fee += _Penny2Dollar(cpObj->productAmount*ratio*cpObj->cost);
           }


           foreach(ProductObject *cpObj, pObj->sub_products)
           {

               float ratio = (float)cpObj->unit_ratio/100;
               // qDebug() << "子商品:" << cpObj->name << cpObj->productAmount<<cpObj->cost <<ratio;

               // 该商品的成本金额
               float cb_fee = _Penny2Dollar(cpObj->productAmount*ratio*cpObj->cost);
               // 该商品应收的钱 组合应收的钱*（该商品的成本/组合成本）
               float ys_fee =  zh_ys_fee*(cb_fee/zh_cb_fee);
               // 该商品实际收到的钱 组合实际收的钱*（该商品的成本/组合成本）
               float ss_fee = zh_ss_fee*(cb_fee/zh_cb_fee);
               // qDebug() << "该商品价格 " << cb_fee << ys_fee << ss_fee;
//               // 该商品应收的钱
//               float ys_fee = _Penny2Dollar(cpObj->price*cpObj->productAmount);
//               // 该商品实际收到的钱
//               float ss_fee = ys_fee*(1-(float)orderObject->dis_shop_fee/orderObject->product_fee);

               if(_proMap.contains(cpObj->stock_barcode))
               {
                   Product_elemet elemet;
                   elemet.skuId = cpObj->stock_barcode;
                   elemet.qty =  _proMap.value(cpObj->stock_barcode).qty + cpObj->productAmount*ratio;
                   elemet.ys_fee = _proMap.value(cpObj->stock_barcode).ys_fee + ys_fee;
                   elemet.ss_fee = _proMap.value(cpObj->stock_barcode).ss_fee + ss_fee;
                   elemet.note = _proMap.value(cpObj->stock_barcode).note + cb_fee;

                   _proMap.insert(cpObj->stock_barcode,  elemet);
                   //qDebug() << "商品插入表格0 " << elemet.skuId << elemet.qty << elemet.ys_fee << elemet.ss_fee << elemet.note;
               }else
               {
                   Product_elemet elemet;
                   elemet.skuId = cpObj->stock_barcode;
                   elemet.qty = cpObj->productAmount*ratio;
                   elemet.ys_fee = ys_fee;
                   elemet.ss_fee = ss_fee;
                   elemet.note = cb_fee;
                   _proMap.insert(cpObj->stock_barcode,  elemet);
                   //qDebug() << "商品插入表格1 " << elemet.skuId << elemet.qty << elemet.ys_fee << elemet.ss_fee << elemet.note;
               }
           }
       }else
       {
           float ratio = (float)pObj->unit_ratio/100;

           // 该商品应收的钱
           float ys_fee = _Penny2Dollar(pObj->price*pObj->productAmount);
           // 该商品实际收到的钱
           float ss_fee = ys_fee*(1-(float)orderObject->dis_shop_fee/orderObject->product_fee);

           if(_proMap.contains(pObj->stock_barcode))
           {
               Product_elemet elemet;
               elemet.skuId = pObj->stock_barcode;
               elemet.qty =  _proMap.value(pObj->stock_barcode).qty + pObj->productAmount*ratio;
               elemet.ys_fee = _proMap.value(pObj->stock_barcode).ys_fee + ys_fee;
               elemet.ss_fee = _proMap.value(pObj->stock_barcode).ss_fee + ss_fee;
               elemet.note = _proMap.value(pObj->stock_barcode).note + _Penny2Dollar(pObj->productAmount*ratio*pObj->cost);
               _proMap.insert(pObj->stock_barcode,  elemet);
           }else
           {
               Product_elemet elemet;
               elemet.skuId = pObj->stock_barcode;
               elemet.qty = pObj->productAmount*ratio;
               elemet.ys_fee = ys_fee;
               elemet.ss_fee = ss_fee;
               elemet.note = _Penny2Dollar(pObj->productAmount*ratio*pObj->cost);
               _proMap.insert(pObj->stock_barcode,  elemet);
           }
       }
    }

    int i = 0;
    foreach(Product_elemet elemet, _proMap.values())
    {
        QJsonObject cObj;
        cObj.insert("skuId", elemet.skuId);
        cObj.insert("qty", elemet.qty);
        cObj.insert("price", elemet.ss_fee/elemet.qty);
        cObj.insert("total", "");
        cObj.insert("freight", "");
        cObj.insert("payAmount", "");
        cObj.insert("unitPrice", elemet.ys_fee/elemet.qty);
        cObj.insert("priceAmount", "");
        cObj.insert("buyAmount", "");
        cObj.insert("businessDiscount", "");
        cObj.insert("platformDiscount", "");
        cObj.insert("businessDiscountInfo", "");
        cObj.insert("platformDiscountInfo", "");
        cObj.insert("note", QString::number(elemet.note,'f',2));
        products.insert(i++, cObj);
    }

    QJsonArray pays;
    QJsonObject payObj;
    // 与毛工确认过不包含平台服务费！！！！！！！！！！！！
    // 与王蒙确认自配送的订单配送费算门店收入不在订单总额体现，海鼎会另外开接口
    payObj.insert("total", _Penny2Dollar(orderObject->total_fee-orderObject->send_fee-orderObject->dis_shop_fee));
    payObj.insert("payName", "非码外卖");
    pays.insert(0, payObj);


    rObj.insert("products", products);
    rObj.insert("pays", pays);

    return QJsonDocument(rObj).toJson(QJsonDocument::Compact);
}

QByteArray FmPlugin::_GetFeeData(const OrderObject *orderObject, QString uuid)
{
    double serviceFee;
    if(orderObject->channel=="jdwm")
    {
        serviceFee = _Penny2Dollar((orderObject->product_fee-orderObject->dis_shop_fee)*0.08);
    }else
    {
        serviceFee = _Penny2Dollar(orderObject->service_fee);
    }
    double sendFee;
    sendFee = _Penny2Dollar(orderObject->send_fee);

    double packFee = 0;
        int packTmp = 0;
        for(int i=0; i < orderObject->proList.count(); i++)
        {
           ProductObject *pObj = orderObject->proList.at(i);
           if(!pObj->sub_products.isEmpty())
           {
               foreach(ProductObject *cpObj, pObj->sub_products)
               {
                    packTmp += cpObj->pack_charge;
               }
           }else
           {
                packTmp += pObj->pack_charge;
           }
        }
        packFee = _Penny2Dollar(packTmp);


    QJsonObject rObj;
    rObj.insert("num",orderObject->order_view_id.isEmpty()?orderObject->order_id:orderObject->order_view_id);
    rObj.insert("cls","外卖费用");
    rObj.insert("busType",orderObject->channelName);
    rObj.insert("platform",orderObject->channelName);
    rObj.insert("filDate",QDateTime::fromTime_t(orderObject->create_time).toString("yyyy-MM-ddThh:mm:ss.zzz+0800"));
    rObj.insert("filler","非码外卖");
    rObj.insert("note", QDateTime::currentDateTime().toString("yyyy-MM-ddThh:mm:ss.zzz+0800"));
    rObj.insert("total", serviceFee+sendFee+packFee);
    rObj.insert("customFieldS1", m_storeId);
    rObj.insert("customFieldS2", uuid);
    rObj.insert("customFieldN1",0);
    rObj.insert("customFieldN2",0);

    QJsonArray array;
    QJsonObject cObj0, cObj1, cObj2;
    cObj0.insert("line", 1);
    cObj0.insert("itemName","服务费");
    cObj0.insert("total", serviceFee);
    cObj0.insert("customFieldS1","");
    cObj0.insert("customFieldS2","");
    cObj0.insert("customFieldN1",0);
    cObj0.insert("customFieldN2",0);
    cObj0.insert("note","");
    array.insert(0, cObj0);


    QString sendFeeName;

    if(orderObject->delivery_type == 1)
    {
        sendFeeName = QString("平台配送费");
    }else
    {
        if(!orderObject->delivery_party.compare("自配送"))
        {
            sendFeeName = QString("自配送费");
        }else
        {
            sendFeeName = QString("三方配送费");
        }
    }
    cObj1.insert("line", 2);
    cObj1.insert("itemName", sendFeeName);
    cObj1.insert("total", sendFee);
    cObj1.insert("customFieldS1", "");
    cObj1.insert("customFieldS2", "");
    cObj1.insert("customFieldN1", 0);
    cObj1.insert("customFieldN2", 0);
    cObj1.insert("note","");
    array.insert(1, cObj1);

    cObj2.insert("line", 3);
    cObj2.insert("itemName", "包装费");
    cObj2.insert("total", packFee);
    cObj2.insert("customFieldS1", "");
    cObj2.insert("customFieldS2", "");
    cObj2.insert("customFieldN1", 0);
    cObj2.insert("customFieldN2", 0);
    cObj2.insert("note","");
    array.insert(2, cObj2);

    rObj.insert("details", array);

    return QJsonDocument(rObj).toJson(QJsonDocument::Compact);
}
