#include "PosMetaDataDB.h"
#include "QsLog.h"
#include <QDateTime>
#include "Control/flowControl.h"
#include "DTools/configManger.h"

PosMetaDataDB::PosMetaDataDB()
{
    QLOG_INFO()<<"[<<<<---PosMetaData:: Structure POS Meta Data Info DataBase--->>>>]";
}


PosMetaDataDB &PosMetaDataDB::getInstance()
{
    static PosMetaDataDB posMetaDataDB;
    return posMetaDataDB;
}


bool PosMetaDataDB::initPosMetaDataDB(){
    bool bRet = false;
    m_configTableExist = false;

    m_sqlDb = QSqlDatabase::addDatabase("QODBC","PosMetaData");   //数据库驱动类型为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=XextCustomDb";
        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()<<"[<<<<---PosMetaData::SqlServer Test Open database success!:--->>>>]";
            QSqlQuery query(m_sqlDb);
            QString selectsql ="select * from sys.tables where name='SBUX_SysConfig'" ;
            if(!query.exec(selectsql)) {
                QLOG_ERROR()<<"[<<<<---PosMetaData::SqlServer Database  check SBUX_SysConfig failed--->>>>]"<<query.lastError().text();
            }
            if(query.next()) {
                QLOG_INFO() << "[<<<<---PosMetaData::Table SBUX_SysConfig Has Exist--->>>>]";
                m_configTableExist = true;
                bRet = true;
            } else {
                QLOG_INFO() << "[<<<<---PosMetaData::Table SBUX_SysConfig Not Exist, It Will Auto Fix Until Pos Generate Offline Order--->>>>]";
            }
            m_sqlDb.close();
        }
    } else {
        QLOG_ERROR()<<"[<<<<---SqlServer ODBC driver no valid--->>>>]";
    }

    return bRet;
}


bool PosMetaDataDB::queryPosMetaDataDB( PosMateDataObject* posMateDataObj) {
    QMutexLocker mutex(&m_mutex);

    if ( !m_configTableExist ) {
        QLOG_INFO()<<"[<<<<---SqlServer Database: queryPosMetaDataDB Table (SBUX_SysConfig), Not Exist Then Skip Query--->>>>]";
        return false;
    }

    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SqlServer Database:Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    bool result = true;

    QSqlQuery query(m_sqlDb);
    QString queryPosMetaDataConfig = QString("SELECT [ConfigName], max( CASE [strKey] WHEN 'WorkstationNumber' THEN strValue else '' end ) as 'WorkstationNumber', "
                                             " max( CASE [strKey] WHEN 'EmpNo' THEN strValue else '' end ) as 'EmpNo', "
                                             " max( CASE [strKey] WHEN 'EmpName' THEN strValue else '' end )  as 'EmpName' "
                                             " FROM [XextCustomDb].[dbo].[SBUX_SysConfig] WHERE ConfigName = 'Workstation' group by ConfigName ");
    // WorkstationNumber; // EmpNo;  // EmpName;
    query.prepare( queryPosMetaDataConfig );
    if(!query.exec()) {
        QLOG_ERROR()<<QString("[<<<<---SqlServer Database::queryPosMetaDataDB Failed, queryPosMetaDataConfig = %1 --->>>>]").arg(queryPosMetaDataConfig)
                   <<query.lastError().text();
        return false;
    } else {

        if ( query.next() ) {
            // QLOG_INFO()<<QString("[<<<<---SqlServer Database::queryPosMetaDataDB Success,  query.value(1) = %1, query.value(2) = %2 , query.value(3) = %3--->>>>]")
            // .arg( query.value(1).toString() ).arg( query.value(2).toString() ).arg( query.value(3).toString() );
            if( query.value(1).toString().length() ) {
                posMateDataObj->workstationNumber = query.value(1).toString();
            } else {
                posMateDataObj->workstationNumber = DEFAULT_WORKSTATION_NUM;
            }
            if( query.value(2).toString().length() ) {
                posMateDataObj->empNo = query.value(2).toString();
            } else {
                posMateDataObj->empNo = DEFAULT_CASHIER_ID;
            }
            if( query.value(3).toString().length() ) {
                posMateDataObj->empName = query.value(3).toString();
            } else {
                posMateDataObj->empName = DEFAULT_CASHIER_NAME;
            }
        }

    }

    m_sqlDb.close();
    return result;
}


QString PosMetaDataDB::getDbStoreId() {
    QMutexLocker mutex(&m_mutex);

    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SqlServer Database:Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return "";
    }

    QString result = "";
    QSqlQuery query(m_sqlDb);
    QLOG_INFO()<< QString("SELECT TOP 1 ObjectNumber FROM [DataStore].[dbo].[V_HIERARCHY] where Parent1=1");
    query.prepare( QString("SELECT TOP 1 ObjectNumber FROM [DataStore].[dbo].[V_HIERARCHY] where Parent1=1") );

    if ( !query.exec() ) {
        QLOG_ERROR()<<"[<<<<---SqlServer Database:getDbStoreId--->>>>]"<<query.lastError().text();
        result= "";
    }

    if ( query.first() ) {
        result= query.value(0).toString();
        QLOG_INFO()<<QString("[<<<<---SqlServer Database, getDbStoreId: %1--->>>>]").arg(result);
    } else {
        result = "";
    }
    m_sqlDb.close();
    return result;
}
