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

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


bool SaveNoticeMsgDB::initSaveNoticeMsgDB(){
    bool bRet = false;
    m_sqlDb = QSqlDatabase::addDatabase("QODBC","SaveNoticeMsgDB");   //数据库驱动类型为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();
        } else {
            QLOG_INFO()<<"[<<<<---SaveNoticeMsgDB::SqlServer Test Open database success!:--->>>>]";
            QSqlQuery query(m_sqlDb);
            QString selectsql ="select * from sys.tables where name='tb_notice_msg'" ;
            if(!query.exec(selectsql)) {
                QLOG_ERROR()<<"[<<<<---SaveNoticeMsgDB::SqlServer Database  check tb_notice_msg failed--->>>>]"<<query.lastError().text();
            }
            if(query.next()) {
                QLOG_INFO() << "[<<<<---SaveNoticeMsgDB::Table tb_notice_msg Has Exist--->>>>]";
                bRet = true;
            } else {
                QLOG_INFO() << "[<<<<---SaveNoticeMsgDB::Table tb_notice_msg Does Not Exist--->>>>]";
                query.prepare( QString("CREATE TABLE [dbo].[tb_notice_msg] ("
                                    " [id] [int] IDENTITY(1,1) NOT NULL, "
                                    " [title] [varchar](200) NULL,  [content] [varchar](1400) NULL, [ack_status] [int] NULL,"
                                    " [create_datetime] [datetime] NULL, [modify_datetime] [datetime] NULL, [ack_datetime] [datetime] NULL,"
                                    " [reserve0] [int] NULL, [reserve1] [int] NULL,[reserve2] [int] NULL,"
                                    " [reserve3] [varchar](100) NULL, [reserve4] [varchar](200) NULL,[reserve5] [varchar](400) NULL,"
                                    " [reserve6] [int] NULL, [reserve7] [int] NULL, [reserve8] [varchar](80) NULL, [reserve9] [varchar](80) NULL"
                                    " PRIMARY KEY CLUSTERED ( [id] ASC"
                                    ")WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = "
                                    " OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]") );

                if(!query.exec()){
                    QLOG_ERROR()<< "[<<<<---Create Table tb_notice_msg Faild--->>>>]" <<query.lastError().text()<<QString::number(query.lastError().type());
                }else {
                    bRet = true;
                }
            }

            QLOG_INFO()<<"[<<<<---SqlServer Test Open database success!:--->>>>]";
            m_sqlDb.close();
        }
    } else {
        QLOG_ERROR()<<"[<<<<---SqlServer ODBC driver no valid--->>>>]";
    }

    return bRet;
}


SaveNoticeMsgDB &SaveNoticeMsgDB::getInstance()
{
    static SaveNoticeMsgDB saveNoticeMsgDB;
    return saveNoticeMsgDB;
}

bool SaveNoticeMsgDB::insertNoticeMsg( NoticeObject* noticeObj , int &insertIdIndex  ) {
    QMutexLocker mutex(&m_mutex);
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SqlServer Database:Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }
    bool result = false;

    QSqlQuery query(m_sqlDb);
    query.prepare("INSERT INTO tb_notice_msg( title, content, ack_status, create_datetime ) VALUES (?, ?, ?, ?)   select @@identity ");
    query.addBindValue( noticeObj->title ); // --通告标题;
    query.addBindValue( noticeObj->content ); // --通告内容;
    query.addBindValue( noticeObj->ackStatus ); // --通告 ACK 状态;
    query.addBindValue( noticeObj->createDatetime ); // --通告创建时间;

    if(!query.exec()) {
        QLOG_ERROR()<<"[<<<<---SqlServer Database: tb_notice_msg  Insert Error--->>>>]"<<query.lastError().text()<<QString::number(query.lastError().type());
        QLOG_INFO()<<QString("INSERT INTO tb_notice_msg( title, content, ack_status, create_datetime ) VALUES(%1, %2, %3, %4)   select @@identity ")
                     .arg( noticeObj->title ).arg( noticeObj->content ).arg( noticeObj->ackStatus ).arg( noticeObj->createDatetime );
    } else {
        result = true;
        if ( query.first() ) {
            insertIdIndex = query.value(0).toInt();
            query.clear();
        }
        QLOG_INFO()<<QString("[<<<<---SaveNoticeMsgDB::insertNoticeMsg  Insert title: %1, content:%2, insertIdIndex:%3 Into Success--->>>>]")
                     .arg( noticeObj->title ).arg( noticeObj->content ).arg( insertIdIndex );
    }

    m_sqlDb.close();
    return result;
}


