#ifndef FMTAKEAWAY_DB_H
#define FMTAKEAWAY_DB_H

#include "fmtakeaway_db_global.h"

#include "../fmTakeaway/DataObject/OrderObject.h"
#include "../fmTakeaway/DataObject/ComdObject.h"

#include <QSqlDatabase>
#include <QThread>
#include <QNetworkAccessManager>

class SqlWorker;

class FMTAKEAWAY_DBSHARED_EXPORT FmTakeaway_db : public QObject
{
    Q_OBJECT
public:
    typedef struct OPERATORINFO
    {
        QString id;             //人员编号
        QString name;           //人员名称
        QString shiftId;        //班次编号
        QString shiftName;      //班次名称
    }OperatorInfo;

public:
    static FmTakeaway_db &Instance();
    ~FmTakeaway_db();

    // 连接数据库
    void Connect(QString host, QString dataBase,
                 QString userName, QString passWord,
                 int outTime=5);

    // 写入销售单
    void InputSale(OrderObject const*orderObj, const OperatorInfo& operaInfo);

    // 获取在班人员
    void GetOperatorsInfo(QList<OperatorInfo> &listOperator);

    // 获取门店号
    QString GetBranchNum();

    // 获取连接信息
    QString GetConnectInfo();

    // 获取出错信息
    QString GetLastError();

public slots:
    void onFailed(const QString& error);

private:
    FmTakeaway_db();
    FmTakeaway_db(FmTakeaway_db const&);
    FmTakeaway_db& operator=(FmTakeaway_db const&);

private:
    QSqlDatabase    m_db;
    SqlWorker*      m_sqlWorker;
    QThread         m_thread;
    QString         m_lastError;

signals:
    // 发送给工作线程
    void doConnect(QSqlDatabase *db);
    void doGetOpsInfo(QList<FmTakeaway_db::OperatorInfo> *listOperator);
    void doGetBranchNum(QString *branchNum);
    void doInputSale(OrderObject const*orderObj, const FmTakeaway_db::OperatorInfo &operaInfo);

signals:
    // 发送给UI
    void successful();
    void failed();
};



class SqlWorker : public QObject
{
    Q_OBJECT
public:
    SqlWorker();
    QString GetBranchNum();

public slots:
    void onDoConnect(QSqlDatabase *db);
    void onGetOpsInfo(QList<FmTakeaway_db::OperatorInfo> *listOperator);
    void onInputSale(OrderObject const*orderObj, const FmTakeaway_db::OperatorInfo &operaInfo);

private:
    QSqlDatabase *m_db;
    QString m_branchNum;
    QNetworkAccessManager *m_manger;

signals:
    void successful();
    void failed(const QString &error);
};

#endif // FMTAKEAWAY_DB_H
