#include "fmPlugin.h"
#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>
#include <QVariant>
#include <QDebug>
#include <QCoreApplication>
#include <QSettings>
#include <QTextCodec>


FmPlugin &FmPlugin::GetInstance()
{
    static FmPlugin fmPlugin;
    return fmPlugin;
}

bool FmPlugin::ConnectDb(const QString &host, const QString &username, const QString &password, const QString &dbname, QString &error)
{
    // 清除之前的连接
    QSqlDatabase::removeDatabase(m_db.connectionName());

    m_db = QSqlDatabase::addDatabase("QODBC");
    m_db.setConnectOptions(QString("SQL_ATTR_LOGIN_TIMEOUT=5;SQL_ATTR_CONNECTION_TIMEOUT=5"));
    m_db.setDatabaseName(QString("Driver={sql server}; server=%1; database=%2; uid=%3; pwd=%4")
                             .arg(host).arg(dbname).arg(username).arg(password));

    if(m_db.open())
    {
       error = QString("success");
       m_db.close();

       return true;
    }else
    {
       error = m_db.lastError().text();

       return false;
    }
}

bool FmPlugin::GetStoreInfo(QString &storeId, QString &posId, QString &cashierId, QDateTime &dateTime, QString &error)
{
    if(!m_db.open())
    {
        error = m_db.lastError().text();
        return false;
    }

    QSqlQuery query = QSqlQuery(m_db);
    // 获取门店号
    QString queryStoreId("select sys_var_value from sys_t_system where sys_var_id='g_branch_no';");
    query.prepare(queryStoreId);
    if (!query.exec())
    {
        error = query.lastError().text();
        m_db.close();
        return false;
    }
    query.next();
    storeId = query.value(0).toString();
    m_storeId = storeId;
    // 获取营业日
    QString queryDateTime("select sys_var_value from sys_t_system where sys_var_id='dBusiness';");
    query.prepare(queryDateTime);
    if (!query.exec())
    {
        error = query.lastError().text();
        m_db.close();
        return false;
    }
    query.next();
    dateTime = query.value(0).toDateTime();

    posId="1";
    cashierId="1";

    error = QString("success");
    m_db.close();
    return true;
}

bool FmPlugin::GetOnDutyCashiers(QList<CashierObject> &cashiersList, QString &error)
{
    if(!m_db.open())
    {
        error = m_db.lastError().text();
        return false;
    }
    // 获取在班收银员信息
    QSqlQuery query = QSqlQuery(m_db);
    QString queryCashiers("select * from v_km_cashshift;");
    query.prepare(queryCashiers);
    if (!query.exec())
    {
        error = query.lastError().text();
        m_db.close();
        return false;
    }
    while(query.next())
    {
        CashierObject cashierObj;
        cashierObj.id           = query.value(0).toString();
        cashierObj.name         = query.value(1).toString();
        cashierObj.shiftId      = query.value(2).toString();
        cashierObj.shiftName    = query.value(3).toString();
        cashiersList.append(cashierObj);
    }

    error = QString("success");
    m_db.close();
    return true;
}

bool FmPlugin::_Check_bill_bWrited(const QString &orderId)
{
    QSqlQuery query = QSqlQuery(m_db);
    QString queryStock = QString("select * from d_t_food_bill0 where sRemark='%1';").arg(orderId);
    query.prepare(queryStock);
    if (!query.exec())
    {
        m_db.close();
        return true;
    }
    if(query.next())
    {
        return true;
    }

    return false;
}


bool FmPlugin::DoOrderEntry(const OrderObject *orderObject, const QString &cashierId, const QString &cashierName, const QString &shiftId, const QString &shiftName, QString &error)
{
    m_orderObject = orderObject;
    if(!m_db.open())
    {
        error = m_db.lastError().text();
        return false;
    }

    // 先检查该订单有没有写入，如果已经写入则不再重复写入
    if(_Check_bill_bWrited(orderObject->order_id))
    {
        error = QString("已经入账,不重复入账");
        m_db.close();
        return true;
    }

    // 先插入顾客信息不管成功与否不影响后续操作
    int custid = -1;
    _InsertInto_p_t_fmwm_custinfo(custid);
    // 开启事务
    if(!m_db.transaction())
    {
        error = m_db.lastError().text();
        m_db.close();
        return false;
    }
    // 插入三张临时表后执行存储过程有一个失败则回滚
    if(_InsertInto_d_t_food_fmbill0(cashierId, cashierName, shiftId, shiftName, custid))
    {
        if(_InsertInto_d_t_food_fmbills0())
        {
            if(_InsertInto_d_t_bill_fmpay0())
            {
                if(_Exec_pr_fmwm())
                {
                    // 都成功则提交
                    m_db.commit();
                    error = QString("success");
                    m_db.close();
                    return true;
                }
            }
        }
    }
    // 回滚
    error = m_lastError;
    m_db.rollback();
    m_db.close();
    return false;
}

