#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 "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;



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 main(int argc, char *argv[])
{
    SetUnhandledExceptionFilter(FMExcpHandler);

    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;
    }

    QApplication a(argc, argv);

    LoadTheme(QString("deaufult"));

    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(2*1024*1024), QsLogging::MaxOldLogCount(6)));
    logger.addDestination(fileDst);
    QsLogging::DestinationPtr consleDest(QsLogging::DestinationFactory::MakeDebugOutputDestination());
    logger.addDestination(consleDest);

    QLOG_INFO() << "--------------------------------takeout start------------------------------------";
    QThread thread;
    QThread threadt;
    QLOG_INFO() << "Thread List :" << &thread << &threadt << QThread::currentThread();

    OrderGetWork work;
    orderprintwork printwork;

    MainForm mainform;
    LoginForm loginform;

    PosOrderPool::InitOrderPool();

    QVariantMap map;

    FloatForm floatform;

    OrderLocalizeWork loac;

    OrderPushWork pwork;

    QObject::connect(&mainform, &MainForm::showFloatForm, &floatform, &FloatForm::onShow);
    QObject::connect(&mainform, &MainForm::startRemind, &floatform, &FloatForm::onStartRemind);
    QObject::connect(&mainform, &MainForm::stopRemind, &floatform, &FloatForm::onStopRemind);
    QObject::connect(&loginform, &LoginForm::showmainform, &mainform, &MainForm::showFullScreen);
    QObject::connect(&loginform, &LoginForm::showfloat, &floatform, &FloatForm::onShow);
    QObject::connect(&floatform, &FloatForm::showMainForm, &loginform, &LoginForm::showfull);

    QString configfile = qApp->applicationDirPath() + "/" + CONFIG_NAME;
    QString storefile = qApp->applicationDirPath() + "/" + STOREINFO_NAME;

    QLOG_INFO() << "config file name : " << configfile;
    QLOG_INFO() << "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();

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


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

//    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_STOREID, storeid);
//    map.insert(JSON_STATIONID, stationid);
//    map.insert(JSON_KEY_USERID, userid);
//    map.insert(JSON_KEY_PWD, pwd);
//    map.insert(JSON_KEY_PARTNERID, partnerid);

    //mainform.setStoreinfo(map);

    //work.setUrl(QString("http://118.89.167.51:9100//gateway?action=%1&access_token=%2&ver=%3&sign=%4"));
    work.setUrl(geturl);
    //work.setSerurl(pushurl);
    work.setAutoconfirm(autoconf);
    //work.setStoreinfo(map);
    work.setTimeout(180000);

    //QStringList list;

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

    //pwork.setStoreinfo(map);
    pwork.setSerurl(pushurl);

    loac.moveToThread(&thread);
    work.moveToThread(&thread);
    printwork.moveToThread(&thread);

    pwork.moveToThread(&threadt);

    QObject::connect(&thread, &QThread::started, &work, &OrderGetWork::workStart);
    QObject::connect(&threadt, &QThread::started, &pwork, &OrderPushWork::workStart);

    thread.start();
    threadt.start();

    mainform.MyShow();
    loginform.showfull();


    return a.exec();
}

#endif
