#include "checkPoskeyExistPosDB.h"
#include "QsLog.h"
#include "alertForm.h"
#include <QDateTime>
#include "Control/flowControl.h"

CheckPoskeyExistPosDB::CheckPoskeyExistPosDB()
{
    QLOG_INFO()<<"[<<<<---CheckPoskeyExistPosDB:: Structure POS CheckPoskeyExistPosDB  INFO DataBase--->>>>]";
}

bool CheckPoskeyExistPosDB::initCheckPoskeyExistPosDB(){
    bool bRet = false;
    m_sqlDb = QSqlDatabase::addDatabase("QODBC","CheckPoskeyExistPosDB");   //数据库驱动类型为SQL Server
    if ( m_sqlDb.isValid() ) {
        QLOG_INFO()<<"[<<<<---SqlServer ODBC driver is valid--->>>>]";
        QString dsn="DRIVER={SQL SERVER};SERVER=127.0.0.1\\sqlexpress;DATABASE=DataStore";
        m_sqlDb.setDatabaseName(dsn);                            //设置数据源名称
        m_sqlDb.setUserName("sa");                               //登录用户
        m_sqlDb.setPassword("SIM29@123");
        if(!m_sqlDb.open()) {                                      //打开数据库
            QLOG_ERROR()<<"[<<<<---SqlServer Open Database error:--->>>>]"<<m_sqlDb.lastError().text();
        } else {
            QLOG_INFO()<<"[<<<<---CheckPoskeyExistPosDB::SqlServer Test Open database success!:--->>>>]";

            QSqlQuery query(m_sqlDb);
            QString selectsql ="select * from sys.tables where name='MENU_ITEM_DEFINITION'" ;
            if(!query.exec(selectsql)) {
                QLOG_ERROR()<<"[<<<<---CheckPoskeyExistPosDB::SqlServer Database  Check  Table MENU_ITEM_DEFINITION failed--->>>>]"<<query.lastError().text();
            }
            if(query.next()) {
                QLOG_INFO() << "[<<<<---CheckPoskeyExistPosDB::Table MENU_ITEM_DEFINITION Has Exist--->>>>]";
                bRet = true;
            } else {
                QLOG_INFO() << "[<<<<---CheckPoskeyExistPosDB::Table MENU_ITEM_DEFINITION Not Exist--->>>>]";
            }

            selectsql ="select * from sys.tables where name='MENU_ITEM_MASTER'" ;
            if(!query.exec(selectsql)) {
                QLOG_ERROR()<<"[<<<<---CheckPoskeyExistPosDB::SqlServer Database  Check  Table MENU_ITEM_MASTER failed--->>>>]"<<query.lastError().text();
            }
            if(query.next()) {
                QLOG_INFO() << "[<<<<---CheckPoskeyExistPosDB::Table MENU_ITEM_MASTER Has Exist--->>>>]";
                bRet = true;
            } else {
                QLOG_INFO() << "[<<<<---CheckPoskeyExistPosDB::Table MENU_ITEM_MASTER Not Exist--->>>>]";
            }
            m_sqlDb.close();
        }
    } else {
        QLOG_ERROR()<<"[<<<<---SqlServer ODBC driver no valid--->>>>]";
    }

    QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---FM TakeOut Plugin Version:2.2021.10.27  Begin Check Poskey Whether Exist POS DB--->>>>]");
    return bRet ;
}


CheckPoskeyExistPosDB &CheckPoskeyExistPosDB::getInstance()
{
    static CheckPoskeyExistPosDB checkPoskeyExistPosDB;
    return checkPoskeyExistPosDB;
}


bool CheckPoskeyExistPosDB::allPoskeyExistDB( OrderObject* orderObj , QStringList & notExistPoskeyList) {
    QMutexLocker mutex(&m_mutex);
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SqlServer Database:Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);
    QVariant queryValue;

    QString tempAllPoskey = orderObj->posKeyList.join(",");
    tempAllPoskey = QString("select distinct M.ObjectNumber from MENU_ITEM_MASTER  AS M "
                            " INNER JOIN MENU_ITEM_DEFINITION AS D on M.MenuItemMasterID = D.MenuItemMasterID  and D.MenuItemClassObjNum IS NOT NULL "
                            " join MENU_ITEM_PRICE AS P on D.MenuItemDefID = P.MenuItemDefID "
                            " left join CHANGE_SET CS on P.ChangeSetObjNum = CS.ObjectNumber "
                            " left join CHANGE_SET_TIMETABLE CST on CS.ChangeSetID = CST.ChangeSetID "
                            " where ( CST.EndTime >= convert( date,getdate() ) OR CST.EndTime IS NULL ) AND   M.ObjectNumber  IN ( " )  + tempAllPoskey  + " )" ;

    QLOG_INFO()<<QString("[<<<<---SqlServer Database: CheckPoskeyExistPosDB  Sql: %1--->>>>]").arg(tempAllPoskey);
    query.prepare( tempAllPoskey );

    if(!query.exec()) {
        QLOG_ERROR()<<"[<<<<---SqlServer Database: allPoskeyExistDB--->>>>] order_id: "<<orderObj->id
                   << " order_status: "<<orderObj->orderStatus<<query.lastError().text();
        result= false;
    }

    QLOG_INFO()<<QString("[<<<<---SqlServer Database: CheckPoskeyExistPosDB  Sql Exe Result: %1 , Target Size: %2 --->>>>]")
                 .arg( query.numRowsAffected() ).arg( orderObj->posKeyList.size() );

    if ( query.numRowsAffected()  == orderObj->posKeyList.size() ) {
        result= true;
        // orderObj->posKeyList.clear();  //不能清空, 否则会在 PrintCupStickPosDB::checkCouponProdAllVaild  将 原本正常合法订单 误判为 非法订单;
    } else {
        result = false;
        notExistPoskeyList = orderObj->posKeyList;

        while( query.next() ) {
            queryValue= query.value(0);
            if ( queryValue.toString().length() ) {
                notExistPoskeyList.removeAll( queryValue.toString() );
            }
        }
    }

    m_sqlDb.close();
    return result;
}


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


bool CheckPoskeyExistPosDB::queryIsNull(const QString &orderId, const QString& key,QString &error, bool &result){
    QMutexLocker mutex(&m_mutex);
    if(!m_sqlDb.open()) {
        error.append(QString("SqlServer Database:Open Failed").append(m_sqlDb.lastError().text()));
        return false;
    }
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("select %1 from MENU_ITEM_MASTER where order_id=%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;
}
