#include "simProcOrderDB.h"
#include "QsLog.h"
#include "preDefine.h"
#include <QDateTime>
#include <QCoreApplication>

SimProcOrderDB::SimProcOrderDB()
{
   QLOG_INFO()<<"[<<<<---SimProcOrderDB:: Structure Order Push and Refund DataBase--->>>>]";
}

bool SimProcOrderDB::initSimProcOrderDB() {
    bool retTryLock = m_mutex.tryLock(VALUE_TRYLOCKNETTIMEOUT);
    if ( !retTryLock ) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::initSimProcOrderDB Try Lock Failed--->>>>]";
        return false;
    }

    bool bRet = false;
    m_sqlDb=QSqlDatabase::addDatabase("QODBC","SimProcOrderDB"); //数据库驱动类型为SQL server;
    if ( m_sqlDb.isValid() ) {
        QLOG_INFO()<<"[<<<<---SimProcOrderDB::SqlServer ODBC driver is valid--->>>>]";
        QString dsn="DRIVER={SQL SERVER};SERVER=127.0.0.1\\sqlexpress;DATABASE=MMXBenefits";
        // Win10不支持属性: ;Trusted_Connection=yes ; 必须取消此属性,否则 QODBC3: Unable to connnet;
        m_sqlDb.setDatabaseName(dsn);                            //设置数据源名称
        m_sqlDb.setUserName("sa");                               //登录用户
        m_sqlDb.setPassword("SIM29@123");
        if(!m_sqlDb.open()) {                                      //打开数据库
            QLOG_ERROR()<<"[<<<<---SimProcOrderDB::SqlServer Open Database error:--->>>>]"<<m_sqlDb.lastError().text();
        } else {
            QLOG_INFO()<<"[<<<<--- SimProcOrderDB::SqlServer Test Open Database Success --->>>>]";
            QSqlQuery query(m_sqlDb);
            QString selectsql ="select * from sys.tables where name='SimProcOrderTable'" ;
            if(!query.exec(selectsql)) {
                QLOG_ERROR()<<"[<<<<---SimProcOrderDB::SqlServer Database  check table SimProcOrderTable command failed--->>>>]"<<query.lastError().text();
            } else {
                if ( query.next() ) {
                    QLOG_INFO() << "[<<<<---SimProcOrderDB::Table SimProcOrderTable Has Exist--->>>>]";
                    bRet = true;
                } else {
                    QLOG_INFO() << "[<<<<---SimProcOrderDB::Table SimProcOrderTable Does Not Exist--->>>>]";
                    // 在此征用: isReport 字段为 预约实物 销售入机标志;在此征用:isBackReport 字段为 预约实物 退货入机标志;
                    // 等待以后扩展: reportOmsSaleRet int default 0, reportOmsRefundRet int default 0
                    query.prepare( QString("create table SimProcOrderTable (orderId varchar(50) primary key, isPushed int, isRefund int, "
                                          " isReport int, isBackReport int, posCheckNo varchar(20), creatTime varchar(20), reportOmsSaleRet int default 0, reportOmsRefundRet int default 0,"
                                          " type varchar(4), status varchar(4), storeId varchar(20), channel varchar(20), opUser varchar(50), "
                                          " recordDate datetime, remark varchar(100), failCode varchar(10), ipAddress varchar(16), decouplePosNo varchar(10),"
                                          " posHostName varchar(50), posMacAddress varchar(30), posVersion varchar(15), deviceType varchar(20), "
                                          " resv0 int default 0, resv1 int default 0, resv2 varchar(10), resv3 varchar(20) )" ) );
                    if ( !query.exec() ) {
                        QLOG_ERROR()<< "[<<<<---Create Table SimProcOrderTable Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
                    } else {
                        bRet = true;
                    }
                }
           }
          m_sqlDb.close();
        }
    } else {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::SqlServer ODBC driver no valid";
    }

    if ( bRet ) {
        bRet = alterTableSimProcOrderDB() && alterTableSimProcOrderDB_2022() ;
        QLOG_INFO()<<QString("[<<<<--- SimProcOrderDB:: FmPosPlugin Version:2.2022.7.25 Begin Alter Column New Cloumn --->>>>]");
        m_mutex.unlock();
        return bRet;
    } else {
        m_mutex.unlock();
        return bRet;
    }
}


