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

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

bool SimProcOrderDB::initSimProcOrderDB(){
    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;Trusted_Connection=yes";
        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();
            return false;
        } 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();
            }
            if(query.next()) {
                QLOG_INFO() << "[<<<<---SimProcOrderDB::Table SimProcOrderTable Has Exist--->>>>]";
            } else {
                QLOG_INFO() << "[<<<<---SimProcOrderDB::Table SimProcOrderTable Does Not Exist--->>>>]";
                query.prepare(QString("create table SimProcOrderTable ( orderId  varchar(20) primary key,isPushed int,isRefund int,isReport int,isBackReport int,posCheckNo varchar(20),creatTime varchar(20) )"));
                if(!query.exec()){
                    QLOG_ERROR()<< "[<<<<---Create Table SimProcOrderTable Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
                    return false;
                }
            }
            m_sqlDb.close();
            return true;
        }
    } else {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::SqlServer ODBC driver no valid";
    }
    return false;
}


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

bool SimProcOrderDB::insertSimProcOrder(const QString &orderId,const QString& creatTime)
{
    QMutexLocker mutex(&m_mutex);
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::insertSimProcOrder Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("insert into SimProcOrderTable values('%1',0,0,0,0,NUll,'%6')").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();
    return result;
}

bool SimProcOrderDB::updatePushOrderStatus(const QString &orderId, const int &pushOrderStatus)
{
    QMutexLocker mutex(&m_mutex);
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::updatePushOrderStatus Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("update SimProcOrderTable set isPushed=%1 where orderId='%2'")
                  .arg(QString::number(pushOrderStatus)).arg(orderId));
    if(!query.exec())
    {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::updatePushOrderStatus Failed--->>>>]"<<query.lastError().text();
        result= false;
    } else {
        QLOG_INFO()<<QString("[<<<<---SimProcOrderDB::Update OrderId %1 pushOrderStatus success;pushOrderStatus:%2--->>>>]").arg(orderId).arg(pushOrderStatus);
        result = true;
    }
    m_sqlDb.close();
    return result;
}

bool SimProcOrderDB::isPushedOrder(const QString &orderId)
{
    QMutexLocker mutex(&m_mutex);
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::isPushedOrder  Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("select isPushed from SimProcOrderTable where orderId='%1'").arg(orderId));
    if(!query.exec()){
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::isPushedOrder Failed--->>>>]"<<query.lastError().text()<<orderId;
        result= false;
    }
    while(query.next()) {
        result= query.value(0).toBool();
        QLOG_INFO()<<QString("[<<<<---SimProcOrderDB::isPushedOrder  orderId:%1  isPushedOrder:%2  --->>>>]").arg(orderId).arg(result);
    }
    m_sqlDb.close();
    return result;
}

bool SimProcOrderDB::updateRefundOrderStatus(const QString &orderId, const int &refundOrderStatus)
{
    QMutexLocker mutex(&m_mutex);
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::updateRefundOrderStatus  Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("update SimProcOrderTable set isRefund=%1 where orderId='%2'")
                  .arg(QString::number(refundOrderStatus)).arg(orderId));
    if(!query.exec()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::updateRefundOrderStatus Failed--->>>>]"<<query.lastError().text();
        result= false;
    } else {
        QLOG_INFO()<<QString("[<<<<---SimProcOrderDB::Update OrderId %1 refundOrderStatus Successd; refundOrderStatus:%2  --->>>>]").arg(orderId).arg(refundOrderStatus);
        result = true;
    }
    m_sqlDb.close();
    return result;
}

bool SimProcOrderDB::isRefundOrder(const QString &orderId)
{
    QMutexLocker mutex(&m_mutex);
    if(!m_sqlDb.open()){
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::isRefundOrder Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("select isRefund from SimProcOrderTable where orderId='%1'").arg(orderId));
    if(!query.exec()) {
        QLOG_ERROR()<<orderId<<"[<<<<---SimProcOrderDB::isRefundOrder Failed--->>>>]"<<query.lastError().text();
        result= false;
    }
    while(query.next()) {
        result= query.value(0).toBool();
        QLOG_INFO()<<QString("[<<<<---SimProcOrderDB::isRefundOrder:  orderId:%1, isRefundOrder:%2--->>>>]").arg(orderId).arg(result);
    }
    m_sqlDb.close();
    return result;
}

