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

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


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

    QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---FM TakeOut Plugin Version:2.20181130.1 Begin Add New Column--->>>>]");
    bRet = alterTablePrintSumBillPosDB();
    return bRet;
}

bool PrintSumBillPosDB::alterTablePrintSumBillPosDB() {
    QMutexLocker mutex(&m_mutex);
    int addSuccessNum = 0;
    QSqlQuery query(m_sqlDb);
    QString selectsql;
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---alterTablePrintSumBillPosDB::SqlServer Database:Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    // Alter Table disPlateformFee;
    selectsql = "select * from syscolumns where id=object_id('tb_msr_customer_info') and name='disPlateformFee'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table tb_msr_customer_info add disPlateformFee int default  0 ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table tb_msr_customer_info disPlateformFee Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    // Alter Table memo;
    selectsql = "select * from syscolumns where id=object_id('tb_msr_customer_info') and name='memo'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table tb_msr_customer_info add memo varchar(400) null ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table tb_msr_customer_info memo Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    // Alter Table reserve0;
    selectsql = "select * from syscolumns where id=object_id('tb_msr_customer_info') and name='reserve0'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table tb_msr_customer_info add reserve0  int default  0 ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table tb_msr_customer_info reserve0 Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    // Alter Table reserve1;
    selectsql = "select * from syscolumns where id=object_id('tb_msr_customer_info') and name='reserve1'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table tb_msr_customer_info add reserve1  int null ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table tb_msr_customer_info reserve1 Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    // Alter Table reserve2;
    selectsql = "select * from syscolumns where id=object_id('tb_msr_customer_info') and name='reserve2'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table tb_msr_customer_info add reserve2  int null ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table tb_msr_customer_info reserve2 Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}

    // Alter Table reserve3;
    selectsql = "select * from syscolumns where id=object_id('tb_msr_customer_info') and name='reserve3'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table tb_msr_customer_info add reserve3  varchar(100) null ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table tb_msr_customer_info reserve3 Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    }  else { addSuccessNum++;}
    // Alter Table reserve4;
    selectsql = "select * from syscolumns where id=object_id('tb_msr_customer_info') and name='reserve4'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table tb_msr_customer_info add reserve4  varchar(200) null ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table tb_msr_customer_info reserve4 Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}
    // Alter Table reserve5;
    selectsql = "select * from syscolumns where id=object_id('tb_msr_customer_info') and name='reserve5'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table tb_msr_customer_info add reserve5  varchar(400) null; ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table tb_msr_customer_info reserve5 Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { addSuccessNum++; }
    } else { addSuccessNum++;}

    m_sqlDb.close();
    if (8 == addSuccessNum) {
        QLOG_INFO()<<"[<<<<---alterTablePrintSumBillPosDB::addSuccessNum = 8 --->>>>]";
        return true;
    } else {
        QLOG_ERROR()<<"[<<<<---alterTablePrintSumBillPosDB::addSuccessNum<8 = --->>>>]"<<addSuccessNum;
        return false;
    }
}


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

bool PrintSumBillPosDB::insertOrderSumBill(OrderObject* orderObj,const QString& posCheckNo){
    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);
    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, "
                  "order_status, waybill_id, take_no, deliver_phone, deliver_name, disPlateformFee, memo) "
                  "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    query.addBindValue(posCheckNo.toInt()); // --小票号
    query.addBindValue(orderObj->lastName); // --顾客-姓
    query.addBindValue(orderObj->consigneeName); // --顾客-全名
    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->orderStatus); // --订单状态(int);
    query.addBindValue((orderObj->waybillId).length()?orderObj->waybillId:QString("0") ); // --物流编号
    query.addBindValue((orderObj->pickupCode).length()?orderObj->pickupCode.toInt():0 ); // --取餐号；
    query.addBindValue(orderObj->riderPhone); // --配送者电话
    query.addBindValue(orderObj->riderName); // -配送者名称
    query.addBindValue( abs(orderObj->disPlateformFee)); // --平台优惠
    query.addBindValue(orderObj->memo); // --订单备注

    QLOG_INFO()<<QString("[<<<--PrintSumBillPosDB::insertOrderSumBill  waybillId:%1-->>>>]").arg((orderObj->waybillId).length()?orderObj->waybillId:QString("0"));

    if(!query.exec())
    {
        QLOG_ERROR()<<"[<<<<---SqlServer Database:customer_info Error--->>>>]"<<query.lastError().text()<<QString::number(query.lastError().type());
        result = false;
        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, disPlateformFee, memo) "
                             "VALUES(%1, %2, %3, %4, %5, %6, %7, %8, %9, %10, %11, %12, %13, %14, %15, %16, %17, %18, %19)").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).length()?orderObj->waybillId:QString("0"))
                     .arg(orderObj->pickupCode.length()==0?0:orderObj->pickupCode.toInt())
                     .arg(orderObj->riderPhone).arg(orderObj->riderName).arg(abs(orderObj->disPlateformFee)).arg(orderObj->memo);
    } else {
        QLOG_INFO()<<QString("[<<<<---SqlServer Database:Insert OrderId %1 Into customer_info Success--->>>>]").arg(orderObj->id);
        result = true;
    }
    m_sqlDb.close();
    return result;
}

bool PrintSumBillPosDB::updateOrderSumBillStatus(OrderObject* orderObj, const int &OrderStatus){
    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);
    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();
    return result;
}

bool PrintSumBillPosDB::isOrderAndCknoSumBillExist(const QString& orderId,const QString& posCheckNo){
    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);
    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();
    return result;
}

bool PrintSumBillPosDB::isOrderSumBillExist(const QString& orderId){
    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);
    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();
    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;
}