bool SimProcOrderDB::alterTableSimProcOrderDB() {
    //QMutexLocker mutex(&m_mutex); 被 initSimProcOrderDB 调用  顾不用加锁，否则死锁；
    int alterSuccessNum = 0;
    QString PrimaryKeyName = "";
    QSqlQuery query(m_sqlDb);
    QString selectsql;
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::alterTableSimProcOrderDB ::SqlServer Database:Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    // 1、Select The Length Of Table Column orderId;
    selectsql = "select length  from syscolumns where id=object_id('SimProcOrderTable') and name='orderId'";
    query.exec(selectsql);
    if(query.first()){
        if(50==query.value(0).toInt()){
            QLOG_INFO()<< "[<<<<---SimProcOrderDB::Length Of SimProcOrderTable Column orderId Is 50, No Need Proc PrimaryKey,Return True --->>>>]" <<query.value(0).toInt();
            m_sqlDb.close();
            return true;
        } else {
            QLOG_ERROR()<< "[<<<<---SimProcOrderDB::Length Of SimProcOrderTable Column orderId Not 50,Need Alter Length Of orderId --->>>>]" <<query.value(0).toInt();
        }
    } else {
        QLOG_ERROR()<< "[<<<<---SimProcOrderDB::Select Length Of SimProcOrderTable Column orderId Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
    }

    // 2、Select The Name Of Table PrimaryKey Constraint;
    selectsql = "select name from SYS.OBJECTS WHERE TYPE_DESC='PRIMARY_KEY_CONSTRAINT' AND PARENT_OBJECT_ID in (SELECT OBJECT_ID FROM SYS.OBJECTS WITH(NOLOCK) WHERE NAME='SimProcOrderTable')";
    query.exec(selectsql);
    if(query.first()){
        PrimaryKeyName = query.value(0).toString();
        QLOG_INFO()<< "[<<<<---SimProcOrderDB::SimProcOrderTable PrimaryKey Constraint Name --->>>>]" <<query.value(0).toString();
        if(PrimaryKeyName.length()){ alterSuccessNum++; }
    } else {
        QLOG_ERROR()<< "[<<<<---SimProcOrderDB::Get SimProcOrderTable PrimaryKey Constraint Name Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
    }

    // 3、Drop Table PrimaryKey Constraint;
    selectsql = "ALTER TABLE SimProcOrderTable DROP CONSTRAINT " + PrimaryKeyName;
    if( !query.exec(selectsql) ){
       QLOG_ERROR()<< "[<<<<---SimProcOrderDB::Drop Table PrimaryKey Constraint Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
    } else { alterSuccessNum++;}

    // 4、Alter Table Column orderId Length 20->50;
    selectsql = "alter table SimProcOrderTable alter column orderId varchar(50) not null;";
    if(!query.exec(selectsql)){
       QLOG_ERROR()<< "[<<<<---SimProcOrderDB::alter table SimProcOrderTable orderId Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
    } else { alterSuccessNum++;}

    // 5、Create Table PrimaryKey Constraint;
    selectsql = "alter table SimProcOrderTable add constraint orderIdPrimaryKey primary key(orderId)";
    if( !query.exec(selectsql) ){
        QLOG_ERROR()<< "[<<<<---SimProcOrderDB::Create Table PrimaryKey Constraint Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
    } else { alterSuccessNum++;}

    m_sqlDb.close();
    if (4 == alterSuccessNum) {
        QLOG_INFO()<<"[<<<<---SimProcOrderDB::alterTableSimProcOrderDB::alterSuccessNum = 4 --->>>>]";
        return true;
    } else {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::alterTableSimProcOrderDB::alterSuccessNum < 4 = --->>>>]"<<alterSuccessNum;
        return false;
    }

}


