#include <QApplication>
#include "event/fmapplication.h"
#include "event/posevent.h"
#include "control/ordergetwork.h"
#include "model/posorderpool.h"
#include "view/mainForm.h"
#include "view/floatForm.h"
#include "control/orderlocalizework.h"
#include "control/orderpushwork.h"
#include "control/orderprintwork.h"
#include "control/pickuporderwork.h"
#include "base/Dump/dump.h"
#include "view/loginform.h"
#include <QVariantMap>
#include <QThread>
#include <QDir>
#include <QsLog.h>
#include <QResource>
#include <QSettings>
#include <Windows.h>

#ifdef FM_MAIN_TEST



void LoadTheme(const QString& theme)
{
    QString rccPath = QString("%1/skin/%2.rcc").arg(qApp->applicationDirPath()).arg(theme);
    if(!QFile(rccPath).exists())
    {
        return;
    }
    QResource::registerResource(rccPath);

    QFile qssFile(QString(":/%1.qss").arg(theme));
    if(!qssFile.open(QFile::ReadOnly))
    {
        qDebug() << "failed";
        return;
    }

    qDebug() << "success";

    qApp->setStyleSheet(qssFile.readAll());
    qssFile.close();
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    LoadTheme(QString("deaufult"));

    LoginForm form;

    form.show();

    return a.exec();
}

//int main(int argc, char *argv[])
//{
//     QApplication a(argc, argv);

//     QsLogging::Logger &logger = QsLogging::Logger::instance();
//     logger.setLoggingLevel(QsLogging::TraceLevel);
//     QsLogging::DestinationPtr consleDest(QsLogging::DestinationFactory::MakeDebugOutputDestination());
//     logger.addDestination(consleDest);

//     OrderPushWork pwork;
//     QThread thread;

//     pwork.setToken("fff72b80-e745-4a2e-8ecb-9c184999d01c");
//     //pwork.setToken("1");

//     QVariantMap map;

//     map.insert(JSON_STOREID, "1036");
//     map.insert(JSON_STATIONID, "saas_bf_pos");
//     map.insert(JSON_KEY_USERID, "beiguo_saas");
//     map.insert(JSON_KEY_PWD, "beiguo_saas");
//     map.insert(JSON_KEY_PARTNERID, "1585");

//     //map.insert(JSON_KEY_PARTNERID, "song_test");
//     //map.insert(JSON_STOREID, "test");

//     pwork.setStoreinfo(map);

//     //QStringList list;

//     //list.append("118.89.167.51:9083");

//     //pwork.setServicelist(list);
//     pwork.setSerurl("http://118.89.167.51:9100/gateway?redirect_url=http://10.20.10.106:9140/queryIdleServer&access_token=7705bf51-0832-49e3-8a3d-ac9a57ff0d4b&bf_ver=1");

//     QObject::connect(&thread, &QThread::started, &pwork, &OrderPushWork::workStart);

//     pwork.moveToThread(&thread);

//     thread.start();

//     return a.exec();
//}

#else

using namespace QsLogging;

int  CheckOnly();
void LoadTheme(const QString& theme);
void InitLog();
void InitCfgInfo(QString &geturl, QString &pushurl, QString &autoconf);
void InitPtr();

int main(int argc, char *argv[])
{
    SetUnhandledExceptionFilter(FMExcpHandler);

    if(CheckOnly() != 0)
        return -1;

    QApplication a(argc, argv);

    InitLog();
    LoadTheme(QString("deaufult"));

    QLOG_INFO() << "--------------------------------takeout start------------------------------------";
    //线程必须定义
    QThread thread;
    QThread threadt;
    QThread prtthreadt;
    QThread prtthreadpickup;
    QLOG_INFO() << "Thread List :" << &thread << &threadt << QThread::currentThread();
    //初始化打印文件
    InitPtr();
    //初始化全局订单池主线程中工作
    PosOrderPool::InitOrderPool();
    //读取配置文件
    QString geturl;
    QString pushurl;
    QString autoconf;
    InitCfgInfo(geturl, pushurl, autoconf);
    //定义子工作流及工作流初始化
    OrderGetWork work;
    orderprintwork printwork;
    OrderLocalizeWork loac;
    OrderPushWork pwork;
    PickUpOrderWork pickuporderwork;
    pickuporderwork.setUrl(geturl);
    work.setUrl(geturl);
    work.setAutoconfirm(autoconf);
    work.setTimeout(180000);
    pwork.setSerurl(pushurl);
    //移动子工作流到线程
    loac.moveToThread(&thread, false);
    work.moveToThread(&thread, true);
    printwork.moveToThread(&prtthreadt, true);
    pwork.moveToThread(&threadt, true);
    pickuporderwork.moveToThread(&prtthreadpickup, true);
    //启动tcp长链接和拉单工作流
    thread.start();
    threadt.start();
    prtthreadt.start();
    prtthreadpickup.start();
    //界面类定义及初始化
    MainForm mainform;
    LoginForm loginform;
    FloatForm floatform;
    //开始展示界面
    mainform.MyShow();
    loginform.showfull();
    //回归事件循环
    return a.exec();
}

