#include "login.h"
#include "ui_login.h"

#include <QFile>
#include <QDesktopWidget>
//#include <QAction>
#include <QSettings>

#include "CAppInfo.h"
#include "CSqlite3DBProc.h"
#include "logproc.h"
#include "awMsgBox.h"
#include "CCommonTools.h"
#include "CLiveViodeProc.h"
#include <QDateTime>
#include "CKeyBoardHook.h"
#include "CWindowsFireWall.h"
#include <process.h>

login::login(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::login)
{
    ui->setupUi(this);

    setWindowFlags(Qt::FramelessWindowHint);	

    m_loginType = LOGIN_TYPE::lt_studentCode;
    initParam();

    QDesktopWidget *dekwiget = QApplication::desktop();
    int nWidth = dekwiget->width();
    int nHeight = dekwiget->height();
    double fWRate = (double)nWidth/1280;
    double fHRate= (double)nHeight/800;
    double fRate = fWRate;
    if(fHRate < fWRate)
    {
        fRate = fHRate;
    }

    g_appInfoPtr->m_fRate = fRate;

    QFile qssFile(":/client.qss");
    qssFile.open(QFile::ReadOnly);
    QString qss;
    qss = qssFile.readAll();
    int RATE_BASE_SIZE1 = fRate < 1? 1 : fRate;
    int RATE_BASE_SIZE2 = 2*fRate;
    int RATE_BASE_SIZE3 = 3*fRate;
    int RATE_BASE_SIZE4 = 4*fRate;
    int RATE_BASE_SIZE5 = 5*fRate;
    int RATE_BASE_SIZE6 = 6*fRate;
    int RATE_BASE_SIZE7 = 7*fRate;
    int RATE_BASE_SIZE8 = 8*fRate;
    int RATE_BASE_SIZE10 = 10*fRate;
    int RATE_BASE_SIZE11 = 11*fRate;
    int RATE_BASE_SIZE12 = 12*fRate;
    int RATE_BASE_SIZE14 = 14*fRate;
    int RATE_BASE_SIZE15 = 15 * fRate;
    int RATE_BASE_SIZE16 = 16*fRate;
    int RATE_BASE_SIZE18 = 18*fRate;
    int RATE_BASE_SIZE20 = 20*fRate;
    int RATE_BASE_SIZE22 = 22*fRate;
    int RATE_BASE_SIZE24 = 24*fRate;
    int RATE_BASE_SIZE26 = 26*fRate;
    int RATE_BASE_SIZE30 = 30*fRate;
    int RATE_BASE_SIZE35 = 35*fRate;
    int RATE_BASE_SIZE39 = 39*fRate;
    int RATE_BASE_SIZE40 = 40*fRate;
    int RATE_BASE_SIZE48 = 48*fRate;
    int RATE_BASE_SIZE52 = 52*fRate;
    int RATE_BASE_SIZE76 = 76*fRate;
    int RATE_BASE_SIZE86 = 86*fRate;
    qss.replace("RATE_BASE_SIZE11", QString::number(RATE_BASE_SIZE11));
    qss.replace("RATE_BASE_SIZE12", QString::number(RATE_BASE_SIZE12));
    qss.replace("RATE_BASE_SIZE14", QString::number(RATE_BASE_SIZE14));
    qss.replace("RATE_BASE_SIZE15", QString::number(RATE_BASE_SIZE15));
    qss.replace("RATE_BASE_SIZE16", QString::number(RATE_BASE_SIZE16));
    qss.replace("RATE_BASE_SIZE18", QString::number(RATE_BASE_SIZE18));
    qss.replace("RATE_BASE_SIZE20", QString::number(RATE_BASE_SIZE20));
    qss.replace("RATE_BASE_SIZE22", QString::number(RATE_BASE_SIZE22));
    qss.replace("RATE_BASE_SIZE24", QString::number(RATE_BASE_SIZE24));
    qss.replace("RATE_BASE_SIZE26", QString::number(RATE_BASE_SIZE26));
    qss.replace("RATE_BASE_SIZE30", QString::number(RATE_BASE_SIZE30));
    qss.replace("RATE_BASE_SIZE35", QString::number(RATE_BASE_SIZE35));
    qss.replace("RATE_BASE_SIZE39", QString::number(RATE_BASE_SIZE39));
    qss.replace("RATE_BASE_SIZE40", QString::number(RATE_BASE_SIZE40));
    qss.replace("RATE_BASE_SIZE48", QString::number(RATE_BASE_SIZE48));
    qss.replace("RATE_BASE_SIZE52", QString::number(RATE_BASE_SIZE52));
    qss.replace("RATE_BASE_SIZE76", QString::number(RATE_BASE_SIZE76));
    qss.replace("RATE_BASE_SIZE86", QString::number(RATE_BASE_SIZE86));
    qss.replace("RATE_BASE_SIZE10", QString::number(RATE_BASE_SIZE10));
    qss.replace("RATE_BASE_SIZE8", QString::number(RATE_BASE_SIZE8));
    qss.replace("RATE_BASE_SIZE7", QString::number(RATE_BASE_SIZE7));
    qss.replace("RATE_BASE_SIZE6", QString::number(RATE_BASE_SIZE6));
    qss.replace("RATE_BASE_SIZE5", QString::number(RATE_BASE_SIZE5));
    qss.replace("RATE_BASE_SIZE4", QString::number(RATE_BASE_SIZE4));
    qss.replace("RATE_BASE_SIZE3", QString::number(RATE_BASE_SIZE3));
    qss.replace("RATE_BASE_SIZE2", QString::number(RATE_BASE_SIZE2));
    qss.replace("RATE_BASE_SIZE1", QString::number(RATE_BASE_SIZE1));
    g_appInfoPtr->m_sQssStr = qss;
    setStyleSheet(qss);

	ui->widget_BG->setVisible(false);
	setGeometry(0, 0, dekwiget->width(), dekwiget->height());
	m_pCourseList = nullptr;
	m_pLoading = std::make_shared<awResumeExam>(this, QString::fromLocal8Bit("程序加载中..."));
	m_pLoading->show();
	
	qRegisterMetaType<CStudentClientConfig>("CStudentClientConfig");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnStudentClientConfig, this, &login::onStudentClientConfig);
	qRegisterMetaType<CLoginLimit>("CLoginLimit");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnLoginLimit, this, &login::onLoginLimit);
	qRegisterMetaType<CLoginInfo>("CLoginInfo");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnLoginInfo, this, &login::onLoginInfo);
	qRegisterMetaType<CLogout>("CLogout");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnLogout, this, &login::onLogout);
	qRegisterMetaType<CDownLoadFileInfo>("CDownLoadFileInfo");
	connect(g_httpBllPtr.get(), &CHttpBll::sgnDownLoadFile, this, &login::onDownLoadFile);
    connect(g_httpBllPtr.get(), &CHttpBll::sgnTokenExpired, this, &login::onTokenExpired);

	CHttpRequestPackage hrp;
    hrp.sUri = QString("https://%1/org_properties/byOrgDomain/%2.ecs.qmth.com.cn/studentClientConfig.json")
            .arg(g_appInfoPtr->m_sEscDomain).arg(g_appInfoPtr->m_sOrgPrefix);
	hrp.nRequestType = RequestType::rtStudentClientConfig;
    g_httpBllPtr->getUrl(hrp);

    g_clientVideoProcPtr = std::make_shared<CLiveViodeProc>();
}