bool SimProcOrderDB::alterTableSimProcOrderDB_2022() {
    //QMutexLocker mutex(&m_mutex); 被 initSimProcOrderDB 调用  顾不用加锁，否则死锁；
    int addSuccessNum = 0;
    QSqlQuery query(m_sqlDb);
    QString selectsql;
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::alterTableSimProcOrderDB_2022 ::SqlServer Database:Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    //1、Alter Table type;
    selectsql = "select * from syscolumns where id=object_id('SimProcOrderTable') and name='type'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table SimProcOrderTable add type varchar(4) null ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table SimProcOrderTable type Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    //2、Alter Table status;
    selectsql = "select * from syscolumns where id=object_id('SimProcOrderTable') and name='status'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table SimProcOrderTable add status varchar(4) null ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table SimProcOrderTable status Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    //3、Alter Table storeId;
    selectsql = "select * from syscolumns where id=object_id('SimProcOrderTable') and name='storeId'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table SimProcOrderTable add storeId varchar(20) null ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table SimProcOrderTable storeId Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    //4、Alter Table channel;
    selectsql = "select * from syscolumns where id=object_id('SimProcOrderTable') and name='channel'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table SimProcOrderTable add channel varchar(20) null";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table SimProcOrderTable channel Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    //5、Alter Table opUser;
    selectsql = "select * from syscolumns where id=object_id('SimProcOrderTable') and name='opUser'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table SimProcOrderTable add opUser varchar(50) null";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table SimProcOrderTable opUser Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    //6、Alter Table recordDate;
    selectsql = "select * from syscolumns where id=object_id('SimProcOrderTable') and name='recordDate'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table SimProcOrderTable add recordDate datetime null ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table SimProcOrderTable recordDate Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    }  else { addSuccessNum++;}
    //7、Alter Table remark;
    selectsql = "select * from syscolumns where id=object_id('SimProcOrderTable') and name='remark'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table SimProcOrderTable add remark  varchar(100) null ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table SimProcOrderTable remark Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    //8、Alter Table failCode;
    selectsql = "select * from syscolumns where id=object_id('SimProcOrderTable') and name='failCode'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table SimProcOrderTable add failCode  varchar(10) null ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table SimProcOrderTable failCode Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    //9、Alter Table ipAddress;
    selectsql = "select * from syscolumns where id=object_id('SimProcOrderTable') and name='ipAddress'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table SimProcOrderTable add ipAddress  varchar(16) null ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table SimProcOrderTable ipAddress Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    //10、Alter Table decouplePosNo;
    selectsql = "select * from syscolumns where id=object_id('SimProcOrderTable') and name='decouplePosNo'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table SimProcOrderTable add decouplePosNo  varchar(10) null ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table SimProcOrderTable decouplePosNo Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    //11、Alter Table posHostName;
    selectsql = "select * from syscolumns where id=object_id('SimProcOrderTable') and name='posHostName'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table SimProcOrderTable add posHostName  varchar(50) null ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table SimProcOrderTable posHostName Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    //12、Alter Table posMacAddress;
    selectsql = "select * from syscolumns where id=object_id('SimProcOrderTable') and name='posMacAddress'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table SimProcOrderTable add posMacAddress  varchar(30) null ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table SimProcOrderTable posMacAddress Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}

    //13、Alter Table posVersion;
    selectsql = "select * from syscolumns where id=object_id('SimProcOrderTable') and name='posVersion'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table SimProcOrderTable add posVersion  varchar(15) null ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table SimProcOrderTable posVersion Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    //14、Alter Table deviceType;
    selectsql = "select * from syscolumns where id=object_id('SimProcOrderTable') and name='deviceType'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table SimProcOrderTable add deviceType  varchar(20) null ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table SimProcOrderTable deviceType Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    //15、Alter Table reportOmsSaleRet;
    selectsql = "select * from syscolumns where id=object_id('SimProcOrderTable') and name='reportOmsSaleRet'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table SimProcOrderTable add reportOmsSaleRet int default 0 ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table SimProcOrderTable reportOmsSaleRet Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    //16、Alter Table reportOmsRefundRet;
    selectsql = "select * from syscolumns where id=object_id('SimProcOrderTable') and name='reportOmsRefundRet'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table SimProcOrderTable add reportOmsRefundRet int default 0 ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table SimProcOrderTable reportOmsRefundRet Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    //17、Alter Table resv0;
    selectsql = "select * from syscolumns where id=object_id('SimProcOrderTable') and name='resv0'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table SimProcOrderTable add resv0 int default 0 ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table SimProcOrderTable resv0 Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    //18、Alter Table resv1;
    selectsql = "select * from syscolumns where id=object_id('SimProcOrderTable') and name='resv1'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table SimProcOrderTable add resv1 int default 0 ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table SimProcOrderTable resv1 Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    //19、Alter Table resv2;
    selectsql = "select * from syscolumns where id=object_id('SimProcOrderTable') and name='resv2'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table SimProcOrderTable add resv2 varchar(20) null ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table SimProcOrderTable resv2 Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    //20、Alter Table resv3;
    selectsql = "select * from syscolumns where id=object_id('SimProcOrderTable') and name='resv3'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table SimProcOrderTable add resv3 varchar(30) null ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table SimProcOrderTable resv3 Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}

    m_sqlDb.close();

    if (20 == addSuccessNum) {
        QLOG_INFO()<<"[<<<<---SimProcOrderDB::alterTableSimProcOrderDB_2022:: addSuccessNum = 20 --->>>>]";
        return true;
    } else {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::alterTableSimProcOrderDB_2022:: addSuccessNum < 20 = --->>>>]"<<addSuccessNum;
        return false;
    }

}


