#include "pmsOrdersData.h"
#include "QsLog.h"
#include "alertForm.h"
#include <QDateTime>
#include "Control/flowControl.h"
#include "DTools/configManger.h"
#include <QSqlDriver>
//#include <windows.h>


PmsOrdersData::PmsOrdersData() {
    QLOG_INFO()<<"[<<<<---PmsOrdersData:: Structure PMS Orders Table--->>>>]";
}

bool PmsOrdersData::initPmsOrdersData() {
    bool bRet = false;        
    if ( m_sqlDb.connectionName() != "PmsOrdersData" ) {
        m_sqlDb = QSqlDatabase::addDatabase("QMYSQL","PmsOrdersData");   //数据库驱动类型为Mysql
    }

    if ( m_sqlDb.isValid() ) {
        bool supportTransact = m_sqlDb.driver()->hasFeature(QSqlDriver::Transactions);
        QLOG_INFO()<<"[<<<<---PmsOrdersData driver is valid  and  supportTransact: --->>>>]"<< supportTransact;

        m_puginInitUrl = ConfigManger::GetInstance().GetLoginServerUrl();
        m_sqlDbIp = ConfigManger::GetInstance().GetMysqlIpConfig();
        m_sqlDbPassword = ConfigManger::GetInstance().GetMysqlPasswordConfig();
        m_sqlDb.setHostName( m_sqlDbIp.length() ? m_sqlDbIp :"127.0.0.1" ); //连接数据库主机名，这里需要注意（若填的为”127.0.0.1“，出现不能连接，则改为localhost)
        m_sqlDb.setPort(3306);                 //连接数据库端口号，与设置一致
        m_sqlDb.setDatabaseName("pms");     //连接数据库名，与设置一致
        m_sqlDb.setUserName("oms");           //数据库用户名，与设置一致
        m_sqlDb.setPassword(m_sqlDbPassword.length() ? m_sqlDbPassword :"starbucks@oms");

        if(!m_sqlDb.open()) {                                      //打开数据库
            QLOG_ERROR()<<"[<<<<---PmsOrdersData Open Database error:--->>>>]"<<m_sqlDb.lastError().text();
            bRet = false;
        } else {
            QLOG_INFO()<<"[<<<<---PmsOrdersData Test Open database success!:--->>>>]";
            m_sqlDb.close();
            bRet = true;
        }
    } else {
        QLOG_ERROR()<<"[<<<<---PmsOrdersData driver no valid--->>>>]";
        bRet = false;
    }
    return bRet;
}

PmsOrdersData &PmsOrdersData::getInstance() {
    static PmsOrdersData pmsOrdersData;
    return pmsOrdersData;
}

//*  App-MOP[18-销售,19-退货]  KouBei-MOP[29-销售,30-退货]   App-MOD[9-销售,17-退货]  客诉单[12 (无退单)]   Wechat-MOD[27-销售, 28-退货 ]
//*  ELEME[11-销售, 16-退货]   ORS[21-实物-销售(实物无退货),  23-配送费-销售, 24-配送费-退货]    MOP自测[20-销售(无退单) ]  STC[25-未使用]  HM[14-已停用]】
//* 无需转换 ServiceType , 已经被其他字段替代;
int  PmsOrdersData::convertPosServiceTypeId( const OrderObject* orderObj, const int &OrderStatus ) {
    int  tempOrderTypeId  = 0;

    if  ( !orderObj) {
        QLOG_ERROR()<<"[<<<<---PmsOrdersData::convertPosServiceTypeId  orderObj Point is Null --->>>>]";
        return tempOrderTypeId;
    }

    switch ( OrderStatus )
    {
    // sale-mode
    case  OrderObject::NewOrder :
    case OrderObject::Confirmed :
    case OrderObject::Sendout :
    case OrderObject::SimExceptSale :
    case OrderObject::Finished :{
        // 转换成星巴克规定的订单类型;  星巴克的订单类型：1:新订单; 2:预订单; 3:客诉单; 4:MOP自测订单; 5:预约订单; 7:预约单日订单; 8:拼单;
        if(3 == orderObj->getOrderType()) {
            tempOrderTypeId = 12;
        }
        else if ( 7== orderObj->getOrderType() ) {
            tempOrderTypeId = 14;
        }
        // MOD渠道对应的业务逻辑 ;  星巴克-MOD,百度外卖,饿了么APP,美团外卖,星巴克-MOP;
        else if("MOD" == orderObj->channel) {
            // platformSource:平台来源:1 app;2 ele;3 ors;4 WeChat ;5 口碑;
            if ( "4" == orderObj->platformSource ) {
                tempOrderTypeId = 27;
            } else {
                tempOrderTypeId = 9;
            }

        } // WSG-MOD 渠道对应的业务逻辑 ;
        else if("WSG-MOD" == orderObj->channel) { // 兼容渠道名称不统一问题
            // platformSource:平台来源:1 app;2 ele;3 ors;4 WeChat ;5 口碑;
            if ( "4" == orderObj->platformSource ) {
                tempOrderTypeId = 31;
            }

        } // MOP渠道对应的业务逻辑;
        else if("MOP" == orderObj->channel){
            // 区别：口碑-MOP  / App-MOP;
            if ( "5" == orderObj->platformSource ){
                tempOrderTypeId = 29;
            } else {
                tempOrderTypeId = 18;
            }
            //MOP最后判断 是否是 MOP自测订单;
            if(4== orderObj->getOrderType()) {
                tempOrderTypeId = 20;
            }

        }else if("ELE" == orderObj->channel){
            tempOrderTypeId = 11;
        //星巴克-预约订单: 预约实物入机: 销售单订单类型:21; 退货单订单类型: 22;
        //为了配合服务端调整:兼容 预约退货 不区分 预约配送费 与 预约实物；必须重点注意退货时支付方式赋值;
        }else if("ORS" == orderObj->channel && orderObj->appointmentDayFlag ){
            tempOrderTypeId = 21;
        //星巴克-预约订单: 配送费入机: 销售单订单类型:23; 退货单订单类型: 24;
        }else if("ORS" == orderObj->channel && !orderObj->appointmentDayFlag ){
            tempOrderTypeId = 23;
            //预约系统 支付方式: 1:支付宝; 2:微信; 3:银联; 4:SVC卡; 5/7:MOP使用券或星星抵扣 0元支付; 8:IStore订单; 9:银联支付(=3);
        }else{
            tempOrderTypeId = 11;
        }

    };
        break;
     //refund-mode
    case OrderObject::SimExceptRefund :
    case OrderObject::Refunded :{
        // 转换成星巴克规定的订单类型;  星巴克的订单类型：1:新订单; 2:预订单; 3:客诉单; 4:MOP自测订单; 5:预约订单; 7:预约单日订单; 8:拼单;
        if(3 == orderObj->getOrderType()) {
            tempOrderTypeId = 12;
        }
        else if ( 7== orderObj->getOrderType() ) {
            tempOrderTypeId = 15;
        }
        // MOD渠道对应的业务逻辑 ;  星巴克-MOD,百度外卖,饿了么APP,美团外卖,星巴克-MOP;
        else if("MOD" == orderObj->channel) {
            // platformSource:平台来源:1 app;2 ele;3 ors;4 WeChat; 5 口碑;
            if ( "4" == orderObj->platformSource ) {
                tempOrderTypeId = 28;
            } else {
                tempOrderTypeId = 17;
            }

        } // WSG-MOD 渠道对应的业务逻辑 ;
        else if("WSG-MOD" == orderObj->channel) { // 兼容渠道名称不统一问题
            // platformSource:平台来源:1 app;2 ele;3 ors;4 WeChat ;5 口碑;
            if ( "4" == orderObj->platformSource ) {
                tempOrderTypeId = 32;
            }

        } // MOP渠道对应的业务逻辑;
        else if("MOP" == orderObj->channel){
            // 区别：口碑-MOP  / App-MOP;
            if ( "5" == orderObj->platformSource ){
                tempOrderTypeId = 30;
            } else {
                tempOrderTypeId = 19;
            }
            //MOP最后判断 是否是 MOP自测订单;
            if(4== orderObj->getOrderType()) {
                tempOrderTypeId = 20;
            }

        }else if("ELE" == orderObj->channel){
            tempOrderTypeId = 16;
        //星巴克-预约订单: 预约实物入机: 销售单订单类型:21; 退货单订单类型: 22;
        //为了配合服务端调整:兼容 预约退货 不区分 预约配送费 与 预约实物；必须重点注意退货时支付方式赋值;
        }else if("ORS" == orderObj->channel && orderObj->appointmentDayFlag ){
            tempOrderTypeId = 24;
            //预约系统 支付方式: 1:支付宝; 2:微信; 3:银联; 4:SVC卡; 5/7:MOP使用券或星星抵扣 0元支付; 8:IStore订单; 9:银联支付(=3);
        }else{
            tempOrderTypeId = 13;
        }

    };
        break;
    default: return tempOrderTypeId;
    }

    return tempOrderTypeId;

}