login::~login()
{
    if(g_logPtr)
    {
        g_logPtr.reset();
    }

    HWND task = nullptr;
    task=FindWindow(L"Shell_TrayWnd",nullptr);
    if(task)
    {
        ShowWindow(task,SW_SHOW);//隐藏任务栏
    }

    awMsgBox::clear();
    delete ui;
}

void login::initParam()
{
    //g_appInfoPtr = std::make_shared<CAppInfo>();

    g_sysDBProcPtr = std::make_shared<CSqlite3DBProc>();
    if(!g_sysDBProcPtr->OpenDB("data/sys.db"))
    {
        ShowMsg(QString::fromLocal8Bit("打开数据库失败！"), this, MSG_ICON_TYPE::mit_error);
//        myDebug()<<QString::fromLocal8Bit("打开数据库失败！");
    }

    sqlite3_stmt *stmt;
    QString sSql = QString("select name,ifnull(value,'') from t_param");
    if(!g_sysDBProcPtr->QuerySql(sSql.toStdString(), &stmt))
    {
        ShowMsg(QString::fromLocal8Bit("加载参数信息失败！"), this, MSG_ICON_TYPE::mit_error);
//        myDebug()<<QString::fromLocal8Bit("查询参数信息失败！");
        return;
    }

    QString sProjectName = "";
    QString sEndpoint = "";
    QString sLogstore = "";
    QString sHttpServer ="";
    QString sHttpPort = "";
    QString sWebsocketServer = "";
    QString sWebsocketPort = "";
    QString sUseHttps = "";
    int nField64 = 0;
    std::string sField = "";
    g_sysDBProcPtr->BeginGetFields(stmt);
    while(!g_sysDBProcPtr->Eof())
    {
        QString sName = g_sysDBProcPtr->GetFields(0, sField, stmt).c_str();
        QString sValue = g_sysDBProcPtr->GetFields(1, sField, stmt).c_str();
        if(sName == "log_project_name")
        {
           sProjectName = sValue;
        }
        else if(sName == "log_endpoint")
        {
            sEndpoint = sValue;
        }
        else if(sName == "log_store")
        {
            sLogstore = sValue;
        }
        else if(sName == "http_server")
        {
            sHttpServer = sValue;
			QStringList sVl = sValue.split(".");
			if (sVl.count() > 0)
			{
				g_appInfoPtr->m_sOrgPrefix = sVl[0];
			}
        }
        else if(sName == "http_port")
        {
            sHttpPort = sValue;
        }
        else if(sName == "websocket_server")
        {
            sWebsocketServer = sValue;
        }
        else if(sName == "websocket_port")
        {
            sWebsocketPort = sValue;
        }
        else if(sName == "use_https")
        {
            sUseHttps = sValue;
        }
		else if (sName == "esc_domain")
		{
			g_appInfoPtr->m_sEscDomain = sValue;
		}		

        g_sysDBProcPtr->Next(stmt);
    }
    g_sysDBProcPtr->EndGetFields(stmt);

    if(sProjectName.isEmpty() || sEndpoint.isEmpty() || sLogstore.isEmpty())
    {
        //未配置日志参数
    }
    else
    {
        g_logPtr = std::make_shared<CLogTrack>(sProjectName, sEndpoint, sLogstore);
    }

    g_appInfoPtr->m_sHttpServer = sHttpServer;
    g_appInfoPtr->m_sHttpPort = sHttpPort;
    g_httpBllPtr = std::make_shared<CHttpBll>();
    if(sUseHttps == "1")
    {
        g_httpBllPtr->init(sHttpServer, sHttpPort, true);
    }
    else
    {
        g_httpBllPtr->init(sHttpServer, sHttpPort);
    }

	sSql = QString("select version_id,version_code,ifnull(machine_id,''),ifnull(update_time,'') from t_sysinfo");
	if (!g_sysDBProcPtr->QuerySql(sSql.toStdString(), &stmt))
	{
        ShowMsg(QString::fromLocal8Bit("加载参数信息失败！"), this, MSG_ICON_TYPE::mit_error);
		//        myDebug()<<QString::fromLocal8Bit("查询参数信息失败！");
		return;
	}
	int nField = 0;
	g_sysDBProcPtr->BeginGetFields(stmt);
	if (!g_sysDBProcPtr->Eof())
	{
		g_appInfoPtr->m_nVersionId = g_sysDBProcPtr->GetFields(0, nField, stmt);
		g_appInfoPtr->m_sVersionCode = g_sysDBProcPtr->GetFields(1, sField, stmt).c_str();
		g_appInfoPtr->m_sMachineId = g_sysDBProcPtr->GetFields(2, sField, stmt).c_str();		
	}
	g_sysDBProcPtr->EndGetFields(stmt);

	if (g_appInfoPtr->m_sMachineId == "")
	{
		if (CCommonTools::IsWow64())
		{
			QSettings settings(R"(HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography)", QSettings::Registry64Format);
			g_appInfoPtr->m_sMachineId = settings.value("MachineGuid", "").toString();
		}
		else
		{
			QSettings settings(R"(HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography)", QSettings::Registry32Format);
			g_appInfoPtr->m_sMachineId = settings.value("MachineGuid", "").toString();
		}

		if (g_appInfoPtr->m_sMachineId == "")
		{
			g_appInfoPtr->m_sMachineId = CCommonTools::getUuid();
		}

		sSql = QString("update t_sysinfo set machine_id = '%1'").arg(g_appInfoPtr->m_sMachineId);
		if (!g_sysDBProcPtr->ExcuteSql(sSql.toStdString()))
		{
            ShowMsg(QString::fromLocal8Bit("保存机器信息失败！"), this, MSG_ICON_TYPE::mit_error);
			//myDebug() << QString::fromLocal8Bit("保存机器信息失败！");
			return;
		}
	}
}