// 根据 “标题” 更新 Notice 通告内容 & ack_status & modify_datetime;
bool SaveNoticeMsgDB::updateNoticeMsg( NoticeObject* noticeObj ){
    QMutexLocker mutex(&m_mutex);
    bool result;

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

    QDateTime qdaTi = QDateTime::currentDateTimeUtc();
    QString currentDate  =  qdaTi.addSecs( 60*60*( 8-24*RETAIN_NOTICE_EXTRA_DAYS ) ).toString("yyyy-MM-dd");
    QLOG_INFO()<<QString("[<<<<---SaveNoticeMsgDB::updateNoticeMsg Update create_datetime >= %1--->>>>]").arg(currentDate);
    QSqlQuery query(m_sqlDb);
    query.prepare( QString("update tb_notice_msg set content='%1', modify_datetime='%2' , ack_status='%3' where title='%4' "
                           " and CONVERT(varchar(100),create_datetime, 21) >= '%5' ")
                   .arg( noticeObj->content ).arg(noticeObj->createDatetime).arg(noticeObj->ackStatus).arg(noticeObj->title).arg(currentDate) );  //  like '%5%'   [当天]

    if(!query.exec()) {
        QLOG_ERROR()<<query.lastError().text()<<"[<<<<---SqlServer Database: Update Notice Content Failed--->>>>]";
        result= false;
    } else {
        QLOG_INFO()<<QString("[<<<<---SqlServer Database: Update notice->title:%1 ,noticeObj->content:%2, noticeObj->ackStatus:%3 Content success--->>>>]")
                     .arg(noticeObj->title).arg(noticeObj->content).arg(noticeObj->ackStatus);
        result = true;
    }
    m_sqlDb.close();
    return result;
}

bool SaveNoticeMsgDB::updateNoticeAckStatus( QString title , const int insertIdIndex ) {
    QMutexLocker mutex(&m_mutex);
    bool result;

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

    QDateTime qdaTi = QDateTime::currentDateTimeUtc();
    QString currentDate  =  qdaTi.addSecs( 60*60*(8-24*RETAIN_NOTICE_EXTRA_DAYS ) ).toString("yyyy-MM-dd");
    QLOG_INFO()<<QString("[<<<<---SaveNoticeMsgDB::updateNoticeAckStatus Update create_datetime >= %1--->>>>]").arg(currentDate);

    QSqlQuery query(m_sqlDb);
    query.prepare( QString("update tb_notice_msg set ack_status=1 where title='%1' and id=%2 and CONVERT(varchar(100),create_datetime, 21) >= '%3' ")
                   .arg(title).arg(insertIdIndex).arg(currentDate) ); //  like '%5%'   [当天]

    if(!query.exec()) {
        QLOG_ERROR()<<query.lastError().text()<<"[<<<<---SqlServer Database:update notice ack_status Failed--->>>>]";
        result= false;
    } else {
        QLOG_INFO()<<QString("[<<<<---SqlServer Database:Update notice->title:%1 ack_status success--->>>>]").arg(title);
        result = true;
    }
    m_sqlDb.close();
    return result;
}


// 根据 “标题” 判断Notice是已经存在, (存在则更新通告内容);
bool SaveNoticeMsgDB::isNoticeMsgExist(NoticeObject* noticeObj){
    QMutexLocker mutex(&m_mutex);
    bool result;

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

    QDateTime qdaTi = QDateTime::currentDateTimeUtc();
    QString currentDate  =  qdaTi.addSecs( 60*60*( 8-24*RETAIN_NOTICE_EXTRA_DAYS ) ).toString("yyyy-MM-dd");

    QLOG_INFO()<<QString("[<<<<---SaveNoticeMsgDB::isNoticeMsgExist Query create_datetime >= %1--->>>>]").arg(currentDate);
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("select top 1 content from tb_notice_msg where title='%1' and CONVERT(varchar(100),create_datetime, 21) >= '%2' order by  create_datetime desc ")
                  .arg(noticeObj->title).arg(currentDate) ); //  like '%5%'   [当天]

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

    if ( query.first() ) {
        result= true;
    } else {
        result = false;
    }
    return result;
}


