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

SimProcOrderDB::SimProcOrderDB()
{
    m_mutex.lock();
    QString dbpath=QCoreApplication::applicationDirPath()+QString("/SimProcOrderDB.db");
    db=QSqlDatabase::addDatabase("QSQLITE","SimProcOrderDB_connection");
    db.setDatabaseName(dbpath);
    if(!db.open())
    {
        QString error=db.lastError().text();
        QLOG_ERROR()<<QString("[<<<<---Sqlite Database:Open Filed--->>>>][%1]").arg(error);
    }
    else{
        QLOG_INFO()<<QString("[<<<<---Sqlite Database:Open Successed--->>>>]");
    }
    QSqlQuery query(db);
    int isTableExist=0;
    query.exec(QString("select count(*) from sqlite_master where type='table' and name='%1'").arg("SimProcOrderTable"));
    while(query.next())
    {
        isTableExist = query.value(0).toInt();
    }
    if(!isTableExist){
        QLOG_INFO() << "[<<<<---Sqlite Database:Table SimProcOrderTable Does Not Exist--->>>>]";
        query.prepare(QString("create table SimProcOrderTable (orderId  varchar(20) primary key,isPushed int(1),isRefund int(1),isReport int(1),isBackReport int(1),posCheckNo varchar(20),creatTime varchar(20))"));
        if(!query.exec())
        {
            QLOG_ERROR()<<query.lastError().text()<<QString::number(query.lastError().type())<<"[<<<<---Sqlite Database:Create Table SimProcOrderTable Faild--->>>>]";
        }
    } else{
        QLOG_INFO() << "[<<<<---Sqlite Database:Table SimProcOrderTable Has Exist--->>>>]";
    }
    db.close();
    m_mutex.unlock();
}

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

bool SimProcOrderDB::insertSimProcOrder(const QString &orderId,const QString& creatTime)
{
    m_mutex.lock();
    if(!db.open())
    {
        QLOG_ERROR()<<"[<<<<---Sqlite Database:Open Failed--->>>>]"<<db.lastError().text();
        return false;
    }
    bool result;
    QSqlQuery query(db);
    query.prepare(QString("insert into SimProcOrderTable values('%1',0,0,0,0,NUll,'%6')").arg(orderId).arg(creatTime));
    qDebug()<<creatTime;
    if(!query.exec())
    {
        QLOG_ERROR()<<query.lastError().text()<<QString::number(query.lastError().type())<<"[<<<<---Sqlite Database:insertSimProcOrder Error--->>>>]";
        result = false;
    }
    else{
        QLOG_INFO()<<QString("[<<<<---Sqlite Database:Insert OrderId %1 Into SimProcOrderTable Success--->>>>]").arg(orderId);
        result = true;
    }
    db.close();
    m_mutex.unlock();
    return result;
}

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

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

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

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

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

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

bool SimProcOrderDB::updateBackReportOrderStatus(const QString &orderId, const int &backReportOrderStatus)
{
    m_mutex.lock();
    if(!db.open())
    {
        QLOG_ERROR()<<"[<<<<---Sqlite Database:Open Failed--->>>>]"<<db.lastError().text();
        return false;
    }
    bool result;
    QSqlQuery query(db);
    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()<<"[<<<<---Sqlite Database:updateBackReportOrderStatus Failed--->>>>]";
        result= false;
    }
    else{
        QLOG_INFO()<<QString("[<<<<---Sqlite Database:Update OrderId %1 backReportOrderStatus Success--->>>>]").arg(orderId);
        result = true;
    }
    db.close();
    m_mutex.unlock();
    return result;
}

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

bool SimProcOrderDB::updatePosOrderCheckNo(const QString &orderId, const QString &posOrderCheckNo)
{
    m_mutex.lock();
    if(!db.open())
    {
        QLOG_ERROR()<<"[<<<<---Sqlite Database:Open Failed--->>>>]"<<db.lastError().text();
        return false;
    }
    bool result;
    QSqlQuery query(db);
    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("[<<<<---Sqlite Database:Update OrderId %1 posCheckNo Success--->>>>]").arg(orderId);
        result = true;
    }
    db.close();
    m_mutex.unlock();
    return result;
}

bool SimProcOrderDB::getPosOrderCheckNo(const QString &orderId,QString& posOrderCheckNo)
{
    m_mutex.lock();
    bool result=false;
    if(!db.open())
    {
        QLOG_ERROR()<<"[<<<<---Sqlite Database:Open Failed--->>>>]"<<db.lastError().text();
        return result;
    }
    QSqlQuery query(db);
    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;
    }
    db.close();
    m_mutex.unlock();
    return result;
}

bool SimProcOrderDB::deleteOrderRecord(QString creatTime)
{
    m_mutex.lock();
    if(!db.open())
    {
        QLOG_ERROR()<<"[<<<<---Sqlite Database:Open Failed--->>>>]"<<db.lastError().text();
        return false;
    }
    bool result=true;
    QSqlQuery query(db);
    query.prepare(QString("delete from SimProcOrderTable where creatTime<'%1'").arg(creatTime));
    if(!query.exec())
    {
        QLOG_ERROR()<<query.lastError().text()<<__FUNCTION__;
        result= false;
    }
    db.close();
    m_mutex.unlock();
    return result;
}


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

bool SimProcOrderDB::updatekey(const QString &orderId, const QString &key, const int value,  QString &error, bool &result)
{
    QMutexLocker mutex(&m_mutex);
    if(!db.open())
    {
        error.append(QString("Sqlite Database:Open Failed").append(db.lastError().text()));
        return false;
    }
    QSqlQuery query(db);
    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());
        db.close();
        return false;
    }
    else{
        result = true;
    }
    db.close();
    return true;
}

bool SimProcOrderDB::queryIsNull(const QString &orderId, const QString &key, QString &error, bool &result)
{
    QMutexLocker mutex(&m_mutex);
    if(!db.open())
    {
        error.append(QString("Sqlite Database:Open Failed").append(db.lastError().text()));
        return false;
    }
    QSqlQuery query(db);
    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());
        db.close();
        return false;
    }
    else{
        if(query.first())
        {
            result= true;
        }
        else{
            result = false;
        }
    }
    db.close();
    return true;
}

