#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;
    bool bRetCheckColumn = 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();
    QLOG_INFO()<<QString::fromLocal8Bit("[<<<<---FM TakeOut Plugin Version:2.2019.520.1 Begin check table tb_msr_customer_info Column--->>>>]");
    bRetCheckColumn = alterTablePrintSumBillPosDBAndCheck();

    return (bRet && bRetCheckColumn);
}

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;
    }
}


bool PrintSumBillPosDB::alterTablePrintSumBillPosDBAndCheck() {
    QMutexLocker mutex(&m_mutex);
    int checkSuccessNum = 0;
    QSqlQuery query(m_sqlDb);
    QString selectsql;
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---alterTablePrintSumBillPosDBAndCheck::SqlServer Database:Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    // Alter Table accept_name;
    selectsql = "select * from syscolumns where id=object_id('tb_msr_customer_info') and name='accept_name'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table tb_msr_customer_info add accept_name varchar(400) null";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table tb_msr_customer_info accept_name Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { checkSuccessNum++; }
    } else { checkSuccessNum++;}
    // Alter Table accept_address ;
    selectsql = "select * from syscolumns where id=object_id('tb_msr_customer_info') and name='accept_address'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table tb_msr_customer_info add accept_address varchar(800) null";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table tb_msr_customer_info accept_address Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { checkSuccessNum++; }
    } else { checkSuccessNum++;}
    // Alter Table accept_phone;
    selectsql = "select * from syscolumns where id=object_id('tb_msr_customer_info') and name='accept_phone'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table tb_msr_customer_info add accept_phone varchar(20) null";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table tb_msr_customer_info accept_phone Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { checkSuccessNum++; }
    } else { checkSuccessNum++;}
    // Alter Table order_id;
    selectsql = "select * from syscolumns where id=object_id('tb_msr_customer_info') and name='order_id'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table tb_msr_customer_info add order_id varchar(50) null";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table tb_msr_customer_info order_id Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { checkSuccessNum++; }
    } else { checkSuccessNum++;}
    // Alter Table order_status;
    selectsql = "select * from syscolumns where id=object_id('tb_msr_customer_info') and name='order_status'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table tb_msr_customer_info add order_status int null ";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table tb_msr_customer_info order_status Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { checkSuccessNum++; }
    } else { checkSuccessNum++;}
    // Alter Table waybill_id;
    selectsql = "select * from syscolumns where id=object_id('tb_msr_customer_info') and name='waybill_id'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table tb_msr_customer_info add waybill_id varchar(50) null";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table tb_msr_customer_info waybill_id Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { checkSuccessNum++; }
    }  else { checkSuccessNum++;}
    // Alter Table take_no;
    selectsql = "select * from syscolumns where id=object_id('tb_msr_customer_info') and name='take_no'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table tb_msr_customer_info add take_no int null";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table tb_msr_customer_info take_no Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { checkSuccessNum++; }
    } else { checkSuccessNum++;}
    // Alter Table deliver_phone;
    selectsql = "select * from syscolumns where id=object_id('tb_msr_customer_info') and name='deliver_phone'";
    query.exec(selectsql);
    if(!query.next()){
        selectsql = "alter table tb_msr_customer_info add deliver_phone varchar(20) null";
        if(!query.exec(selectsql)){
            QLOG_ERROR()<< "[<<<<---alter table tb_msr_customer_info deliver_phone Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
        } else { checkSuccessNum++; }
    } else { checkSuccessNum++;}

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

    m_sqlDb.close();
    if (9 == checkSuccessNum) {
        QLOG_INFO()<<"[<<<<---alterTablePrintSumBillPosDBAndCheck::checkSuccessNum = 9 --->>>>]";
        return true;
    } else {
        QLOG_ERROR()<<"[<<<<---alterTablePrintSumBillPosDBAndCheck::checkSuccessNum < 9 = --->>>>]"<<checkSuccessNum;
        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, reserve3) "
                  "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); // --订单备注
    query.addBindValue(orderObj->secretSignal); // --接头暗号

    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, reserve3) "
                             "VALUES(%1, %2, %3, %4, %5, %6, %7, %8, %9, %10, %11, %12, %13, %14, %15, %16, %17, %18, %19, %20)").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).arg(orderObj->secretSignal);
    } 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;
}