void login::initUI()
{
    QDesktopWidget *dekwiget = QApplication::desktop();
    setGeometry(0, 0, dekwiget->width(), dekwiget->height());
    ui->widget_BG->setGeometry(0, 0, dekwiget->width(), dekwiget->height());
    ui->btn_close->setGeometry(width() - g_appInfoPtr->m_fRate*24, 0,
                               g_appInfoPtr->m_fRate*24, g_appInfoPtr->m_fRate*24);
    ui->label_org_logo->setGeometry(g_appInfoPtr->m_fRate * 80, g_appInfoPtr->m_fRate *5, g_appInfoPtr->m_fRate * 400, g_appInfoPtr->m_fRate * 100);
    ui->label_org_bg->setGeometry(0, g_appInfoPtr->m_fRate * (100+10), ui->widget_BG->width(), ui->widget_BG->height() - g_appInfoPtr->m_fRate*(100 + 10));
//	ui->widget_loginBG->setGeometry((width() - g_appInfoPtr->m_fRate*800)/2, (height() - g_appInfoPtr->m_fRate*480)/2,
//                                    g_appInfoPtr->m_fRate*800, g_appInfoPtr->m_fRate*480);
//    ui->widget_orgInfo->setGeometry(0,0, g_appInfoPtr->m_fRate*300, ui->widget_loginBG->height());
//    ui->label_orgTitle->adjustSize();
//    ui->label_orgTitle->setGeometry((ui->widget_orgInfo->width() - ui->label_orgTitle->width())/2,
//                                    g_appInfoPtr->m_fRate*42, ui->label_orgTitle->width(), ui->label_orgTitle->height());


//    ui->label_complay->adjustSize();
//    ui->label_complay->setGeometry(g_appInfoPtr->m_fRate*42, ui->widget_orgInfo->height() - g_appInfoPtr->m_fRate*42 - ui->label_complay->height(),
//                                   ui->label_complay->width(), ui->label_complay->height());
    if(!g_appInfoPtr->m_sVersionCode.isEmpty())
    {
        ui->label_login_version->setText(QString::fromLocal8Bit("系统版本号：V%1").arg(g_appInfoPtr->m_sVersionCode));
    }

    ui->widget_login->setGeometry(width() - g_appInfoPtr->m_fRate*(120+498), ui->label_org_bg->y() + g_appInfoPtr->m_fRate*60,
                                  g_appInfoPtr->m_fRate*400, g_appInfoPtr->m_fRate*454);
    ui->label_loginTitle->adjustSize();
    ui->label_loginTitle->setGeometry((ui->widget_login->width() - ui->label_loginTitle->width())/2,
                                      0,
                                      ui->label_loginTitle->width(), ui->label_loginTitle->height());

    ui->btn_studentCodeLogin->setGeometry(g_appInfoPtr->m_fRate*40, ui->label_loginTitle->y() + ui->label_loginTitle->height() + g_appInfoPtr->m_fRate*30,
                                          (ui->widget_login->width() -g_appInfoPtr->m_fRate*40*2) / 2, g_appInfoPtr->m_fRate * 44);
    ui->btn_identityLogin->setGeometry(ui->btn_studentCodeLogin->x() + ui->btn_studentCodeLogin->width(), ui->btn_studentCodeLogin->y(),
		ui->btn_studentCodeLogin->width(), ui->btn_studentCodeLogin->height());
	if (m_loginType == LOGIN_TYPE::lt_identity)
	{
		ui->btn_identityLogin->setGeometry((ui->widget_login->width() - ui->btn_studentCodeLogin->width() )/ 2, ui->btn_studentCodeLogin->y(),
			ui->btn_studentCodeLogin->width(), ui->btn_studentCodeLogin->height());
	}

    if(m_nloginTypeCount < 2)
    {
        if(m_loginType == LOGIN_TYPE::lt_studentCode)
        {
            ui->btn_studentCodeLogin->setGeometry(g_appInfoPtr->m_fRate*40, ui->label_loginTitle->y() + ui->label_loginTitle->height() + g_appInfoPtr->m_fRate*30, ui->widget_login->width() - g_appInfoPtr->m_fRate*40*2, g_appInfoPtr->m_fRate * 44);
        }

        if(m_loginType == LOGIN_TYPE::lt_identity)
        {
            ui->btn_identityLogin->setGeometry(g_appInfoPtr->m_fRate*40, ui->label_loginTitle->y() + ui->label_loginTitle->height() + g_appInfoPtr->m_fRate*30, ui->widget_login->width() - g_appInfoPtr->m_fRate*40*2, g_appInfoPtr->m_fRate * 44);
        }
    }
	
    ui->widget_loginInfo->setGeometry(0, ui->btn_studentCodeLogin->y() + ui->btn_studentCodeLogin->height(),
                                      ui->widget_login->width(), ui->widget_login->height() - ui->btn_studentCodeLogin->y() - ui->btn_studentCodeLogin->height());

    ui->edt_account->setGeometry((ui->widget_loginInfo->width() - g_appInfoPtr->m_fRate*280)/2,
                                 g_appInfoPtr->m_fRate*70,
                                 g_appInfoPtr->m_fRate*280, g_appInfoPtr->m_fRate*50);


    ui->edt_password->setGeometry(ui->edt_account->x(), ui->edt_account->y() + ui->edt_account->height() + g_appInfoPtr->m_fRate*20,
                                  ui->edt_account->width(), ui->edt_account->height());
    ui->btn_login->setGeometry(ui->edt_account->x(), ui->edt_password->y() + ui->edt_password->height() + g_appInfoPtr->m_fRate*40,
                               ui->edt_account->width(), g_appInfoPtr->m_fRate*56);
    ui->label_login_version->adjustSize();
    ui->label_login_version->setGeometry(ui->widget_login->x() + (ui->widget_login->width() - ui->label_login_version->width())/2,
                                   ui->widget_BG->height() - g_appInfoPtr->m_fRate*40 - ui->label_login_version->height(),
                                   ui->label_login_version->width(), ui->label_login_version->height());

	ui->widget_BG->setVisible(true);
	setBtnStyle();
	
	m_pLoading.reset();
}