bool PmsOrdersData::insertOrderData(OrderObject* orderObj,QString& pmsOrderRef) {
    bool btryLock = m_mutex.tryLock(VALUE_TRYLOCKMEMTIMEOUT);
    bool result = false;
    //数据库原子操作:加锁成功;
    if(btryLock){
        if(!m_sqlDb.open()) {
            QLOG_ERROR()<<"[<<<<---PmsOrdersData::insertOrderData:Open Failed--->>>>]"<<m_sqlDb.lastError().text();
            m_mutex.unlock();
            return false;
        }

        // 开启数据库事务实现原子操作: 保证 orders  order_items order_item_condiments 同时插入成功;
        // m_sqlDb.transaction(); 驱动不支持;
        QSqlQuery query(m_sqlDb);

        if ( !query.exec("START TRANSACTION") ) {
           QLOG_ERROR()<<"[<<<<---PmsOrdersData::insertOrderData: Begin transaction Failed--->>>>]"<<m_sqlDb.lastError().text();
        }

        query.prepare("INSERT INTO orders(guid, order_id, order_status, update_time,order_channel, order_type,order_type_id,take_no, order_total, products_total, "
                      "discount_total, payment_method, invoice_url, invoice_status, third_party_id, third_party_index, package_fee, package_discount, accept_date, secret_signal, "
                      "address_detail, consignee_name ,first_name,last_name,consignee_phone, delivery_price,delivery_discount,delivery_time, order_estimation,make_finish_time,"
                      "is_package, last_pay_time, address_latitude, address_longitude, oms_msrno, consumer_birthday, cancel_reason, confirm_time,customer_id,customer_gender,"
                      "way_bill_id,store_id,store_name,store_address,store_street, pos_id, lang, ext_info, rider_phone, rider_name, "
                      "displateform_fee, make_status, make_source, make_device_id,reserve_type, appointed_time,appointed_remind_template,sub_store_id, "
                      "global_order_type,global_service_type,platform_source,callback_url, member_level, pcs_extend_list ) "
                      "VALUES(?, ?, ?, ?, ?,?, ?, ?, ?, ?, "
                      "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "
                      "?, ?, ?, ?, ?, ?, ?, ?, ?, ?,"
                      "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "
                      "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "
                      "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" );

        query.addBindValue(orderObj->id); // --非码OMS订单号
        query.addBindValue(orderObj->id); // --非码OMS订单号
        query.addBindValue(orderObj->orderStatus); // --订单状态
        QString updateTimeString = QDateTime::fromSecsSinceEpoch(orderObj->updateTime).toString("yyyy-MM-dd hh:mm:ss");
        query.addBindValue(updateTimeString); // --订单更新时间

        QString tempChannel = ("WSG-MOD"==orderObj->channel) ? "MOD" : orderObj->channel;
        tempChannel = ( "WSG-MOP" == tempChannel || "MT-MOP" == tempChannel ) ? "MOP" : tempChannel;
        tempChannel = ( "EC_WECHAT_MOP" == tempChannel ) ? "EC-MOP" : tempChannel;  // EC_WECHAT_MOP: 电商微信MOP 需转换 电商MOP;

        query.addBindValue(tempChannel); // --订单渠道
        query.addBindValue(orderObj->orderType); // --订单类型

        int tempOrderTypeId = convertPosServiceTypeId( orderObj, orderObj->orderStatus);
        query.addBindValue(tempOrderTypeId); // --订单类型ID
        query.addBindValue(orderObj->pickupCode); // --取餐码
        query.addBindValue(orderObj->totalPrice * 0.01); // --订单总额 (单位:分)
        query.addBindValue(orderObj->productPrice * 0.01); // --商品总额 (单位:分)
        query.addBindValue(orderObj->orderDiscount * 0.01); // --整单折扣 (单位:分)
        query.addBindValue(""); // --支付方式
        query.addBindValue(orderObj->invoiceUrl); // --发票连接 插件还没有对OMS接口;????????
        query.addBindValue(""); // --发票状态 插件还没有对OMS接口;????????
        query.addBindValue(orderObj->thirdPartyOrderId); // --第三方订单号 thirdPartyOrderId  thirdPartyBatch:第三方交易流水号
        query.addBindValue(orderObj->orderIndex); // --第三方平台账单序号 /*orderObj->flowId*/ ;
        query.addBindValue(orderObj->packageFee * 0.01); // --打包盒费;
        query.addBindValue(orderObj->packDiscount * 0.01); // --打包盒费折扣;
        query.addBindValue(orderObj->acceptedDate);  //--接单时间; acceptedDate
        query.addBindValue(orderObj->secretSignal); // --暗号
        query.addBindValue(orderObj->addressDetail); // --收货地址
        query.addBindValue(orderObj->consigneeName); // --收货者名称
        query.addBindValue(orderObj->firstName); // --收货者名称
        query.addBindValue(orderObj->lastName); // --收货者名称
        query.addBindValue(orderObj->consigneePhone); // --收货者名称
        query.addBindValue(orderObj->deliveryPrice * 0.01); // --配送费
        query.addBindValue(orderObj->deliveryDiscount * 0.01); // --配送费折扣
        if ( orderObj->deliveryTime.isEmpty() ) {
            orderObj->deliveryTime = QString("1970-01-01 00:00:00");
        }
        query.addBindValue(orderObj->deliveryTime); // --订单预计送达时间
        query.addBindValue(orderObj->estimation); // --订单预计制作时间 estimation;
        if ( orderObj->finishTime.isEmpty() ) {
            orderObj->finishTime = QString("1970-01-01 00:00:00");
        }
        query.addBindValue(orderObj->finishTime); // --订单预计完成时间 makeFinishDate;
        query.addBindValue(orderObj->isPackage); // --订单是否打包;
        query.addBindValue(""); // --最后支付时间 lastPayTime;
        query.addBindValue(""); // --纬度 latitude;
        query.addBindValue(""); // --经度 longitude;
        query.addBindValue(orderObj->msr_no); // --MSR 卡号;
        query.addBindValue(""); // --消费者生日  birthday;
        query.addBindValue(orderObj->cancelReason); // --取消原因  cancelReason;
        if ( orderObj->confirmTime.isEmpty() ) {
            orderObj->confirmTime = QString("1970-01-01 00:00:00");
        }
        query.addBindValue(orderObj->confirmTime); // --确认订单时间 confirmTime;
        query.addBindValue(orderObj->customerId); // --消费者ID;
        QString temp_customerSex = "";
        if ( !orderObj->customerSex.compare(QString::fromLocal8Bit(FM_MALE)) || !orderObj->customerSex.compare(QString("Male")) ) {
            temp_customerSex = "Male";
        } else if ( !orderObj->customerSex.compare(QString::fromLocal8Bit(FM_FEMALE)) || !orderObj->customerSex.compare(QString("Female")) ){
            temp_customerSex = "Female";
        } else if ( orderObj->customerSex.length() ) {
            temp_customerSex = orderObj->customerSex;
        } else{ temp_customerSex = ""; }
        query.addBindValue(temp_customerSex); // --消费者性别;
        query.addBindValue(orderObj->waybillId); // --运单号;
        query.addBindValue(orderObj->storeId); // --门店号;
        query.addBindValue(orderObj->storeName); // --门店名称;
        query.addBindValue(orderObj->storeAddress); // --门店地址;
        query.addBindValue(""); // --门店街道 ?????? 对接oms;
        query.addBindValue(""); // --插件地址;
        query.addBindValue(orderObj->lang); // --语言;
        query.addBindValue(orderObj->memo); // --订单备注 扩展信息
        query.addBindValue(orderObj->riderPhone); // --配送者电话
        query.addBindValue(orderObj->riderName); // -配送者名称
        query.addBindValue( abs(orderObj->disPlateformFee * 0.01)); // --平台优惠
        query.addBindValue(orderObj->makeStatus); // --制作状态
        query.addBindValue(orderObj->makeSource); // --提供制作状态来源
        query.addBindValue(orderObj->makeDeviceId); // --提供制作状态设备ID

        // 与 oms协定此块业务出现 歧异 故在此处转换;  【与PMS协定: businessType -> 10: 预约;  20: WSG-用星说:  21: WSG-美好咖啡; 30: 拼团】
        int tempBusinessType = orderObj->businessType.toInt();
        if ( ( "WSG-MOD" == orderObj->channel || "WSG-MOP" == orderObj->channel ) && "4" == orderObj->platformSource) {
            if ( 1 == orderObj->isGiftitForward )
                tempBusinessType = 21;
            else
                tempBusinessType = 20;
        }
        if ( 7 == orderObj->orderType || 11 == orderObj->orderType )
            tempBusinessType = 10;
        else if (8 == orderObj->orderType) {
            tempBusinessType = 30;
        }

        query.addBindValue( tempBusinessType ); // --订单业务类型
        if ( orderObj->expectDate.isEmpty() ) {
            orderObj->expectDate = QString("1970-01-01 00:00:00");
        }
        query.addBindValue(orderObj->expectDate);  // --订单预约时间
        query.addBindValue( QString::number(orderObj->inAdvanceTakemeal) + ";" + orderObj->reserveMakeTime ); // --订单预约提醒模板
        query.addBindValue(orderObj->subStoreId); // --母子门店的子门店编号;
        query.addBindValue( orderObj->globalOrderType ); // --全链路订单类型
        query.addBindValue( orderObj->globalServiceType);  // --全链路服务类型
        query.addBindValue( orderObj->platformSource);  // --平台来源枚举值
        // Origin: orderObj->callBackUrl : https://o2ofulfillment.stg.starbucks.net/fulfillment/pos
        // Dest:   orderObj->pcsCallbackUrl : https://o2ofulfillment.stg.starbucks.net/fulfillment/pcs/order/pms/callback
        QString tempPcsCallbackUrl = "";
        if ( orderObj->callBackUrl.length()  ) { // callBackUrl 如果是空值 还是需要 插件使用 目前地址进行拼接;
            tempPcsCallbackUrl = orderObj->callBackUrl.mid(0, orderObj->callBackUrl.length() - 3) + "pcs/order/pms/callback";
        } else {
            tempPcsCallbackUrl =  m_puginInitUrl.mid(0, m_puginInitUrl.length() - 4) + "pcs/order/pms/callback";
        }
        query.addBindValue( tempPcsCallbackUrl );  // --平台来源枚举值  //PCS系统拼接的 callback_url
        query.addBindValue( orderObj->memberLevel );  // 会员等级;
        query.addBindValue( orderObj->posExtendListString ); // POS/PCS 扩展属性列表;
        /*
        QStringList tempSlist;
        QString tempPcsExtendList;
        if ( orderObj->posExtendList.isEmpty() ) {
            tempPcsExtendList = QString("");
        } else {
            foreach (PosExtendObject* posExtend, orderObj->posExtendList) {
                tempSlist.append( posExtend->objectToString() );
            }
            tempPcsExtendList = QString("[").toUtf8() + tempSlist.join(",") + QString("]").toUtf8();
        }
        */

        if(!query.exec()) {
            QLOG_ERROR()<<"[<<<<---PmsOrdersData::insertOrderData:Insert Order Error--->>>>]"<<query.lastError().text()
                       <<QString::number(query.lastError().type());
            result = false;
            QLOG_INFO()<<QString("INSERT INTO orders(guid, order_id, order_status, update_time, "
                                 "order_channel, order_type,order_type_id,take_no, order_total, products_total, discount_total, payment_method, "
                                 "invoice_url, invoice_status, third_party_id, third_party_index, package_fee, package_discount, "
                                 "accept_date, secret_signal, address_detail, consignee_name ,first_name,last_name,consignee_phone, "
                                 "delivery_price,delivery_discount,delivery_time, order_estimation,make_finish_time,is_package, "
                                 "last_pay_time, address_latitude, address_longitude, oms_msrno, consumer_birthday, cancel_reason, "
                                 "confirm_time,customer_id,customer_gender,way_bill_id,store_id,store_name,store_address,store_street, "
                                 "pos_id, lang, ext_info, rider_phone, rider_name, displateform_fee, make_status, make_source, make_device_id,"
                                 "reserve_type, appointed_time,appointed_remind_template,sub_store_id,global_order_type,global_service_type,platform_source,"
                                 "callback_url, member_level, pcs_extend_list  ) "
                                 "VALUES(%1, %2, %3, %4, %5, %6, %7, %8, %9, %10, %11, %12, %13, %14, %15, %16, %17, %18, %19, %20, "
                                 "%21, %22, %23, %24, %25, %26, %27, %28, %29, %30, %31, %32, %33, %34, %35, %36, %37, %38, %39, %40,"
                                 "%41, %42, %43, %44, %45, %46, %47, %48, %49, %50, %51, %52, %53, %54,%55,%56,%57,%58,%59,%60,%61,"
                                 "%62,%63,%64)")
                         .arg(orderObj->id).arg(orderObj->id).arg(orderObj->orderStatus).arg(updateTimeString).arg( tempChannel )
                         .arg(orderObj->orderType).arg(tempOrderTypeId)
                         .arg(orderObj->pickupCode).arg(orderObj->totalPrice * 0.01).arg(orderObj->productPrice * 0.01).arg(orderObj->orderDiscount * 0.01)
                         .arg("").arg(orderObj->invoiceUrl).arg("").arg(orderObj->thirdPartyOrderId).arg(orderObj->orderIndex)
                         .arg(orderObj->packageFee * 0.01).arg(orderObj->packDiscount * 0.01).arg(orderObj->acceptedDate).arg(orderObj->secretSignal)
                         .arg(orderObj->addressDetail).arg(orderObj->consigneeName).arg(orderObj->firstName).arg(orderObj->lastName)
                         .arg(orderObj->consigneePhone).arg(orderObj->deliveryPrice * 0.01).arg(orderObj->deliveryDiscount * 0.01)
                         .arg(orderObj->deliveryTime)
                         .arg(orderObj->estimation).arg(orderObj->finishTime).arg(orderObj->isPackage).arg("").arg("").arg("").arg(orderObj->msr_no).arg("").arg(orderObj->cancelReason)
                         .arg(orderObj->confirmTime).arg(orderObj->customerId).arg("Female").arg(orderObj->waybillId).arg(orderObj->storeId)
                         .arg(orderObj->storeName).arg(orderObj->storeAddress).arg("")
                         .arg("").arg(orderObj->lang).arg(orderObj->memo).arg(orderObj->riderPhone).arg(orderObj->riderName)
                         .arg(orderObj->disPlateformFee * 0.01).arg(orderObj->makeStatus).arg(orderObj->makeSource).arg(orderObj->makeDeviceId)
                         .arg( tempBusinessType ).arg(orderObj->expectDate).arg( QString::number(orderObj->inAdvanceTakemeal) + ";" + orderObj->reserveMakeTime )
                         .arg(orderObj->subStoreId).arg(orderObj->globalOrderType).arg(orderObj->globalServiceType).arg(orderObj->platformSource)
                         .arg( tempPcsCallbackUrl ).arg( orderObj->memberLevel ).arg( orderObj->posExtendListString );

        } else {
            QLOG_INFO()<<QString("[<<<<---PmsOrdersData::insertOrderData:Insert OrderId %1 Into PMS Order Success--->>>>]").arg(orderObj->id);
            pmsOrderRef = query.lastInsertId().toString();
            QString ProInIdRef;

            if (  ( "WSG-MOD" == orderObj->channel || "WSG-MOP" == orderObj->channel ) && "4" == orderObj->platformSource ) {
                result = insertConponData(orderObj->coupList, orderObj->id, ProInIdRef);
            }else {
                result = insertProductData(orderObj->proList, orderObj->id, ProInIdRef);
            }
            QLOG_INFO()<<QString("[<<<<---PmsOrdersData::insertOrderData  OrderId %1 insertProductData | insertConponData :--->>>>]").arg(orderObj->id)<<result;
        }

        // 结束数据库事务操作 保证 orders  order_items order_item_condiments 同时插入成功;
        // Sleep(10*1000);   // test  sqldb transaction
        /*  // m_sqlDb.commit()  and m_sqlDb.rollback() 都是不支持的;
        if ( !m_sqlDb.commit() ) {
            bool rollbackRet = m_sqlDb.rollback();
            QLOG_ERROR()<<QString("[<<<<---PmsOrdersData::insertOrderData  OrderId %1 commit() failed and rollback:%2 --->>>>]").arg(orderObj->id).arg(rollbackRet?1:0);
        }
        */
        if ( !query.exec( "COMMIT" ) ) {
            QLOG_ERROR()<<"[<<<<---PmsOrdersData::insertOrderData: Begin Commit Failed--->>>>]"<<m_sqlDb.lastError().text();

            if ( !query.exec( "ROLLBACK" ) ) {
                QLOG_ERROR()<<"[<<<<---PmsOrdersData::insertOrderData: Begin Rollback Failed--->>>>]"<<m_sqlDb.lastError().text();
            }
        }

        m_sqlDb.close();
        m_mutex.unlock();
    //数据库原子操作:加锁失败;
    } else {
        QLOG_ERROR()<<QString("[<<<<---PmsOrdersData::insertOrderData: Try Lock Error OrderId:%1--->>>>]").arg(orderObj->id);
    }
    return result;
}