SimProcOrderDB &SimProcOrderDB::getInstance()
{
    static SimProcOrderDB simProcOrderDB;
    return simProcOrderDB;
}


bool SimProcOrderDB::insertSimProcOrder(const QString &orderId,const QString& creatTime)
{
    //QMutexLocker mutex(&m_mutex);
    bool retTryLock = m_mutex.tryLock(VALUE_TRYLOCKNETTIMEOUT);
    if(!retTryLock){
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::insertSimProcOrder Try Lock Failed--->>>>]";
        return false;
    }

    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::insertSimProcOrder Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        m_mutex.unlock();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("insert into SimProcOrderTable(orderId,isPushed,isRefund,isReport,isBackReport,posCheckNo,creatTime) "
                          " values( '%1', 0, 0, 0, 0, NUll, '%2' ) ").arg(orderId).arg(creatTime));
    if(!query.exec()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB:insertSimProcOrder Error--->>>>]"<<query.lastError().text()<<QString::number(query.lastError().type());
        result = false;
    } else {
        QLOG_INFO()<<QString("[<<<<---SimProcOrderDB:: Insert OrderId %1 Into SimProcOrderTable Success--->>>>]").arg(orderId);
        result = true;
    }
    m_sqlDb.close();
    m_mutex.unlock();
    return result;
}


bool SimProcOrderDB::updatePushOrderStatusAndChkNum(const QString &orderId, const int &pushOrderStatus, const QString &chkNum)
{
    //QMutexLocker mutex(&m_mutex);
    bool retTryLock = m_mutex.tryLock(VALUE_TRYLOCKNETTIMEOUT);
    if(!retTryLock){
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::updatePushOrderStatusAndChkNum Try Lock Failed--->>>>]";
        return false;
    }
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::updatePushOrderStatusAndChkNum Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        m_mutex.unlock();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("update SimProcOrderTable set isPushed=%1, posCheckNo='%2' where orderId='%3'").arg(QString::number(pushOrderStatus)).arg(chkNum).arg(orderId));
    if(!query.exec())
    {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::updatePushOrderStatusAndChkNum Failed--->>>>] OrderId: " << orderId << " " << query.lastError().text();
        result= false;
    } else {
        QLOG_INFO()<<QString("[<<<<---SimProcOrderDB::Update OrderId: %1 pushOrderStatus: %2 CheckNum: %3 Success--->>>>]").arg(orderId).arg(pushOrderStatus).arg(chkNum);
        result = true;
    }
    m_sqlDb.close();
    m_mutex.unlock();
    return result;
}


bool SimProcOrderDB::getDbOrderAllFlag(const QString& id, int& dataBaseIsOrderExistInt, int& dataBaseIsPushInt, int& dataBaseIsCancleInt,
                                        int& dataBaseIsORSPushInt, int& dataBaseIsORSCancleInt, QString& dataBasePosOrderCheckNo){
    //QMutexLocker mutex(&m_mutex);
    bool retTryLock = m_mutex.tryLock(VALUE_TRYLOCKNETTIMEOUT);
    if(!retTryLock){
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::getDbOrderAllFlag Try Lock Failed--->>>>]";
        return false;
    }

    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::getDbOrderAllFlag Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        m_mutex.unlock();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);

    query.prepare(QString("select orderId,isPushed,isRefund,isReport,isBackReport, posCheckNo from SimProcOrderTable where orderId='%1'").arg(id));
    if(!query.exec()) {
        QLOG_ERROR()<<query.lastError().text()<<id<<"[<<<<---SimProcOrderDB::isOrderExit Failed--->>>>]";
        result= false;
    }
    if(query.first()) {
        dataBaseIsOrderExistInt = 1;
        dataBaseIsPushInt = query.value(1).toInt();
        dataBaseIsCancleInt = query.value(2).toInt();
        dataBaseIsORSPushInt = query.value(3).toInt();
        dataBaseIsORSCancleInt = query.value(4).toInt();
        dataBasePosOrderCheckNo = query.value(5).toString();
        result= true;
    } else {
        result = true;
    }
    m_sqlDb.close();
    m_mutex.unlock();
    return result;
}