void login::setBtnStyle()
{
    if(m_nloginTypeCount < 2)
    {
        if(m_loginType == LOGIN_TYPE::lt_studentCode)
        {
            ui->btn_studentCodeLogin->setStyleSheet(QString(R"(QPushButton
                                                            {
                                                                outline:none;
                                                                font-size:%1px;
                                                                font-family:"Microsoft YaHei";
                                                                font-weight:400;
                                                                color:rgba(19,187,138,1);
                                                                background:rgba(255,255,255,1);
                                                                border:0px;
                                                                border-top-left-radius:%2;
                                                                border-top-right-radius:%3px;
                                                            })").arg((int)(g_appInfoPtr->m_fRate*14)).arg((int)(g_appInfoPtr->m_fRate*8)).arg((int)(g_appInfoPtr->m_fRate*8)));
        }
        else
        {
            ui->btn_identityLogin->setStyleSheet(QString(R"(QPushButton
                                             {
                                                 outline:none;
                                                 font-size:%1px;
                                                 font-family:"Microsoft YaHei";
                                                 font-weight:400;
                                                 color:rgba(19,187,138,1);
                                                 background:rgba(255,255,255,1);
                                                 border-top-left-radius:%2;
                                                 border-top-right-radius:%3px;
                                             })").arg((int)(g_appInfoPtr->m_fRate*14))
                                            .arg((int)(g_appInfoPtr->m_fRate*8))
                                            .arg((int)( g_appInfoPtr->m_fRate*8 )));
        }
    }
    else
    {
        if(m_loginType == LOGIN_TYPE::lt_studentCode)
        {
            ui->btn_studentCodeLogin->setStyleSheet(QString(R"(QPushButton
                                                            {
                                                                outline:none;
                                                                font-size:%1px;
                                                                font-family:"Microsoft YaHei";
                                                                font-weight:400;
                                                                color:rgba(255,255,255,1);
                                                                background:rgba(19,187,138,1);
                                                                border:0px;
                                                                border-top-left-radius:%2px;
                                                            })").arg((int)(g_appInfoPtr->m_fRate*14)).arg((int)(g_appInfoPtr->m_fRate*8)));
            ui->btn_identityLogin->setStyleSheet(QString(R"(QPushButton
                                                         {
                                                             outline:none;
                                                             font-size:%1px;
                                                             font-family:"Microsoft YaHei";
                                                             font-weight:400;
                                                             color:rgba(32,32,32,1);
                                                             background:rgba(239,240,245,1);
                                                             border-top-right-radius:%2px;
                                                         })").arg((int)(g_appInfoPtr->m_fRate*14)).arg((int)(g_appInfoPtr->m_fRate*8)));
        }
        else
        {
            ui->btn_studentCodeLogin->setStyleSheet(QString(R"(QPushButton
                                                            {
                                                                outline:none;
                                                                font-size:%1px;
                                                                font-family:"Microsoft YaHei";
                                                                font-weight:400;
                                                                color:rgba(153,153,153,1);
                                                                background:rgba(239,240,245,1);
                                                                border:0px;
                                                                border-top-left-radius:%2px;
                                                            })").arg((int)(g_appInfoPtr->m_fRate*14)).arg((int)(g_appInfoPtr->m_fRate*8)));
            ui->btn_identityLogin->setStyleSheet(QString(R"(QPushButton
                                                         {
                                                             outline:none;
                                                             font-size:%1px;
                                                             font-family:"Microsoft YaHei";
                                                             font-weight:400;
                                                             color:rgba(255,255,255,1);
                                                             background:rgba(19,187,138,1);
                                                             border-top-right-radius:%2px;
                                                         })").arg((int)(g_appInfoPtr->m_fRate*14))
                                                        .arg((int)(ui->btn_studentCodeLogin->isVisible() ? g_appInfoPtr->m_fRate*8 : 0)));
        }
    }


}

void login::on_btn_close_clicked()
{
    close();
}

void login::onStudentClientConfig(CStudentClientConfig studentClientConfig)
{
	if (studentClientConfig.nCode == 200)
	{
		ui->btn_studentCodeLogin->setVisible(false);
		ui->btn_identityLogin->setVisible(false);
		if (studentClientConfig.bStudentCodeLogin )
		{
            ++m_nloginTypeCount;
			ui->btn_studentCodeLogin->setVisible(true);
			ui->btn_studentCodeLogin->setText(studentClientConfig.sStudentCodeLoginAlias);
			m_loginType = LOGIN_TYPE::lt_studentCode;
		}
		else
		{
			m_loginType = LOGIN_TYPE::lt_identity;
		}

		if (studentClientConfig.bIdentifyNumberLogin)
		{
            ++m_nloginTypeCount;
			ui->btn_identityLogin->setVisible(true);
			ui->btn_identityLogin->setText(studentClientConfig.sIdentityNumberLoginAlias);
		}
		
        ui->label_loginTitle->setText(studentClientConfig.sOeStudentSysName);
		g_appInfoPtr->m_bDisableMutiScreen = studentClientConfig.bDisableMutiScreen;
		g_appInfoPtr->m_bDisableRemoteAssistance = studentClientConfig.bDisableRemoteAssistance;
		g_appInfoPtr->m_bFullScreenTop = studentClientConfig.bFullScreenTop;
		g_appInfoPtr->m_bDisableVirtualCamera = studentClientConfig.bDisableVirtualCamera;
		g_appInfoPtr->m_sRootOrgId = studentClientConfig.sRootOrgId;
		g_appInfoPtr->m_bShowQmthLogo = studentClientConfig.bShowQmthLogo;
		g_appInfoPtr->m_bShowStudentClientAppQrcode = studentClientConfig.bShowStudentClientAppQrcode;

        g_appInfoPtr->m_bShowStudentName = studentClientConfig.bShowStudentName;
        g_appInfoPtr->m_bShowStudentCode = studentClientConfig.bShowStudentCode;
        g_appInfoPtr->m_bShowStudentIdentity = studentClientConfig.bShowStudentIdentity;

        if(studentClientConfig.bIsCustomMenuLogo)
        {
            g_appInfoPtr->m_sMenuLogoUrl = studentClientConfig.sCusMenuLogoFileUrl;
        }  

		initUI();

		if (!studentClientConfig.sStudentClientBgPictureUrl.isEmpty())
		{
			m_sStudentClientBgPictureUrl = studentClientConfig.sStudentClientBgPictureUrl;
			QString sFileName = m_sStudentClientBgPictureUrl.right(m_sStudentClientBgPictureUrl.length() - m_sStudentClientBgPictureUrl.lastIndexOf("/") - 1);
			sFileName = g_appInfoPtr->m_sCacheFileDir + sFileName;
			CHttpRequestPackage hrp;
			hrp.sUri = studentClientConfig.sStudentClientBgPictureUrl;
			hrp.sCommonStr = sFileName;
			hrp.sAdditionStr = "downloadAnswerSheet";
			hrp.sCommonStr1 = __FILE__;
			hrp.nRequestType = RequestType::rtDownLoadFile;
			hrp.nRetryCount = 3;
			g_httpBllPtr->downLoad(hrp);
		}

		if (!studentClientConfig.sLogoFileUrl.isEmpty())
		{
			m_sLogoFileUrl = studentClientConfig.sLogoFileUrl;
			QString sFileName = m_sLogoFileUrl.right(m_sLogoFileUrl.length() - m_sLogoFileUrl.lastIndexOf("/") - 1);
			sFileName = g_appInfoPtr->m_sCacheFileDir + sFileName;
			CHttpRequestPackage hrp;
			hrp.sUri = studentClientConfig.sLogoFileUrl;
			hrp.sCommonStr = sFileName;			
			hrp.sCommonStr1 = __FILE__;
			hrp.nRequestType = RequestType::rtDownLoadFile;
			hrp.nRetryCount = 3;
			g_httpBllPtr->downLoad(hrp);
		}
		
#ifdef _DEBUG
        g_appInfoPtr->m_bFullScreenTop = false;
#endif // _DEBUG

        if(g_appInfoPtr->m_bFullScreenTop)
        {
            CCommonTools::topMostSlot(this, true);
            
            g_keyBoardHookPtr = std::make_shared<CKeyBoardHook>();
            g_keyBoardHookPtr->Hotkey_Install(0);

            HWND task = nullptr;
            task=FindWindow(L"Shell_TrayWnd",nullptr);
            if(task)
            {
                ShowWindow(task,SW_HIDE);//隐藏任务栏
            }

            g_windowsFireWallPtr = std::make_shared<CWindowsFireWall>(_getpid());
        }
  
        
		
	}
	else
	{
        ShowMsg(QString::fromLocal8Bit("获取系统参数失败，请检查网络连接！"), this, MSG_ICON_TYPE::mit_error);
		if (m_pLoading != nullptr)
		{
			m_pLoading.reset();
		}
        QTimer::singleShot(3000, this, [&](){close();});
	}
}

void login::on_btn_login_clicked()
{
	if (ui->btn_studentCodeLogin->text().isEmpty() ||
		ui->btn_identityLogin->text().isEmpty())
	{
        ShowMsg(QString::fromLocal8Bit("请填写账号和密码"), this, MSG_ICON_TYPE::mit_error);
		return;
	}

    ui->btn_login->setEnabled(false);
    m_nRetryCount = 0;
	//登录限流
	CHttpRequestPackage hrp;
	hrp.sUri = QString("https://tcc.qmth.com.cn/rate_limit/prod/login/%1").arg(500);
	hrp.nRequestType = RequestType::rtLoginLimit;    
	g_httpBllPtr->getUrl(hrp);
   	
}

void login::onLoginLimit(CLoginLimit loginLimit)
{
	if (loginLimit.nCode == 200)
	{
        ++m_nRetryCount;
		if (loginLimit.bPass)
		{
			//登录
			CHttpRequestPackage hrp;
			hrp.sUri = "/api/ecs_core/client/login";
			hrp.nRequestType = RequestType::rtLogin;
			hrp.eParamType = HttpParamType::hptBody;
			hrp.sParamList.push_back(QString::fromLocal8Bit("accountValue,%1").arg(ui->edt_account->text()));
			hrp.sParamList.push_back(QString::fromLocal8Bit("password,%1").arg(ui->edt_password->text()));
			hrp.sParamList.push_back(QString::fromLocal8Bit("accountType,%1").arg(m_loginType == LOGIN_TYPE::lt_studentCode ? "STUDENT_CODE": "STUDENT_IDENTITY_NUMBER"));
			hrp.sParamList.push_back(QString::fromLocal8Bit("rootOrgId,%1").arg(g_appInfoPtr->m_sRootOrgId));
			g_httpBllPtr->post(hrp);
		}
        else
		{
			//等待重试
            if(m_nRetryCount >= 3)
            {
                ShowMsg(QString::fromLocal8Bit("系统繁忙，请稍后重试"), this, MSG_ICON_TYPE::mit_error);
                ui->btn_login->setEnabled(true);
            }
            else
            {
                QTimer::singleShot(3000, this, [](){
                    //登录限流
                    CHttpRequestPackage hrp;
                    hrp.sUri = QString("https://tcc.qmth.com.cn/rate_limit/prod/login/%1").arg(500);
                    hrp.nRequestType = RequestType::rtLoginLimit;
                    g_httpBllPtr->getUrl(hrp);
                });
            }
		}
	}
	else
    {
        if(loginLimit.sMessage.isEmpty())
        {
            ShowMsg(QString::fromLocal8Bit("登录失败"), this, MSG_ICON_TYPE::mit_error);
        }
        else
        {
            ShowMsg(loginLimit.sMessage, this, MSG_ICON_TYPE::mit_error);
        }
        ui->btn_login->setEnabled(true);
	}
}

void login::onTokenExpired()
{
   if(m_pCourseList != nullptr)
   {
       m_pCourseList.reset();
   }

   if (m_pLoading != nullptr)
   {
       m_pLoading.reset();
   }

   ShowMsg(QString::fromLocal8Bit("登录失效，请重新登录"), this, MSG_ICON_TYPE::mit_error);
}

void login::onLoginInfo(CLoginInfo loginInfo)
{
    ui->btn_login->setEnabled(true);

	if (loginInfo.nCode == 200)
	{
		g_appInfoPtr->m_nStudentId = loginInfo.nUserId;
        g_appInfoPtr->m_sRootOrgId = QString::number(loginInfo.nRootOrgId);
        g_appInfoPtr->m_sRootOrgName = loginInfo.sRootOrgName;
		if (m_pCourseList == nullptr)
		{
			m_pCourseList = std::make_shared<courseList>(this);
			connect(m_pCourseList.get(), &courseList::minisize, this, [&]() {showMinimized(); });
		}

		m_pCourseList->show();
		ui->edt_account->setText("");
		ui->edt_password->setText("");
	}
	else
	{
		if (loginInfo.sMessage != "")
		{
            ShowMsg(loginInfo.sMessage, this, MSG_ICON_TYPE::mit_error);
		}
		else
		{
            ShowMsg(QString::fromLocal8Bit("登录失败"), this, MSG_ICON_TYPE::mit_error);
		}
	}
}

void login::onLogout(CLogout )
{
	if (m_pCourseList !=nullptr)
	{
		m_pCourseList.reset();
	}
}

void login::on_btn_studentCodeLogin_clicked()
{
    m_loginType = LOGIN_TYPE::lt_studentCode;
    setBtnStyle();
}

void login::on_btn_identityLogin_clicked()
{
    m_loginType = LOGIN_TYPE::lt_identity;
    setBtnStyle();
}

void login::onDownLoadFile(CDownLoadFileInfo downLoadFileInfo)
{
	if (downLoadFileInfo.sModuleName == __FILE__)
	{
		if (downLoadFileInfo.nCode == 200)
		{
			QString sLogoFileName = m_sLogoFileUrl.right(m_sLogoFileUrl.length() - m_sLogoFileUrl.lastIndexOf("/") - 1);
			sLogoFileName = g_appInfoPtr->m_sCacheFileDir + sLogoFileName;
			QString sClientBgPictureFileName = m_sStudentClientBgPictureUrl.right(m_sStudentClientBgPictureUrl.length() - m_sStudentClientBgPictureUrl.lastIndexOf("/") - 1);
			sClientBgPictureFileName = g_appInfoPtr->m_sCacheFileDir + sClientBgPictureFileName;
			if (sLogoFileName == downLoadFileInfo.sFileName)
			{
				ui->label_org_logo->setPixmap(QPixmap(sLogoFileName).scaled(ui->label_org_logo->width(), ui->label_org_logo->height(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
			}

			if (sClientBgPictureFileName == downLoadFileInfo.sFileName)
			{
				ui->label_org_bg->setPixmap(QPixmap(sClientBgPictureFileName).scaled(ui->label_org_bg->width(), ui->label_org_bg->height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
			}
		}
	}
}