void InitPtr()
{
    QFile tmpfile(qApp->applicationDirPath() + "/" + PREINTER_NEED);

    if(!tmpfile.exists())
    {
        if(tmpfile.open(QFile::ReadWrite))
            tmpfile.close();
    }
}

void InitCfgInfo(QString &geturl, QString &pushurl, QString &autoconf)
{
    QString configfile = qApp->applicationDirPath() + "/" + CONFIG_NAME;
    QString storefile = qApp->applicationDirPath() + "/" + STOREINFO_NAME;

    QLOG_DEBUG() << "config file name : " << configfile;
    QLOG_DEBUG() << "store file name : " << storefile;

    QString tmpstoreid = QSettings(configfile, QSettings::IniFormat).value(INI_BASE_STOREID).toString();
    QString tmppartnerid = QSettings(configfile, QSettings::IniFormat).value(INI_BASE_PARNETID).toString();
    QString tmpuserid = QSettings(configfile, QSettings::IniFormat).value(INI_BASE_USERID).toString();
    QString tmppwd = QSettings(configfile, QSettings::IniFormat).value(INI_BASE_PWD).toString();
    QString tmpstationid = QSettings(configfile, QSettings::IniFormat).value(INI_BASE_STATIONIID).toString();


    QFile file(storefile);
    if(!file.exists())
    {
        QLOG_INFO() << "Not found " << storefile;
        file.open(QFile::ReadWrite);
        file.close();

        if(!tmpstoreid.isEmpty() && !tmppartnerid.isEmpty() && !tmpuserid.isEmpty() && !tmppwd.isEmpty() && !tmpstationid.isEmpty())
        {
            QSettings(storefile, QSettings::IniFormat).setValue(INI_BASE_PARNETID, tmppartnerid);
            QSettings(storefile, QSettings::IniFormat).setValue(INI_BASE_STOREID, tmpstoreid);
            QSettings(storefile, QSettings::IniFormat).setValue(INI_BASE_STATIONIID, tmpstationid);
            QSettings(storefile, QSettings::IniFormat).setValue(INI_BASE_USERID, tmpuserid);
            QSettings(storefile, QSettings::IniFormat).setValue(INI_BASE_PWD, tmppwd);
        }
    }

    QString storeid = QSettings(storefile, QSettings::IniFormat).value(INI_BASE_STOREID).toString();
    QString partnerid = QSettings(storefile, QSettings::IniFormat).value(INI_BASE_PARNETID).toString();
    QString userid = QSettings(storefile, QSettings::IniFormat).value(INI_BASE_USERID).toString();
    QString pwd = QSettings(storefile, QSettings::IniFormat).value(INI_BASE_PWD).toString();
    QString stationid = QSettings(storefile, QSettings::IniFormat).value(INI_BASE_STATIONIID).toString();

    autoconf = QSettings(configfile, QSettings::IniFormat).value(INI_AUTOCONFIRM).toString();
    pushurl = QSettings(configfile, QSettings::IniFormat).value(INI_PUSHSERVER).toString();
    geturl = QSettings(configfile, QSettings::IniFormat).value(INI_GETSERVER).toString();


    QLOG_DEBUG() << "storeid" << storeid << "partnerid" << partnerid << "userid" << userid;
    QLOG_DEBUG() << "pwd" << pwd << "stationid" << stationid << "autoconf" << autoconf;
    QLOG_DEBUG() << "pushurl" << pushurl << "geturl" << geturl;
}

void InitLog()
{
    QString logDir = QString("%1/log").arg(QCoreApplication::applicationDirPath());
    QDir().mkdir(logDir);

    QsLogging::Logger &logger = QsLogging::Logger::instance();
    logger.setLoggingLevel(QsLogging::DebugLevel);
    QString logPath = QString("%1/%2").arg(logDir, "takeout.log");
    QsLogging::DestinationPtr fileDst(QsLogging::DestinationFactory::MakeFileDestination(
    logPath, QsLogging::EnableLogRotation, QsLogging::MaxSizeBytes(10*1024*1024), QsLogging::MaxOldLogCount(10)));
    logger.addDestination(fileDst);
    QsLogging::DestinationPtr consleDest(QsLogging::DestinationFactory::MakeDebugOutputDestination());
    logger.addDestination(consleDest);
}

void LoadTheme(const QString& theme)
{
    QString rccPath = QString("%1/skin/%2.rcc").arg(qApp->applicationDirPath()).arg(theme);
    if(!QFile(rccPath).exists())
    {
        return;
    }
    QResource::registerResource(rccPath);

    QFile qssFile(QString(":/%1.qss").arg(theme));
    if(!qssFile.open(QFile::ReadOnly))
    {
        return;
    }
    qApp->setStyleSheet(qssFile.readAll());
    qssFile.close();
}

int CheckOnly()
{
    HANDLE m_hMutex  =  CreateMutex(NULL, FALSE,  L"Global\\fmtakeout");

    if(m_hMutex != NULL)
    {
        if  (GetLastError()  ==  ERROR_ALREADY_EXISTS||GetLastError()  ==  ERROR_ACCESS_DENIED)  {
            CloseHandle(m_hMutex);
            m_hMutex  =  NULL;
            return  -1;
        }
    }
    else{
        return -1;
    }

    return 0;
}

#endif