bool SimProcOrderDB::updateRefundOrderStatusAndChkNum(const QString &orderId, const int &refundOrderStatus, const QString &chkNum)
{
    //QMutexLocker mutex(&m_mutex);
    bool retTryLock = m_mutex.tryLock(VALUE_TRYLOCKNETTIMEOUT);
    if(!retTryLock){
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::updateRefundOrderStatusAndChkNum Try Lock Failed--->>>>]";
        return false;
    }
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::updateRefundOrderStatusAndChkNum  Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        m_mutex.unlock();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("update SimProcOrderTable set isRefund=%1, posCheckNo='%2' where orderId='%3'").arg(QString::number(refundOrderStatus)).arg(chkNum).arg(orderId));

    if(!query.exec()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::updateRefundOrderStatusAndChkNum Failed--->>>>] OrderId: " << orderId << " " <<query.lastError().text();
        result= false;
    } else {
        QLOG_INFO()<<QString("[<<<<---SimProcOrderDB::Update OrderId: %1 refundOrderStatus: %2 CheckNum: %3  Successd --->>>>]").arg(orderId).arg(refundOrderStatus).arg(chkNum);
        result = true;
    }
    m_sqlDb.close();
    m_mutex.unlock();
    return result;
}

//征用isReport 数据库字段用来标志 预约实物 销售单 是否已经入机;
//征用isReport 数据库字段用来标志 预约实物 销售单 是否已经入机;
//征用 isBackReport 数据库字段用来标志 预约实物 退货单 是否已经入机;
//征用 isBackReport 数据库字段用来标志 预约实物 退货单 是否已经入机;

bool SimProcOrderDB::presistOrderInputPosSuccessRecord(const QString &orderId, const OrderObject::PresistInputPosSuccessRecord* pInPosSuRd)
{
    // 单入口更新入机成功记录,无需加锁; [错误理论]
    // [多线程同时操作此表时,将会出现程序异常退出: action: 1,4,5,6,11,12.. 操作SimProcOrderDB表同时, 与定时持久化入机结果相冲突]
    if ( !pInPosSuRd ) {
        QLOG_ERROR()<<QString("[<<<<---SimProcOrderDB::presistOrderInputPosSuccessRecord orderId: %1 Pointer Is Null, Then Return--->>>>]").arg(orderId);
        return false;
    }

    bool retTryLock = m_mutex.tryLock(VALUE_TRYLOCKNETTIMEOUT);
    if(!retTryLock){
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::presistOrderInputPosSuccessRecord Try Lock Failed--->>>>]";
        return false;
    } else {
        QLOG_INFO()<<QString("[<<<<---SimProcOrderDB::presistOrderInputPosSuccessRecord Try Lock Successed, OrderId=%1 --->>>>]")
                     .arg(orderId);
    }

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

    bool result = false;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("update SimProcOrderTable set type='%1', status='%2', storeId='%3', channel='%4', opUser='%5', recordDate='%6', "
                          " remark='%7', failCode='%8', ipAddress='%9', decouplePosNo='%10', posHostName='%11', posMacAddress='%12', posVersion='%13', deviceType='%14' "
                          " where orderId='%15' ")
                  .arg(pInPosSuRd->type).arg(pInPosSuRd->status).arg(pInPosSuRd->storeId).arg(pInPosSuRd->channel).arg(pInPosSuRd->opUser).arg(pInPosSuRd->recordDate)
                  .arg(pInPosSuRd->remark).arg(pInPosSuRd->failCode).arg(pInPosSuRd->ipAddress).arg(pInPosSuRd->decouplePosNo).arg(pInPosSuRd->posHostName)
                  .arg(pInPosSuRd->posMacAddress).arg(pInPosSuRd->posPluginVersion).arg(pInPosSuRd->deviceType).arg(orderId));

    if ( !query.exec() ) {
        QLOG_ERROR()<<QString("[<<<<---SimProcOrderDB::presistOrderInputPosSuccessRecord OrderId: %1, Error: %2  Failed--->>>>]").arg(orderId).arg( query.lastError().text() );
        result= false;
    } else {
        QLOG_INFO()<<QString("[<<<<---SimProcOrderDB::Update OrderId: %1 ReqType: %2 Status: %3  Remark: %4  Successd --->>>>]")
                     .arg(orderId).arg(pInPosSuRd->type).arg(pInPosSuRd->status).arg(pInPosSuRd->remark);
        result = true;
    }

    m_sqlDb.close();
    m_mutex.unlock();
    return result;
}