bool SaveNoticeMsgDB::queryAllNoticeMsgRecord( QList<NoticeObject*> &noticeObjList )
{
    QMutexLocker mutex(&m_mutex);
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SaveNoticeMsgDB::select notice msg Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }

    bool result=true;
    QDateTime qdaTi = QDateTime::currentDateTimeUtc();
    QString currentDate  =  qdaTi.addSecs( 60*60*( 8-24*RETAIN_NOTICE_EXTRA_DAYS ) ).toString("yyyy-MM-dd");

    QLOG_INFO()<<QString("[<<<<---SaveNoticeMsgDB::Begin Query All Notice Msg Record create_datetime >= %1--->>>>]").arg(currentDate);
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("select id, title, content, ack_status, create_datetime from tb_notice_msg where CONVERT(varchar(100),create_datetime, 21) >= '%1' order by create_datetime")
                  .arg(currentDate));  //  like '%5%'   [当天]

    if ( !query.exec() ) {
        QLOG_ERROR()<<query.lastError().text()<<__FUNCTION__;
        result= false;
    } else {
        // 遍历数据库 通告消息;
        while ( query.next() ) {
            NoticeObject* noPtr = new NoticeObject();
            if ( noPtr ) {
                noPtr->id = query.value(0).toInt();
                noPtr->title = query.value(1).toString();
                noPtr->content = query.value(2).toString();
                noPtr->ackStatus = query.value(3).toInt();
                noPtr->createDatetime = query.value(4).toString();
                noticeObjList.append(noPtr);
                // QLOG_INFO()<<QString("SaveNoticeMsgDB:: Query DB All Notice Msg Sucess, noticeObjList.size()=%1, idIndex:%2, title:%3, ackStatus:%4 ")
                //             .arg( noticeObjList.size() ).arg(noPtr->id).arg( noPtr->title ).arg( noPtr->ackStatus );
            } else {
                QLOG_INFO()<<QString("SaveNoticeMsgDB:: Query DB  All Notice Msg Success, But New NoticeObject Failed, Abandon This Item");
            }
        }
    }
    m_sqlDb.close();
    return result;
}


bool SaveNoticeMsgDB::existNoAckNotice()
{
    QMutexLocker mutex(&m_mutex);
    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SaveNoticeMsgDB::exist No Ack Notice msg Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }

    bool result=true;
    QDateTime qdaTi = QDateTime::currentDateTimeUtc();
    QString currentDate  =  qdaTi.addSecs( 60*60*( 8-24*RETAIN_NOTICE_EXTRA_DAYS ) ).toString("yyyy-MM-dd");

    QLOG_INFO()<<QString("[<<<<---SaveNoticeMsgDB::begin query Exist No Ack Notice create_datetime >= %1--->>>>]").arg(currentDate);
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("select title, content, ack_status, create_datetime from tb_notice_msg where CONVERT(varchar(100),create_datetime, 21) >= '%1' and ack_status = 0 ")
                  .arg(currentDate) ); //  like '%5%'   [当天]

    if ( !query.exec() ) {
        QLOG_ERROR()<<"[<<<<---SqlServer Database:: existNoAckNotice Failed--->>>>] "<<query.lastError().text()<<__FUNCTION__;
        result= false;
    } else {
        if ( query.first() ) {
            result= true;
        } else {
            result = false;
        }
    }
    m_sqlDb.close();
    return result;
}


bool SaveNoticeMsgDB::deleteNoticeMsgRecord(QString creatTime)
{
    QMutexLocker mutex(&m_mutex);
    bool result=true;

    if(!m_sqlDb.open()) {
        QLOG_ERROR()<<"[<<<<---SaveNoticeMsgDB::delete notice msg Open Failed--->>>>]"<<m_sqlDb.lastError().text();
        return false;
    }

    QLOG_INFO()<<QString("[<<<<---SaveNoticeMsgDB::begin delete notice msg create_datetime: %1--->>>>]").arg(creatTime);
    QSqlQuery query(m_sqlDb);
    query.prepare(QString("delete from tb_notice_msg where CONVERT(varchar(100),create_datetime, 21) < '%1' ").arg(creatTime));

    if ( !query.exec() ) {
        QLOG_ERROR()<<query.lastError().text()<<__FUNCTION__;
        result= false;
    }
    m_sqlDb.close();

    return result;
}