bool PmsOrdersData::deleteOrderData(OrderObject* orderObj) {
    bool btryLock = m_mutex.tryLock(VALUE_TRYLOCKMEMTIMEOUT);
    bool delOrderRet = false;
    //数据库原子操作:加锁成功;
    if(btryLock){
        if(!m_sqlDb.open()) {
            QLOG_ERROR()<<"[<<<<---PmsOrdersData::deleteOrderData:Open Failed--->>>>]"<<m_sqlDb.lastError().text();
            m_mutex.unlock();
            return false;
        }
        QSqlQuery query(m_sqlDb);
        query.prepare(QString("delete from orders where order_status=%1 and order_id='%2'")
                      .arg(QString::number(orderObj->orderStatus)).arg(orderObj->id));
        if(!query.exec()) {
            QLOG_ERROR()<<query.lastError().text()<<"[<<<<---PmsOrdersData::deleteOrderData Order Failed orderId:--->>>>]"<<orderObj->id;
            delOrderRet= false;
        } else {
            QLOG_INFO()<<QString("[<<<<---PmsOrdersData::deleteOrderData OrderId %1 success--->>>>]").arg(orderObj->id);
            delOrderRet = deleteProductData(orderObj);
            if(delOrderRet) {
                QLOG_INFO()<<QString("[<<<<---PmsOrdersData::deleteOrderData OrderId %1 delete ProductData Success--->>>>]").arg(orderObj->id);
            } else {
                QLOG_INFO()<<QString("[<<<<---PmsOrdersData::deleteOrderData OrderId %1 delete ProductData Failed--->>>>]").arg(orderObj->id);
            }
        }
        //关闭数据库连接;
        m_sqlDb.close();
        m_mutex.unlock();

    //数据库原子操作:加锁失败;
    } else {
        QLOG_ERROR()<<QString("[<<<<---PmsOrdersData::deleteOrderData: Try Lock Error OrderId:%1--->>>>]").arg(orderObj->id);
    }
    return delOrderRet;
}