bool SimProcOrderDB::queryPresistInputPosSuccessRecord(const QString &orderId, QJsonObject&  pInPosSuRdJS)
{
    // 单入口更新入机成功记录,无需加锁; [错误理论]
    // [多线程同时操作此表时,将会出现程序异常退出: action: 1,4,5,6,11,12.. 操作SimProcOrderDB表同时, 与定时持久化入机结果相冲突]
    bool retTryLock = m_mutex.tryLock(VALUE_TRYLOCKNETTIMEOUT);

    if(!retTryLock){
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::queryPresistInputPosSuccessRecord Try Lock Failed--->>>>]";
        return false;
    }

    QString tempOrderId = orderId.trimmed();
    if ( !tempOrderId.length() ) {
        QLOG_ERROR()<<QString("[<<<<---SimProcOrderDB::queryPresistInputPosSuccessRecord orderId Is Empty, Then Return--->>>>]");
        m_mutex.unlock();
        return false;
    }

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

    bool result = false;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("select orderId, type, status, storeId, channel, opUser, recordDate, remark, failCode, ipAddress, decouplePosNo, "
                          " posHostName, posMacAddress, posVersion, deviceType, posCheckNo from SimProcOrderTable where orderId='%1' ").arg( tempOrderId ) );

    if ( !query.exec() ) {
        QLOG_ERROR()<<QString("[<<<<---SimProcOrderDB::queryPresistInputPosSuccessRecord OrderId: %1, Error: %2  Failed--->>>>]").arg(tempOrderId).arg( query.lastError().text() );
    } else {
        if ( query.first() ) {
            QString type = query.value(1).toString();
            QString status  = query.value(2).toString();
            QString storeId  = query.value(3).toString();
            QString channel  = query.value(4).toString();
            QString opUser  = query.value(5).toString();
            QDateTime tempDateTime = query.value(6).toDateTime();
            QString recordDate = tempDateTime.toString("yyyy-MM-dd hh:mm:ss");
            QString remark  = query.value(7).toString();
            QString failCode  = query.value(8).toString();
            QString ipAddress  = query.value(9).toString();
            QString decouplePosNo  = query.value(10).toString();
            QString posHostName = query.value(11).toString();
            QString posMacAddress  = query.value(12).toString();
            QString posVersion  = query.value(13).toString();
            QString deviceType  = query.value(14).toString();
            QString checkNo  = query.value(15).toString();

            pInPosSuRdJS.insert("orderNo",tempOrderId);
            pInPosSuRdJS.insert("type", type);
            pInPosSuRdJS.insert("status", status);
            pInPosSuRdJS.insert("storeId",  storeId);
            pInPosSuRdJS.insert("channel", channel);
            pInPosSuRdJS.insert("checkNo", checkNo);
            pInPosSuRdJS.insert("opUser", opUser);
            pInPosSuRdJS.insert("recordDate", recordDate);
            pInPosSuRdJS.insert("remark", remark);
            pInPosSuRdJS.insert("failCode", failCode);
            pInPosSuRdJS.insert(JSON_IP_ADDRESS, ipAddress);
            pInPosSuRdJS.insert(JSON_POS_WORKS_NUM, decouplePosNo);
            pInPosSuRdJS.insert(JSON_POS_HOST_NAME, posHostName);
            pInPosSuRdJS.insert(JSON_POS_MAC_ADDRESS, posMacAddress);
            pInPosSuRdJS.insert(JSON_POS_PLUGIN_VERSION, posVersion);
            pInPosSuRdJS.insert(JSON_TCP_DEVICE_TYPE , deviceType);
            result= true;
            QLOG_INFO()<<QString("[<<<<---SimProcOrderDB::Query OrderId: %1 ReqType: %2 Status: %3  Remark: %4  Successd --->>>>]")
                         .arg(tempOrderId).arg(type).arg(status).arg(remark);
        } else {
            QLOG_ERROR()<<QString("[<<<<---SimProcOrderDB::Query OrderId: %1 Failed, Not Find Any Record --->>>>]").arg(tempOrderId);
        }
    }
    m_sqlDb.close();
    m_mutex.unlock();
    return result;
}