bool FmPlugin::GetStockInfo(QList<StockObject> &stockList, QString &error)
{
    if(!m_db.open())
    {
        error = m_db.lastError().text();
        return false;
    }
    StockObject stock;
    QSqlQuery query = QSqlQuery(m_db);
    QString queryStock("select * from v_km_clearfood;");
    query.prepare(queryStock);
    if (!query.exec())
    {
        error = query.lastError().text();
        m_db.close();
        return false;
    }
    while(query.next())
    {
        stock.id = query.value(0).toString();
        stock.num = query.value(2).toInt();
        stockList.append(stock);
    }
    error = QString("success");
    m_db.close();
    return true;
}

bool FmPlugin::_InsertInto_p_t_fmwm_custinfo(int &custid)
{
    QSqlQuery query =  QSqlQuery(m_db);
    // 插入顾客信息表
    QString queryInsert("insert into p_t_fmwm_custinfo(cphone, ccust_n, ssex, saddr) \
                         values(?,?,?,?) select @@identity;");
    query.prepare(queryInsert);
    query.bindValue(0, m_orderObject->phone);
    query.bindValue(1, m_orderObject->customer);
    query.bindValue(2, "");
    query.bindValue(3, m_orderObject->address);
    if(!query.exec())
    {
       return false;
    }
    query.next();
    custid = query.value(0).toInt();
    return true;
}

bool FmPlugin::_InsertInto_d_t_food_fmbill0(const QString& cashierId, const QString& cashierName, const QString& shiftId, const QString& shiftName, int custid)
{
    QSqlQuery query = QSqlQuery(m_db);
    // 查询营业日
    QDateTime dbussiness;
    QString queryDateTime("select sys_var_value from sys_t_system where sys_var_id='dBusiness';");
    query.prepare(queryDateTime);
    if (!query.exec())
    {
        m_lastError = query.lastError().text();
        return false;
    }
    query.next();
    dbussiness = query.value(0).toDateTime();

    // 插入到临时表
    QString queryInsert("insert into d_t_food_fmbill0(cbill_c,cbranch_c,dBusiness,"
                         "ccashier_c, ccashier_n, cshift_c, cshift_n,"
                         "iguestnum,dtbilltime,dtsettletime,noughtamt,npayamt,"
                         "ndisamt,sbilltype,fmwmbillid,sprovider,nfreight,icustid)"
                         "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);");
    query.prepare(queryInsert);
    query.bindValue(0, m_orderObject->order_id);
    query.bindValue(1, m_storeId);
    query.bindValue(2, dbussiness);
    query.bindValue(3, cashierId);
    query.bindValue(4, cashierName);
    query.bindValue(5, shiftId);
    query.bindValue(6, shiftName);
    query.bindValue(7, m_orderObject->remark.mid(m_orderObject->remark.lastIndexOf(':')+1).toInt());
    query.bindValue(8, QDateTime::fromTime_t(m_orderObject->create_time));
    query.bindValue(9, QDateTime::fromTime_t(m_orderObject->create_time));
    query.bindValue(10, _Penny2Dollar(m_orderObject->shop_fee));
    query.bindValue(11, _Penny2Dollar(m_orderObject->shop_fee));
    query.bindValue(12, _Penny2Dollar(m_orderObject->discount_fee));
    query.bindValue(13, QString("\351\200\201\351\244\220\345\215\225"));// 送餐单
    query.bindValue(14, m_orderObject->order_id);
    query.bindValue(15, !m_orderObject->channelName.compare("饿了么") ? QString("饿了么外卖") : m_orderObject->channelName);
    QString send_fee;
    if(!m_orderObject->pay_type.compare("在线支付"))
    {
        send_fee = _Penny2Dollar(m_orderObject->send_fee);
    }else
    {
        send_fee = "0";
    }
    if(m_orderObject->delivery_type==1)
    {
        send_fee = "0";
    }
    query.bindValue(16, send_fee);
    query.bindValue(17, custid);
    if(!query.exec())
    {
        m_lastError = query.lastError().text();
        return false;
    }
    return true;
}