//此函数将会在 insertOrderData 函数中调用;顾无需加锁 否则 会导致死锁;
bool PmsOrdersData::insertProductData(const QList<dishesObject*> proList, const QString& OrderId,  QString& ProInIdRef) {
    bool insertProRet = false;
    bool insertSubProRet = false;
    int  insertProSucNum = 0;
    int availProNum = 0;  // Skip Some Invalid Products;
    QString  MainProOptions = "" ;

    if ( proList.count() ) {
        foreach(dishesObject* dishesObjectTemp, proList){
            QString tempCodeLeftHead = dishesObjectTemp->code.left(1);
            if ( dishesObjectTemp->code.contains("Default",Qt::CaseInsensitive) || (tempCodeLeftHead<QString('0')||tempCodeLeftHead>QString('9')) || !dishesObjectTemp->qty ){
                continue;
            }
            // 跳过--外送包装费组装的 poskey;
            if ( dishesObjectTemp->code == "6000201" ) {
                continue;
            }

            ++availProNum;

            QSqlQuery query(m_sqlDb);
            query.prepare("INSERT INTO order_items(order_id,product_id, product_code, product_name, en_product_name, product_qty, item_total,"
                          "spec_id, spec_name, en_spec_name, price, promotion_name, promotion_price, promotion_qty, promotion_sku,"
                          "package_price, default_image, prod_owner, sku_id ) "
                          "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            query.addBindValue(OrderId); // --非码OMS订单号
            query.addBindValue(dishesObjectTemp->id); // --主商品ID
            query.addBindValue(dishesObjectTemp->code); // --主商品code
            query.addBindValue(dishesObjectTemp->name); // --主商品名称
            query.addBindValue(dishesObjectTemp->enProductName); // --主商品英文名称
            query.addBindValue(dishesObjectTemp->qty); // --主商品数量
            query.addBindValue(0); // --主商品应收价格 dishesObjectTemp->totalQuantityPrice ????????
            query.addBindValue(dishesObjectTemp->specId); // --主商品规格ID
            query.addBindValue(dishesObjectTemp->specName); // --主商品规格名称
            query.addBindValue(dishesObjectTemp->enSpecificationName); // --主商品规格英文名称
            query.addBindValue(dishesObjectTemp->price  * 0.01); // --主商品价格
            query.addBindValue(dishesObjectTemp->promotionName); // --主商品优惠名
            query.addBindValue(dishesObjectTemp->promotionPrice  * 0.01); // --主商品优惠金额
            query.addBindValue(dishesObjectTemp->promotionQty); // --主商品优惠数量
            query.addBindValue(dishesObjectTemp->promotionSku); // --主商品优惠sku
            query.addBindValue(dishesObjectTemp->packagePrice  * 0.01); // --主商品打包价格
            query.addBindValue(dishesObjectTemp->defaultImage); // --主商品默认图片
            // (默认主商品的拼单人 拆字)  拆口令分配的字  |#|   拼单人昵称     例："世" |#| "Kernel(邹伍洋)"     分割符为:  "|#|"
            query.addBindValue(dishesObjectTemp->userName + ( dishesObjectTemp->wechatName.length() ? "|#|" + dishesObjectTemp->wechatName : "" ) );  // 拆字 + 微信昵称
            query.addBindValue(dishesObjectTemp->supplyChainSku); // --EC-MOP主商品 SKU Code;

            if(!query.exec()) {
                QLOG_ERROR()<<QString("[<<<<---PmsOrdersData::insertProductData:Insert OrderId %1 Product code:%2 Failed --->>>>]")
                              .arg(OrderId).arg(dishesObjectTemp->code)
                           <<query.lastError().text()<<QString::number(query.lastError().type());
                QLOG_ERROR()<<QString("INSERT INTO order_items(order_id,order_item_id, product_id, product_name, en_product_name, product_qty,"
                                      " item_total,spec_id, spec_name, en_spec_name, price, promotion_name, promotion_price, promotion_qty,"
                                      " promotion_sku, package_price, default_image, prod_owner, sku_id) "
                                      "VALUES(%1, %2, %3, %4, %5, %6, %7, %8, %9, %10, %11, %12, %13, %14, %15, %16, %17, %18, %19)")
                              .arg(OrderId).arg(dishesObjectTemp->id).arg(dishesObjectTemp->code).arg(dishesObjectTemp->name)
                              .arg("").arg(dishesObjectTemp->qty).arg(0).arg(dishesObjectTemp->specId).arg(dishesObjectTemp->specName)
                              .arg("").arg(dishesObjectTemp->price * 0.01).arg(dishesObjectTemp->promotionName).arg(dishesObjectTemp->promotionPrice * 0.01)
                              .arg(dishesObjectTemp->promotionQty).arg(dishesObjectTemp->promotionSku).arg(dishesObjectTemp->packagePrice * 0.01).arg("")
                              .arg(dishesObjectTemp->userName + ( dishesObjectTemp->wechatName.length() ? "|#|" + dishesObjectTemp->wechatName : "" ) )
                              .arg(dishesObjectTemp->supplyChainSku);
            } else {
                ProInIdRef = query.lastInsertId().toString();
                QLOG_INFO()<<QString("[<<<<---PmsOrdersData::insertOrderProductData:Insert OrderId %1 Product Success code:%2 increaseId:%3--->>>>]")
                             .arg(OrderId).arg(dishesObjectTemp->code).arg(ProInIdRef);
                QString SubProInIdRef;
                //插入配料商品数据+Special Hot / Cold;
                MainProOptions = dishesObjectTemp->options;
                if( dishesObjectTemp->sub_products.count() || !MainProOptions.isEmpty() ) {
                    insertSubProRet = insertSubProductData(dishesObjectTemp->sub_products,MainProOptions, ProInIdRef, SubProInIdRef);
                    if(insertSubProRet){
                        insertProSucNum++;
                    } else{  // insertSubProductData occurred Error And Faild Need Return False Immediately;
                        insertProRet = false;
                        QLOG_ERROR()<<QString("[<<<<---PmsOrdersData::insertSubProductData: Insert MainProduct code:%1's SubProduct Failed --->>>>]").arg(dishesObjectTemp->code);
                        return insertProRet;
                    }
                } else {
                    insertProSucNum++;
                }
            }

        }
    }else{
        QLOG_INFO()<<QString("[<<<<---PmsOrdersData::insertProductData OrderId %1 Has No Products --->>>>]").arg(OrderId);
    }

    if( insertProSucNum == availProNum ){
        insertProRet = true;
    }

    return insertProRet;
}



//此函数将会在 insertOrderData 函数中调用;顾无需加锁 否则 会导致死锁;
bool PmsOrdersData::insertConponData(const QList<CouponsObject*> coupList, const QString& OrderId,  QString& ProInIdRef) {
    bool insertCoupRet = false;
    bool insertCoupSubProRet = false;
    Q_UNUSED(insertCoupSubProRet); // Waitting Start
    int  insertCoupSucNum = 0;
    int availCoupNum = 0;  // Skip Some Invalid Coupon Products;

    if ( coupList.count() ) {
        foreach(CouponsObject* coupObjTemp, coupList) {

            if ( !coupObjTemp->skus.count() ) {
                QLOG_ERROR()<<QString("[<<<<---PmsOrdersData::insertConponData:  Coupon Code:%1 Sku List Is Empty --->>>>]").arg(coupObjTemp->code);
                if ( insertCoupSucNum ) {
                    QSqlQuery query(m_sqlDb);
                    query.prepare("delete from order_items where order_id = '"+ OrderId +"' ");
                    if ( !query.exec() ) {
                        QLOG_ERROR()<<QString("[<<<<---PmsOrdersData::insertConponData:  Clear Order Coupon Data Failed  orderId:%1 --->>>>]").arg(OrderId);
                    }else{
                        QLOG_INFO()<<QString("[<<<<---PmsOrdersData::insertConponData:  Clear Order Coupon Data Sucessed  orderId:%1 --->>>>]").arg(OrderId);
                    }
                }
                return false;
            }
            ++availCoupNum;

            QSqlQuery query(m_sqlDb);
            query.prepare("INSERT INTO order_items(order_id,product_id, product_code, product_name, en_product_name, product_qty, item_total,"
                          "spec_id, spec_name, en_spec_name, price, promotion_name, promotion_price, promotion_qty, promotion_sku,"
                          "package_price, default_image, coupon_show_giver, coupon_giver, coupon_wishes, nick_name) "
                          "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            query.addBindValue(OrderId); // --非码OMS订单号
            query.addBindValue(""); // --主商品ID
            query.addBindValue(coupObjTemp->skus[0]->code); // --券主商品code
            query.addBindValue(coupObjTemp->skus[0]->name); // --券主商品名称
            query.addBindValue(""); // --券主商品英文名称
            query.addBindValue(coupObjTemp->skus[0]->qty); // --券主商品数量
            query.addBindValue(coupObjTemp->skus[0]->price); // --券主商品应收价格
            query.addBindValue(""); // --券主商品规格ID
            query.addBindValue(""); // --券主商品规格名称
            query.addBindValue(""); // --券主商品规格英文名称
            query.addBindValue(coupObjTemp->skus[0]->price* 0.01); // --券主商品价格
            query.addBindValue(coupObjTemp->discountName); // --券主商品优惠名
            query.addBindValue(coupObjTemp->consumeDiscountAmount  * 0.01); // --券主商品优惠金额
            query.addBindValue(1); // --券主商品优惠数量
            query.addBindValue(coupObjTemp->discount); // --券主商品优惠sku
            query.addBindValue(0); // --券主商品打包价格
            query.addBindValue(""); // --券主商品默认图片
            query.addBindValue(coupObjTemp->isShowGiver);  // --券主商品-是否显示赠送者;
            query.addBindValue(coupObjTemp->giverName);  // --券主商品-赠送者名;
            query.addBindValue(coupObjTemp->blessingWords);  // --券主商品-赠送祝福词;
            query.addBindValue(coupObjTemp->skus[0]->nickname);   // --券主商品-商品昵称

            if(!query.exec()) {
                QLOG_ERROR()<<QString("[<<<<---PmsOrdersData::insertConponData:Insert OrderId %1 Product code:%2 Failed --->>>>]")
                              .arg(OrderId).arg(coupObjTemp->skus[0]->code)
                           <<query.lastError().text()<<QString::number(query.lastError().type());
                QLOG_ERROR()<<QString("INSERT INTO order_items(order_id,order_item_id, product_id, product_name, en_product_name, product_qty,"
                                      " item_total,spec_id, spec_name, en_spec_name, price, promotion_name, promotion_price, promotion_qty,"
                                      " promotion_sku, package_price, default_image, coupon_show_giver, coupon_giver, coupon_wishes, nick_name) "
                                      "VALUES(%1, %2, %3, %4, %5, %6, %7, %8, %9, %10, %11, %12, %13, %14, %15, %16, %17, %18, %19, %20, %21)")
                              .arg(OrderId).arg("").arg(coupObjTemp->skus[0]->code).arg(coupObjTemp->skus[0]->name)
                              .arg("").arg(coupObjTemp->skus[0]->qty).arg(coupObjTemp->skus[0]->price).arg("").arg("")
                              .arg("").arg(coupObjTemp->skus[0]->price * 0.01).arg(coupObjTemp->discountName).arg(coupObjTemp->consumeDiscountAmount * 0.01)
                              .arg(1).arg(coupObjTemp->discount).arg(0).arg("").arg(coupObjTemp->isShowGiver).arg(coupObjTemp->giverName)
                        .arg(coupObjTemp->blessingWords).arg(coupObjTemp->skus[0]->nickname);
            } else {
                ProInIdRef = query.lastInsertId().toString();
                QLOG_INFO()<<QString("[<<<<---PmsOrdersData::insertConponData:Insert OrderId %1 Conpon Success code:%2 increaseId:%3--->>>>]")
                             .arg(OrderId).arg(coupObjTemp->skus[0]->code).arg(ProInIdRef);

                insertCoupSucNum++;
                //插入券商品列表 客制化数据;
                /*
                QString SubProInIdRef;
                if( coupObjTemp->skus.count() ) {
                    insertCoupSubProRet = insertCounpSubProData(coupObjTemp->skus,"", ProInIdRef, SubProInIdRef);
                    if(insertCoupProRet){
                        insertCoupSucNum++;
                    } else{  // insertSubProductData occurred Error And Faild Need Return False Immediately;
                        insertCoupRet = false;
                        QLOG_ERROR()<<QString("[<<<<---PmsOrdersData::insertSubProductData: Insert Coupon Product code:%1's SubProduct Failed --->>>>]").arg(dishesObjectTemp->code);
                        return insertCoupRet;
                    }
                } else {
                    insertCoupSucNum++;
                }
                */
            }

        }

    }else{
        QLOG_INFO()<<QString("[<<<<---PmsOrdersData::insertConponData OrderId %1 Has No Coupons --->>>>]").arg(OrderId);
    }

    if( insertCoupSucNum && insertCoupSucNum == availCoupNum ){
        insertCoupRet = true;
    }

    return insertCoupRet;
}


//此函数将会在 deleteOrderData 函数中调用;顾无需加锁 否则 会导致死锁;
bool PmsOrdersData::deleteProductData(OrderObject* orderObj) {
    bool delResultRet = false;
    bool delProductFailRet = false;
    bool delSubProductFailRet = false;
    int id = 0;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("select id from order_items where order_id='%1'").arg(orderObj->id));
    if(!query.exec()) {
        QLOG_ERROR()<<query.lastError().text()<<"[<<<<---PmsOrdersData::deleteProductData"
                                                " select id from order_items Failed orderId:--->>>>]"<<orderObj->id;
        delSubProductFailRet = true;
        delProductFailRet = true;
    } else {
        //循环逐个删除子商品;
        while(query.next()) {
            id = query.value(0).toInt();
            query.prepare(QString("delete from order_item_condiments where item_id=%1").arg(id) );
            if(!query.exec()) {
                QLOG_ERROR()<<query.lastError().text()<<QString("[<<<<---PmsOrdersData::deleteProductData"
                                                        " delete from order_item_condiments where item_id=%1 Failed--->>>>]").arg(QString::number(id));
                delSubProductFailRet = true;
            }
        }
        //批量删除主商品;
        query.prepare(QString("delete from order_items where order_id='%1'").arg(orderObj->id) );
        if(!query.exec()) {
            QLOG_ERROR()<<query.lastError().text()<<QString("[<<<<---PmsOrdersData::deleteProductData"
                                                    " delete from order_items where order_id='%1' Failed--->>>>]").arg(orderObj->id);
            delProductFailRet = true;
        }
    }
    QLOG_INFO()<<QString("[<<<<---PmsOrdersData::deleteProductData orderId:%1 delProductFailRet: delSubProductFailRet:--->>>>]")
                 .arg(orderObj->id)<<delProductFailRet<<" "<<delSubProductFailRet;
    if( delProductFailRet || delSubProductFailRet ) {
        delResultRet = false;
    } else {
        delResultRet = true;
    }
    return delResultRet;
}

//此函数将会在 insertProductData 函数中调用;顾无需加锁 否则 会导致死锁;
bool PmsOrdersData::insertSubProductData(const QList<dishesObject*> sub_products, const QString& MainProOptions ,const QString& ProInIdRef, QString& SubProInIdRef) {
    bool insertSubProRet = false;
    int  insertSubProSucNum = 0;
    int availSubProNum = 0;  // Skip Some Invalid Sub Products;

    if(sub_products.count()) {
        foreach(dishesObject* subDishesObjectTemp, sub_products){

            QString tempSubCodeLeftHead = subDishesObjectTemp->code.left(1);
            if ( subDishesObjectTemp->code.contains("Default",Qt::CaseInsensitive) || (tempSubCodeLeftHead<QString('0') || tempSubCodeLeftHead>QString('9')) || !subDishesObjectTemp->qty ){
                continue;
            }

            ++availSubProNum;

            QSqlQuery query(m_sqlDb);
            query.prepare("INSERT INTO order_item_condiments(item_id,condiment_id, condiment_code, condiment_name, en_condiment_name,"
                          " price, condimen_total, sequence, qty ) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)");
            query.addBindValue(ProInIdRef.toInt()); // --主商品自增编号
            query.addBindValue(subDishesObjectTemp->id); // --子商品ID
            query.addBindValue(subDishesObjectTemp->code); // --子商品code
            query.addBindValue(subDishesObjectTemp->name); // --子商品名称
            query.addBindValue(subDishesObjectTemp->enProductName); // --子商品英文名称
            query.addBindValue(subDishesObjectTemp->price * 0.01); // --子商品价格
            query.addBindValue(0); // --子商品应收价格 dishesObjectTemp->totalQuantityPrice   ????????
            query.addBindValue(subDishesObjectTemp->sequence); // --子商品顺序
            query.addBindValue(subDishesObjectTemp->qty); // --子商品数量
            if(!query.exec()) {
                QLOG_ERROR()<<QString("[<<<<---PmsOrdersData::insertSubProductData:Insert ProInIdRef:%1  subProduct code:%2 Failed --->>>>]")
                              .arg(ProInIdRef).arg(subDishesObjectTemp->code)
                           <<query.lastError().text()<<QString::number(query.lastError().type());
                QLOG_ERROR()<<QString("INSERT INTO order_item_condiments(item_id,condiment_id, condiment_code, condiment_name, en_condiment_name,"
                                      " price, condimen_total, sequence, qty ) "
                                      "VALUES(%1, %2, %3, %4, %5, %6, %7, %8, %9 )")
                              .arg(ProInIdRef.toInt()).arg(subDishesObjectTemp->id).arg(subDishesObjectTemp->code).arg(subDishesObjectTemp->name)
                              .arg(subDishesObjectTemp->enProductName).arg(subDishesObjectTemp->price * 0.01).arg(0).arg(subDishesObjectTemp->sequence).arg(subDishesObjectTemp->qty);
            } else {
                SubProInIdRef = query.lastInsertId().toString();
                QLOG_INFO()<<QString("[<<<<---PmsOrdersData::insertSubProductData:Insert ProInIdRef:%1 subProduct Success code:%2 SubProInIdRef:%3"
                                     " increaseId:%4--->>>>]")
                             .arg(ProInIdRef).arg(subDishesObjectTemp->code).arg(SubProInIdRef).arg( query.lastInsertId().toString() );
                insertSubProSucNum++;
            }
        }
    } else {
        QLOG_INFO()<<QString("[<<<<---PmsOrdersData::insertSubProductData ProInIdRef:%1 Has No subProducts--->>>>]").arg(ProInIdRef);
    }

    //Special Insert MainProOptions;
    if( !MainProOptions.isEmpty() ) {
        ++availSubProNum;
        QSqlQuery query(m_sqlDb);
        query.prepare("INSERT INTO order_item_condiments(item_id, condiment_code , price, condimen_total , qty ) VALUES(?, ?, ?, ?, ?)");
        query.addBindValue(ProInIdRef.toInt()); // --主商品自增编号
        query.addBindValue(MainProOptions); // --子商品code
        query.addBindValue(0); // --子商品价格
        query.addBindValue(0); // --子商品应收价格 dishesObjectTemp->totalQuantityPrice   ????????
        query.addBindValue(1); // --子商品数量
        if(!query.exec()) {
            QLOG_ERROR()<<QString("[<<<<---PmsOrdersData::insertSubProductData:Insert ProInIdRef:%1  MainProOptions code:%2 Failed --->>>>]")
                          .arg(ProInIdRef).arg(MainProOptions)
                       <<query.lastError().text()<<QString::number(query.lastError().type());
            QLOG_ERROR()<<QString("INSERT INTO order_item_condiments(item_id, condiment_code , price, condimen_total , qty ) VALUES(%1, %2, %3, %4, %5)")
                          .arg(ProInIdRef.toInt()).arg(MainProOptions).arg(0).arg(0).arg(1);
        } else {
            SubProInIdRef = query.lastInsertId().toString();
            QLOG_INFO()<<QString("[<<<<---PmsOrdersData::insertSubProductData:Insert ProInIdRef:%1 MainProOptions Success code:%2 SubProInIdRef:%3"
                                 " increaseId:%4--->>>>]")
                         .arg(ProInIdRef).arg(MainProOptions).arg(SubProInIdRef).arg( query.lastInsertId().toString() );
            insertSubProSucNum++;
        }
    }


    if(insertSubProSucNum == availSubProNum ){
        insertSubProRet = true;
    }
    return insertSubProRet;
}

//更新订单状态:需加锁;
bool PmsOrdersData::updateOrderStatus(OrderObject* orderObj, const int &OrderStatus , const QString &makeStatus ) {

    if  ( !orderObj) {
        QLOG_ERROR()<<"[<<<<---PmsOrdersData::updateOrderStatus  orderObj Point is Null --->>>>]";
        return false;
    }

    bool btryLock = m_mutex.tryLock(VALUE_TRYLOCKMEMTIMEOUT);
    bool result = false;

    //数据库原子操作:加锁成功;
    if(btryLock){

        if(!m_sqlDb.open()) {
            QLOG_ERROR()<<"[<<<<---PmsOrdersData::updateOrderStatus:Open Failed--->>>>]"<<m_sqlDb.lastError().text();
            m_mutex.unlock();
            return false;
        }

        QSqlQuery query(m_sqlDb);
        // 需要对应转换并更新: order_type_id;
        int  tempOrderTypeId  = convertPosServiceTypeId( orderObj, orderObj->orderStatus);

        // 预约时间 & 街送小票时间 & 车牌号 & 隐私号  PCS 使用不到, 故没有进行更新.
        query.prepare( QString("update orders set order_status=%1,order_type_id=%2, global_service_type=%3,  global_order_type=%4, make_status='%5',"
                              " make_source='%6', make_device_id='%7', appointed_remind_template ='%8', appointed_time ='%9'   where order_id='%10'")
                      .arg( QString::number(OrderStatus) ).arg( QString::number(tempOrderTypeId) ).arg( QString::number(orderObj->globalServiceType) )
                      .arg( QString::number(orderObj->globalOrderType) ).arg( makeStatus ).arg( orderObj->makeSource ).arg( orderObj->makeDeviceId )
                      .arg( QString::number(orderObj->inAdvanceTakemeal) +';'+ orderObj->reserveMakeTime ).arg( orderObj->expectDate ).arg( orderObj->id ) );

        if(!query.exec()) {
            QLOG_ERROR()<<query.lastError().text()<<"[<<<<---PmsOrdersData::update Order Status Failed--->>>>]";
            result= false;

        } else {
            QLOG_INFO()<<QString("[<<<<---PmsOrdersData::Update OrderId %1 OrderStatus success--->>>>]").arg(orderObj->id);
            result = true;
        }

        m_sqlDb.close();
        m_mutex.unlock();

    //数据库原子操作:加锁失败;
    } else {
        QLOG_ERROR()<<QString("[<<<<---PmsOrdersData::updateOrderStatus: Try Lock Error OrderId:%1--->>>>]").arg(orderObj->id);
    }
    return result;
}

//查询无需加锁;
bool PmsOrdersData::isOrderAndStatusExist(const QString& orderId, const int &OrderStatus, const QString& makeStatus, bool& pmsMakeStatusIsExistRet, int& arriveAheadFlag) {
    bool result = false;
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---PmsOrdersData::isOrderAndStatusExist:Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("select order_id, make_status, appointed_remind_template  from orders where order_id='%1' and order_status='%2' ").arg(orderId).arg(OrderStatus));
    if(!query.exec()) {
        QLOG_ERROR()<<"[<<<<---PmsOrdersData::isOrderAndStatusExist: isOrderAndStatusExist Selcet Failed--->>>>]"<<orderId<<query.lastError().text();
        return false;
    }
    if(query.first()) {
        result= true;

        if (makeStatus !=query.value(1).toString()) {
            pmsMakeStatusIsExistRet = false;
        }
        QString appointedTemplate = query.value(2).toString();
        if ( appointedTemplate.length() >3 ) {
            arriveAheadFlag = appointedTemplate.split(";").first().toInt();
        }

    } else {
        QLOG_ERROR()<<QString("[<<<<---PmsOrdersData::isOrderAndStatusExist: OrderId:%1 OrderStatus:%2 Not Exist--->>>>]").arg(orderId).arg(OrderStatus);
        result = false;
    }
    m_sqlDb.close();
    return result;
}