bool SimProcOrderDB::getPosOrderCheckNo(const QString &orderId,QString& posOrderCheckNo)
{
    bool retTryLock = m_mutex.tryLock(VALUE_TRYLOCKNETTIMEOUT);
    if(!retTryLock){
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::getPosOrderCheckNo Try Lock Failed--->>>>]";
        return false;
    }
    bool result=false;
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::getPosOrderCheckNo Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        m_mutex.unlock();
        return result;
    }
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("select posCheckNo from SimProcOrderTable where orderId='%1'").arg(orderId));
    if(!query.exec()) {
        QLOG_ERROR()<<query.lastError().text()<<orderId<<__FUNCTION__;
        m_mutex.unlock();
        return result;
    }
    while(query.next()) {
        posOrderCheckNo= query.value(0).toString();
        result=true;
    }
    m_sqlDb.close();
    m_mutex.unlock();
    return result;
}


bool SimProcOrderDB::deleteOrderRecord(QString creatTime)
{
    //QMutexLocker mutex(&m_mutex);
    bool retTryLock = m_mutex.tryLock(VALUE_TRYLOCKNETTIMEOUT);
    if(!retTryLock){
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::deleteOrderRecord Try Lock Failed--->>>>]";
        return false;
    }
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::deleteOrderRecord Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        m_mutex.unlock();
        return false;
    }
    bool result=true;
    QLOG_INFO()<<QString("[<<<<---SimProcOrderDB::begin deleteOrderRecord creatTime:%1--->>>>]").arg(creatTime);
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("delete from SimProcOrderTable where creatTime<'%1'").arg(creatTime));
    if(!query.exec()) {
        QLOG_ERROR()<<query.lastError().text();
        result= false;
    }
    m_sqlDb.close();
    m_mutex.unlock();
    return result;
}


bool SimProcOrderDB::queryValue(const QString &orderId, const QString& key,  QString &error, QVariant & value)
{
    QMutexLocker mutex(&m_mutex);
    if(!m_sqlDb.open()) {
        error.append(QString("SimProcOrderDB::queryValue :Open Failed").append(m_sqlDb.lastError().text()));
        return false;
    }
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("select %1 from SimProcOrderTable where orderId='%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;
}


bool SimProcOrderDB::updatekey(const QString &orderId, const QString &key, const int value,  QString &error, bool &result)
{
    QMutexLocker mutex(&m_mutex);
    if(!m_sqlDb.open()) {
        error.append(QString("SimProcOrderDB::updatekey :Open Failed").append(m_sqlDb.lastError().text()));
        return false;
    }
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("update SimProcOrderTable set %1=%2 where orderId='%3'").arg(key)
                  .arg(QString::number(value)).arg(orderId));
    if(!query.exec()) {
        error.append(query.lastError().text());
        m_sqlDb.close();
        return false;
    } else {
        result = true;
    }
    m_sqlDb.close();
    return true;
}


bool SimProcOrderDB::queryIsNull(const QString &orderId, const QString &key, QString &error, bool &result)
{
    QMutexLocker mutex(&m_mutex);
    if(!m_sqlDb.open()) {
        error.append(QString("SimProcOrderDB::queryIsNull Open Failed").append(m_sqlDb.lastError().text()));
        return false;
    }
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("select %1 from SimProcOrderTable where orderId=%2 and %3 is null").arg(orderId,orderId,key));
    if(!query.exec()) {
        error.append(query.lastError().text());
        m_sqlDb.close();
        return false;
    } else {
        if(query.first()) {
            result= true;
        } else {
            result = false;
        }
    }
    m_sqlDb.close();
    return true;
}