bool FmPlugin::_InsertInto_d_t_food_fmbills0()
{
    QSqlQuery query = QSqlQuery(m_db);
    // 插入商品详情
    QString queryInsert("insert into d_t_food_fmbills0(cbill_c,cfoodbill,"
                         "cfood_c,cfood_n,nqty,nprc,namt)"
                         "values(?,?,?,?,?,?,?);");
    query.prepare(queryInsert);
    for(int i=0; i<m_orderObject->proList.count(); i++)
    {
        query.bindValue(0, m_orderObject->order_id);
        query.bindValue(1, QString("%1").arg(QString::number(i+1),4,QChar('0')));
        query.bindValue(2, m_orderObject->proList.at(i)->pid);
        query.bindValue(3, m_orderObject->proList.at(i)->name);
        query.bindValue(4, QString::number(m_orderObject->proList.at(i)->productAmount));
        query.bindValue(5, _Penny2Dollar(m_orderObject->proList.at(i)->price));
        query.bindValue(6, _Penny2Dollar(m_orderObject->proList.at(i)->price*m_orderObject->proList.at(i)->productAmount));
        if(!query.exec())
        {
            m_lastError = query.lastError().text();
            return false;
        }
    }
    // 单独增加餐盒费入账
    if(m_orderObject->package_fee!=0)
    {
        query.bindValue(0, m_orderObject->order_id);
        query.bindValue(1, QString("%1").arg(QString::number(m_orderObject->proList.count()+1),4,QChar('0')));
        query.bindValue(2, "1510000999");
        query.bindValue(3, QString("餐盒费"));
        query.bindValue(4, "1");
        query.bindValue(5, _Penny2Dollar(m_orderObject->package_fee));
        query.bindValue(6, _Penny2Dollar(m_orderObject->package_fee));
        if(!query.exec())
        {
            m_lastError = query.lastError().text();
            return false;
        }
    }

    return true;
}

bool FmPlugin::_InsertInto_d_t_bill_fmpay0()
{
    QSqlQuery query = QSqlQuery(m_db);
    // 插入支付详情
    QString queryInsert("insert into d_t_bill_fmpay0(cbill_c,"
                         "cbillpay,cpay_c,cpay_n,npayamt)"
                         "values(?,?,?,?,?);");
    query.prepare(queryInsert);
    query.bindValue(0, m_orderObject->order_id);
    query.bindValue(1, "01");
    QString cpay_c(""), cpay_n("");
    if(!m_orderObject->pay_type.compare("在线支付"))
    {
        //程序写死部分移到config文件PayInfo字段
//        if(!m_orderObject->channel.compare("mtwm"))
//        {
//            cpay_c = QString("14");
//            cpay_n = QString("\347\276\216\345\233\242\345\244\226\345\215\226");//美团外卖
//        }else if(!m_orderObject->channel.compare("fmwd"))
//        {
//            cpay_c = QString("13");
//            cpay_n = QString("\345\276\256\344\277\241\345\244\226\345\215\226");//微店外卖
//        }
        QString config = QString("%1/config.ini").arg(QCoreApplication::applicationDirPath());

        QSettings settings(config, QSettings::IniFormat);
        settings.setIniCodec(QTextCodec::codecForName("utf-8"));
        QString strPayInfo = settings.value(QString("PayInfo/%1").arg(m_orderObject->channel)).toString();
        QStringList info = strPayInfo.split('|');
        if(info.count()==2)
        {
            cpay_c = info.at(0);
            cpay_n = info.at(1);
        }
    }else
    {
        cpay_c = QString("01");
        cpay_n = QString("\347\216\260\351\207\221");//现金
    }
    query.bindValue(2, cpay_c);
    query.bindValue(3, cpay_n);
    query.bindValue(4, _Penny2Dollar(m_orderObject->shop_fee));
    if(!query.exec())
    {
        m_lastError = query.lastError().text();
        return false;
    }
    return true;
}

bool FmPlugin::_Exec_pr_fmwm()
{
    QSqlQuery query = QSqlQuery(m_db);
    query.prepare("exec pr_fmwm ?, ? output;");
    query.bindValue(0, m_orderObject->order_id);
    query.bindValue(1, 0, QSql::Out);
    if(!query.exec())
    {
        m_lastError = query.lastError().text();
        return false;
    }
    if(query.boundValue(1).toInt() != 1)
    {
        m_lastError = QString("pr_fmwm result[%1]").arg(query.boundValue(1).toInt());
        return false;
    }
    return true;
}

QString FmPlugin::_Penny2Dollar(int penny)
{
    double dollar = (double)penny/100;
    return QString::number(dollar,'f',2);
}


