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

PrintSumBillPosDB::PrintSumBillPosDB()
{
    QLOG_INFO()<<"[<<<<---Try Open Pos SqlServer DataBase--->>>>]";
}


bool PrintSumBillPosDB::initPrintSumBillPosDB(){
    //QString dbPath = QString(ConfigManage::Instance().databasePath());
    m_sqlDb = QSqlDatabase::addDatabase("QODBC");   //数据库驱动类型为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=MMXBenefits"; //数据源名称 QT_FmConnectPosDb
        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()<<"[<<<<---SqlServer Test Open database success!:--->>>>]";
            m_sqlDb.close();
            return true;
        }
    }
    else {
        QLOG_ERROR()<<"[<<<<---SqlServer ODBC driver no valid--->>>>]";
    }
    return false;
}

PrintSumBillPosDB &PrintSumBillPosDB::getInstance()
{
    static PrintSumBillPosDB printSumBillPosDB;
    return printSumBillPosDB;
}

bool PrintSumBillPosDB::insertOrderSumBill(OrderObject* orderObj,const QString& posCheckNo){
    m_mutex.lock();
    if(!m_sqlDb.open())
    {
        QLOG_ERROR()<<"[<<<<---SqlServer Database:Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);
    query.prepare("INSERT INTO tb_msr_customer_info(chk_num, last_name, full_name, gender, "
                  "is_birthday, create_datetime, created_by, modify_datetime, modified_by, accept_name, accept_address, accept_phone, order_id, "
                  "waybill_id, take_no, deliver_phone, deliver_name) "
                  "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    query.addBindValue(posCheckNo.toInt()); // --小票号
    query.addBindValue(orderObj->lastName); // --顾客-姓
    query.addBindValue(orderObj->customerName); // --顾客-全名
    QString temp_customerSex;
    if( !orderObj->customerSex.compare(QString::fromLocal8Bit(FM_MALE)) || !orderObj->customerSex.compare(QString("Male")) ){
        temp_customerSex = "Male";
    }else if( !orderObj->customerSex.compare(QString::fromLocal8Bit(FM_FEMALE)) || !orderObj->customerSex.compare(QString("Female")) ){
        temp_customerSex = "Female";
    }else{ temp_customerSex = ""; }
    query.addBindValue(temp_customerSex); // --顾客-性别
    query.addBindValue(0); // --顾客-生日
    QDateTime qdaTi = QDateTime::currentDateTimeUtc();
    query.addBindValue(qdaTi.addSecs(60*60*8).toString("yyyy-MM-dd hh:mm:ss")); // --POS出小票时间
    query.addBindValue(FlowControl::GetInstance()._GetCashierId()); // --订单处理者
    query.addBindValue(""); // --变更订单时间 //??????????????????????????????????????????
    query.addBindValue(""); // --变更订单作者 [*****后期更新*****]
    query.addBindValue(orderObj->consigneeName); // --收货者-人名
    query.addBindValue(orderObj->addressDetail); // --收货者
    query.addBindValue(orderObj->consigneePhone); // --收货者-电话
    query.addBindValue(orderObj->id); // --订单编号
    query.addBindValue(orderObj->waybillId); // --物流编号
    query.addBindValue(orderObj->pickupCode.length()==0?0:orderObj->pickupCode.toInt()); // --取餐号；
    query.addBindValue(orderObj->riderPhone); // --配送者电话
    query.addBindValue(orderObj->riderName); // -配送者名称

    if(!query.exec())
    {
        QLOG_ERROR()<<"[<<<<---SqlServer Database:customer_info Error--->>>>]"<<query.lastError().text()<<QString::number(query.lastError().type());

        QLOG_INFO()<<QString("INSERT INTO tb_msr_customer_info(chk_num, last_name, full_name, gender, "
                             "is_birthday, create_datetime, created_by, modify_datetime, modified_by, "
                             "accept_name, accept_address, accept_phone, order_id, "
                             "waybill_id, take_no, deliver_phone, deliver_name) "
                             "VALUES(%1, %2, %3, %4, %5, %6, %7, %8, %9, %10, %11, %12, %13, %14, %15, %16, %17)").arg(posCheckNo.toInt())
                     .arg(orderObj->lastName).arg(orderObj->customerName).arg(temp_customerSex)
                     .arg(0).arg(qdaTi.addSecs(60*60*8).toString("yyyy-MM-dd hh:mm:ss")).arg(FlowControl::GetInstance()._GetCashierId()).arg("").arg("")
                     .arg(orderObj->consigneeName).arg(orderObj->addressDetail).arg(orderObj->consigneePhone).arg(orderObj->id)
                     .arg(orderObj->waybillId).arg(orderObj->pickupCode.length()==0?0:orderObj->pickupCode.toInt()).arg(orderObj->riderPhone).arg(orderObj->riderName);
        result = false;
    }
    else{
        QLOG_INFO()<<QString("[<<<<---SqlServer Database:Insert OrderId %1 Into customer_info Success--->>>>]").arg(orderObj->id);
        result = true;
    }
    m_sqlDb.close();
    m_mutex.unlock();
    return result;
}

bool PrintSumBillPosDB::updateOrderSumBillStatus(OrderObject* orderObj, const int &OrderStatus){
    m_mutex.lock();
    if(!m_sqlDb.open())
    {
        QLOG_ERROR()<<"[<<<<---SqlServer Database:Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("update tb_msr_customer_info set OrderStatus=%1 where order_id='%2'")
                  .arg(QString::number(OrderStatus)).arg(orderObj->id));
    if(!query.exec())
    {
        QLOG_ERROR()<<query.lastError().text()<<"[<<<<---SqlServer Database:update Order Status Failed--->>>>]";
        result= false;
    }
    else{
        QLOG_INFO()<<QString("[<<<<---SqlServer Database:Update OrderId %1 OrderStatus success--->>>>]").arg(orderObj->id);
        result = true;
    }
    m_sqlDb.close();
    m_mutex.unlock();
    return result;
}

bool PrintSumBillPosDB::isOrderAndCknoSumBillExist(const QString& orderId,const QString& posCheckNo){
    m_mutex.lock();
    if(!m_sqlDb.open())
    {
        QLOG_ERROR()<<"[<<<<---SqlServer Database:Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("select order_id from tb_msr_customer_info where order_id='%1' and chk_num='%2'").arg(orderId).arg(posCheckNo));
    if(!query.exec())
    {
        QLOG_ERROR()<<"[<<<<---SqlServer Database:isOrderAndCknoSumBillExit--->>>>]"<<orderId<<query.lastError().text();
        result= false;
    }
    if(query.first())
    {
        result= true;
    }
    else{
        result = false;
    }
    m_sqlDb.close();
    m_mutex.unlock();
    return result;
}

bool PrintSumBillPosDB::isOrderSumBillExist(const QString& orderId){
    m_mutex.lock();
    if(!m_sqlDb.open())
    {
        QLOG_ERROR()<<"[<<<<---SqlServer Database:Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    bool result;
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("select order_id from tb_msr_customer_info where order_id='%1'").arg(orderId));
    if(!query.exec())
    {
        QLOG_ERROR()<<"[<<<<---SqlServer Database:isOrderSumBillExit--->>>>]"<<orderId<<query.lastError().text();
        result= false;
    }
    if(query.first())
    {
        result= true;
    }
    else{
        result = false;
    }
    m_sqlDb.close();
    m_mutex.unlock();
    return result;
}

bool PrintSumBillPosDB::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 tb_msr_customer_info 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 PrintSumBillPosDB::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 tb_msr_customer_info 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;
}