//查询无需加锁;
bool PmsOrdersData::isOrderExist(const QString& orderId) {
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---PmsOrdersData::isOrderExist:Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("select order_id from orders where order_id='%1'").arg(orderId));
    if(!query.exec()) {
        QLOG_ERROR()<<"[<<<<---PmsOrdersData::isOrderExist: Select Failed--->>>>]"<<orderId<<query.lastError().text();
        result= false;
    }
    if(query.first()) {
        result= true;
    } else {
        result = false;
        QLOG_ERROR()<<QString("[<<<<---PmsOrdersData::isOrderExist: OrderId:%1 Not Exist--->>>>]").arg(orderId);
    }
    m_sqlDb.close();
    return result;
}

bool PmsOrdersData::queryValue(const QString& orderId, const QString& key, QString& error, QVariant &value){
    if(!m_sqlDb.open()) {
        error.append(QString("PmsOrdersData::Database:Open Failed").append(m_sqlDb.lastError().text()));
        return false;
    }
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("select %1 from orders where order_id='%1'").arg(key).arg(orderId));
    if(!query.exec()) {
        error.append(query.lastError().text());
        m_sqlDb.close();
        return false;
    } else {
        while(query.next()) {
            value= query.value(0);
        }
    }
    m_sqlDb.close();
    return true;
}

