#include "mainForm.h"
#include <QApplication>
#include <QDir>
#include <QResource>
#include <QThread>
#include "QsLog.h"
#include "preDefine.h"
#include "Control/flowControl.h"
#include "Control/SocketCommunicate.h"
#include "floatForm.h"
#include "DTools/configManger.h"
#include <windows.h>
#include <QProcess>
#include <QSqlDatabase>
#include "DTools/dump.h"

using namespace QsLogging;

QString g_appDir;
QThread  tcpThread;
QThread  workThread;


void InitLogger(){
    QString logDir = QString("%1/log").arg(g_appDir);
    QDir().mkdir(logDir);
    QsLogging::Logger& logger = QsLogging::Logger::instance();
    logger.setLoggingLevel(QsLogging::TraceLevel);
    //日志按天输出
    QsLogging::DestinationPtr fileDst(QsLogging::DestinationFactory::MakeFileDestination(logDir,"FmPlugin", 30,QsLogging::EnableLogRotation,
    QsLogging::MaxSizeBytes(10*1024*1024), QsLogging::MaxOldLogCount(50)));
    logger.addDestination(fileDst);
    QsLogging::DestinationPtr consoleDst(QsLogging::DestinationFactory::MakeDebugOutputDestination());
    logger.addDestination(consoleDst);
}


void LoadTheme(const QString& theme)
{
    QString rccPath = QString("%1/skin/%2.rcc").arg(g_appDir).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();
}

// config.ini (子门店号配置) + userConfig.ini (悬浮框位置坐标)
void CopyOriginConfigResetSelf(const QString& g_appDir){
    QString configFileFullName =  "C:\\Freemud\\fmPlugin\\config.ini";
    QString newConfigFileFullName =  g_appDir + "//" + "config.ini";
    QString newBakConfigFileFullName =  g_appDir + "//" + "config.ini_bak";

    QString userConfigFileFullName =  "C:\\Freemud\\fmPlugin\\userConfig.ini";
    QString newUserConfigFileFullName =  g_appDir + "//" + "userConfig.ini";
    QString newBakUserConfigFileFullName =  g_appDir + "//" + "userConfig.ini_bak";

    QFileInfo configFileInfo(configFileFullName);
    if ( configFileInfo.isFile() )
    {
        QFile::rename(newConfigFileFullName ,newBakConfigFileFullName);
        QFile::copy(configFileFullName, newConfigFileFullName);
        QLOG_INFO() << QString(" Copy config.ini File:: %1 To %2 Success !!!").arg(configFileFullName).arg(newConfigFileFullName);
    }

    QFileInfo userConfigFileInfo(userConfigFileFullName);
    if ( userConfigFileInfo.isFile() )
    {
        QFile::rename(newUserConfigFileFullName ,newBakUserConfigFileFullName);
        QFile::copy(userConfigFileFullName, newUserConfigFileFullName);
        QLOG_INFO() << QString(" Copy userConfig.ini File:: %1 To %2 Success !!!").arg(userConfigFileFullName).arg(newUserConfigFileFullName);
    }

}


int main(int argc, char *argv[])
{
#ifdef Q_OS_WIN
    SetUnhandledExceptionFilter(FMExcpHandler);
#endif
    HANDLE m_hMutex  =  CreateMutex(NULL, FALSE,  L"Global\\fmTakeaway" );
    if(NULL!=m_hMutex){
        if  (GetLastError()  ==  ERROR_ALREADY_EXISTS||GetLastError()  ==  ERROR_ACCESS_DENIED)  {
            CloseHandle(m_hMutex);
            m_hMutex  =  NULL;
            return  -1;
        }
    }
    else{
        return -1;
    }

    QApplication a(argc, argv);
    g_appDir = a.applicationDirPath();

    // 初始化日志
    InitLogger();

    // 加载主题
    LoadTheme(APP_THEME);

    QLOG_INFO() << QString("[<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<---->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>]");
    QLOG_INFO() << QString("[<<<<<<<<<<<<<-- fmTakeout  Start  Version: %1 -->>>>>>>>>>>>>>]").arg(APP_VERSION);
    QLOG_INFO() << QString("[<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<---->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>]");

    // SocketCommuProcess::getMockByteFormatLoginReq();
    // return a.exec();

    // 兼容之前老版本(Qt5.5 & VS2010)的配置文件 与 守护程序的配置文件:
    CopyOriginConfigResetSelf(g_appDir);

    // 将控制器移到工作线程
    FlowControl::GetInstance().moveToThread(&workThread);
    workThread.start();

    // 等插件正常登录成功后,才能发起 长连接业务;
    SocketCommunicate  sockCommunicate;
    sockCommunicate.moveToThread(&tcpThread, true);

    FloatForm f;
    MainForm w;
    QObject::connect(&w, &MainForm::showFloatForm, &f, &FloatForm::onShow);
    QObject::connect(&w, &MainForm::hideFloatForm, &f, &FloatForm::onHide);

    QObject::connect(&FlowControl::GetInstance(), &FlowControl::startRemind, &f, &FloatForm::onStartRemind);
    QObject::connect(&FlowControl::GetInstance(), &FlowControl::doHideMainShowFloatFrom, &w, &MainForm::on_mainBtnHide_clicked);

    QObject::connect(&FlowControl::GetInstance(), &FlowControl::doLockFloatForm, &f, &FloatForm::onLockFloatForm);
    QObject::connect(&FlowControl::GetInstance(), &FlowControl::doUnLockFloatFrom, &f, &FloatForm::onUnLockFloatForm);
    QObject::connect(&FlowControl::GetInstance(), &FlowControl::doUpdateStoreStatus, &f, &FloatForm::onUpdateStoreStatus);
    QObject::connect(&FlowControl::GetInstance(), &FlowControl::changeNoticeStatus, &w, &MainForm::onChangeNoticeStatus);

    QObject::connect(&w, &MainForm::startRemind, &f, &FloatForm::onStartRemind);
    QObject::connect(&w, &MainForm::stopRemind, &f, &FloatForm::onStopRemind);
    QObject::connect(&f, &FloatForm::showMainForm, &w, &MainForm::show);

    // 跨线程 连接 信号与槽， 需要使用 Qt::QueuedConnection 属性;
    QObject::connect(&FlowControl::GetInstance(), &FlowControl::doLoginSuccess,
                     &sockCommunicate,&SocketCommunicate::onFlowControlLoginSuccess, Qt::DirectConnection);
    QObject::connect(&sockCommunicate, &SocketCommunicate::showAlert, &w, &MainForm::onShowAlert);

    w.MyShow();

    return a.exec();
}