bool SimProcOrderDB::updateReportOrderStatus(const QString &orderId, const int &reportOrderStatus)
{
    QMutexLocker mutex(&m_mutex);
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::updateReportOrderStatus Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("update SimProcOrderTable set isReport=%1 where orderId='%2'")
                  .arg(QString::number(reportOrderStatus)).arg(orderId));
    if(!query.exec()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::updateReportOrderStatus Failed--->>>>]"<<query.lastError().text();
        result= false;
    } else {
        QLOG_INFO()<<QString("[<<<<---SimProcOrderDB::Update OrderId %1 reportOrderStatus Success--->>>>]").arg(orderId);
        result = true;
    }
    m_sqlDb.close();
    return result;
}

bool SimProcOrderDB::isReportOrder(const QString &orderId)
{
    QMutexLocker mutex(&m_mutex);
    if(!m_sqlDb.open()){
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::isReportOrder Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("select isReport from SimProcOrderTable where orderId='%1'").arg(orderId));
    if(!query.exec()) {
        QLOG_ERROR()<<query.lastError().text()<<orderId<<"[<<<<---SimProcOrderDB::isReportOrder Failed--->>>>]";
        result= false;
    }
    while(query.next()) {
        result= query.value(0).toBool();
    }
    m_sqlDb.close();
    return result;
}

bool SimProcOrderDB::updateBackReportOrderStatus(const QString &orderId, const int &backReportOrderStatus)
{
    QMutexLocker mutex(&m_mutex);
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::updateBackReportOrderStatus Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("update SimProcOrderTable set isBackReport=%1 where orderId='%2'")
                  .arg(QString::number(backReportOrderStatus)).arg(orderId));
    if(!query.exec()) {
        QLOG_ERROR()<<query.lastError().text()<<"[<<<<---SimProcOrderDB::updateBackReportOrderStatus Failed--->>>>]";
        result= false;
    } else {
        QLOG_INFO()<<QString("[<<<<---SimProcOrderDB::Update OrderId %1 backReportOrderStatus Success--->>>>]").arg(orderId);
        result = true;
    }
    m_sqlDb.close();
    return result;
}

bool SimProcOrderDB::isBackReportOrder(const QString &orderId)
{
    QMutexLocker mutex(&m_mutex);
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::isBackReportOrder Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("select isBackReport from SimProcOrderTable where orderId='%1'").arg(orderId));
    if(!query.exec()) {
        QLOG_ERROR()<<query.lastError().text()<<orderId<<"[<<<<---SimProcOrderDB::isBackReportOrder Failed--->>>>]";
        result= false;
    }
    while(query.next()) {
        result= query.value(0).toBool();
    }
    m_sqlDb.close();
    return result;
}
bool SimProcOrderDB::isOrderExist(const QString &orderId)
{
    QMutexLocker mutex(&m_mutex);
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::isOrderExist Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("select orderId from SimProcOrderTable where orderId='%1'").arg(orderId));
    if(!query.exec()) {
        QLOG_ERROR()<<query.lastError().text()<<orderId<<"[<<<<---SimProcOrderDB::isOrderExit Failed--->>>>]";
        result= false;
    }
    if(query.first()) {
        result= true;
    } else {
        result = false;
    }
    m_sqlDb.close();
    return result;
}

bool SimProcOrderDB::updatePosOrderCheckNo(const QString &orderId, const QString &posOrderCheckNo)
{
    QMutexLocker mutex(&m_mutex);
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::updatePosOrderCheckNo Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("update SimProcOrderTable set posCheckNo='%1' where orderId='%2'")
                  .arg(posOrderCheckNo).arg(orderId));
    if(!query.exec()) {
        QLOG_ERROR()<<query.lastError().text()<<__FUNCTION__;
        result= false;
    } else {
        QLOG_INFO()<<QString("[<<<<---SimProcOrderDB::Action4: Report CheckNo : Update OrderId:%1 posCheckNo:%2 Success--->>>>]").arg(orderId).arg(posOrderCheckNo);
        result = true;
    }
    m_sqlDb.close();
    return result;
}

bool SimProcOrderDB::getPosOrderCheckNo(const QString &orderId,QString& posOrderCheckNo)
{
    QMutexLocker mutex(&m_mutex);
    bool result=false;
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::getPosOrderCheckNo Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        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__;
        return result;
    }
    while(query.next()) {
        posOrderCheckNo= query.value(0).toString();
        result=true;
    }
    m_sqlDb.close();
    return result;
}

bool SimProcOrderDB::deleteOrderRecord(QString creatTime)
{
    QMutexLocker mutex(&m_mutex);
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SimProcOrderDB::deleteOrderRecord Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        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()<<__FUNCTION__;
        result= false;
    }
    m_sqlDb.close();
    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;
}

