#include "orderstatus.h"
#include "QsLog.h"
#include <QCoreApplication>

Orderstatus::Orderstatus()
{
    QString dbpath=QCoreApplication::applicationDirPath()+QString("/orderstatus.db");
    //db.addDatabase("QSQLITE");
    QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE");
    //db.setDatabaseName("orderstatus.db");
    db.setDatabaseName(dbpath);
    if(!db.open())
    {
        QString error=db.lastError().text();
        QLOG_ERROR()<<QString("Qsqlite database open filed,%1").arg(error);
    }
    else{
        QLOG_INFO()<<QString("Qsqlite database open successed");
    }
    QSqlQuery query;
    int isTableExist;
    query.exec(QString("select count(*) from sqlite_master where type='table' and name='%1'").arg("status"));
    while(query.next())
    {
        isTableExist = query.value(0).toInt();
    }
    if(!isTableExist){
        QLOG_INFO() << "table status does not exist";
        query.exec(QString("create table status (orderId  varchar(20) primary key, isprint int(1))"));
    } else{
        QLOG_INFO() << "table status exists";
    }
    qDebug()<<query.lastError().text();
}

Orderstatus &Orderstatus::getInstance()
{
    static Orderstatus order;
    return order;
}

bool Orderstatus::statusinsert(const QString &orderId, const int &printstatus)
{
    QSqlQuery query;
    query.prepare(QString("insert into status values(%1,%2)").arg(orderId).arg(printstatus));
    if(!query.exec())
    {
        QLOG_ERROR()<<query.lastError().text()<<QString::number(query.lastError().type())<<"statusinsert";
        return false;
    }
    else{
        QLOG_INFO()<<QString("insert orderId %1 into status success").arg(orderId);
        return true;
    }
}

bool Orderstatus::printupdate(const QString &orderId, const int &printstatus)
{
    QSqlQuery query;
    query.prepare(QString("update status set isprint=%1 where orderId='%2'").arg(printstatus).arg(orderId));
    if(!query.exec())
    {
        QLOG_ERROR()<<query.lastError().text()<<"printupdate";
        return false;
    }
    else{
        QLOG_INFO()<<QString("update orderId %1 status success").arg(orderId);
        return true;
    }
}

bool Orderstatus::isprint(const QString &orderId)
{
    QSqlQuery query;
    query.prepare(QString("select isprint from status where orderId=%1").arg(orderId));
    if(!query.exec())
    {
        QLOG_ERROR()<<query.lastError().text();
    }
    while(query.next())
    {
        return query.value(0).toBool();
    }
}

bool Orderstatus::isorderexit(const QString &orderId)
{
    QSqlQuery query;
    query.prepare(QString("select orderId from status where orderId=%1").arg(orderId));
    if(!query.exec())
    {
        QLOG_ERROR()<<query.lastError().text();
    }
    if(query.first())
    {
        return true;
    }
    else{
        return false;
    }
}

