#include "CFrameWnd.h"
#include"MixpanelScript.h"

void CFrameWnd::InitInstallingControls()
{
	thread installingThread(Thread_LoadedBanner, m_threadData);
	installingThread.detach();
}

/// <summary>
/// 安装中界面控件绑定事件
/// </summary>
void CFrameWnd::NotifyInstalling(TNotifyUI& msg)
{
}

LRESULT CFrameWnd::InstallingMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	LRESULT lRes = 0;
	BOOL bHandled1 = TRUE;

	if (m_pm.MessageHandler(uMsg, wParam, lParam, lRes)) return lRes;
	return CWindowWnd::HandleMessage(uMsg, wParam, lParam);
}

//Todo:安装过程的逻辑还是会有些乱，还会有重复的代码，以后再进行优化
void CFrameWnd::Thread_Installing(ThreadData threadData)
{
	if (threadData.pFrame->banner->IsEmptyBanner == true)
	{
		thread installingThread(CFrameWnd::Thread_LoadedBanner, threadData);
		installingThread.detach();
	}


	//下载安装前，安装路径过长问题
	if (DiskCore::IsMeetInstallPathMaxLength(true) == false)
	{
		threadData.pFrame->KillAllTimer();
		if (MSGID_OK == MessageBoxWnd::Show(threadData.pFrame->m_hWnd, MessageContentType::LongInstallingPath))
		{
			DownloadProgress::Currentpercentage = 0;
			threadData.pFrame->SelectLayout(LayoutType::Home);
			return;//直接返回是为了避免IsExistFile判断无效；

		}
		else
		{
			wstring installPackgeAbePath = PathCore::smPath_Install + L"\\" + Product::smName_InstallPackage;
			PathCore::smPath_Install = PathCore::smPath_DefaultInstall;
			threadData.pFrame->StartTimer(Timer_Installing_ID);
			threadData.pFrame->StartTimer(Timer_Banner_ID);

		}
	}


	CDownLoadFile downLoadFile;
	bool isDownloadSuccess = false;
	CFrameWnd::m_SilenceInstallingType = SilenceInstallingType::DownLoading;
	//1.下载
	isDownloadSuccess = downLoadFile.GetInstallPackage(PathCore::smPath_Install.c_str());

	//2.下载失败
	if (isDownloadSuccess == false)
	{
		//TODO：检查是否是代理服务器问题，已确认初版隐藏掉该需求，不可删除以下这段代码
		//若要使用，可以恢复以下代码，修改弹窗提示内容便可；
		//2.1下载失败，代理服务器问题
		//if (NetWorkState::IsProxyNetError())
		//{
		//	if (MSGID_OK == MessageBoxWnd::Show(threadData.pFrame->m_hWnd, MessageContentType::ProxyNetError))
		//	{
		//	//打开系统“Internet选项”-“连接”界面，引导用户，在“局域网设置”界面，取消勾选LAN代理，或者重新填写可用的代理服务器
		//		ShellExecute(0, L"open", L"rundll32.exe", L"inetcpl.cpl,LaunchConnectionDialog", NULL, SW_SHOWDEFAULT);
		//	}
		//	threadData.pFrame->KillAllTimer();
		//	DownloadProgress::Currentpercentage = 0;
		//	threadData.pFrame->SelectLayout(LayoutType::Home);
		//	return;
		//}  

		//2.1下载失败，安装路径过长问题
		if (DiskCore::IsMeetInstallPathMaxLength(true) == false)
		{
			threadData.pFrame->KillAllTimer();
			if (MSGID_OK == MessageBoxWnd::Show(threadData.pFrame->m_hWnd, MessageContentType::LongInstallingPath))
			{
				DownloadProgress::Currentpercentage = 0;
				threadData.pFrame->SelectLayout(LayoutType::Home);
				return;//直接返回是为了避免IsExistFile判断无效；

			}
			else
			{
				wstring installPackgeAbePath = PathCore::smPath_Install + L"\\" + Product::smName_InstallPackage;
				PathCore::smPath_Install = PathCore::smPath_DefaultInstall;
				threadData.pFrame->StartTimer(Timer_Installing_ID);
				threadData.pFrame->StartTimer(Timer_Banner_ID);
				DownloadProgress::Currentpercentage = 0;
				isDownloadSuccess = downLoadFile.GetInstallPackage(PathCore::smPath_Install.c_str());
			}
		}

	}

	//2.3下载失败，网络断网问题
	if (isDownloadSuccess == false)
	{
		CFrameWnd::m_SilenceInstallingType = SilenceInstallingType::DownLoadNoNetWork;
		threadData.pFrame->m_InstallingPage->NetWorkUI(false);
		threadData.pFrame->WaitForNetwork();
		return;
	}

	CCmd cmd;
	bool IsNeedInstallNet = false;
	//3.若缺少NET Framework框架，则优先安装
	if (threadData.pFrame->m_State.m_NetFrameworkType == InstallNetFrameworkType::V40_46)
	{
		cmd.InstallNetcmd();
		IsNeedInstallNet = true;
	}

	//3.若缺少Vc++环境，则优先安装,目前以使用vcruntime140.dll来配置，配置环境逻辑注释掉
	/*if (threadData.pFrame->m_State.m_VcPlusPlusType != InstallVCPlusPlusType::V14_3)
	{
		cmd.InstallVcPlusPluscmd();
	}*/

	//4.静默安装产品
	threadData.pFrame->StartTimer(Timer_SilentInstall_ID);
	int error = cmd.Installcmd();
	if (error)
	{
		//如果安装失败，有可能是安装路径太长的问题，此处指令并不会返回失败的值；所以需要做个判断，是否需要返回安装前的页面
		//4.1 静默安装产品，若因为路径过长，安装失败
		if (DiskCore::IsMeetInstallPathMaxLength(false) == false)
		{
			threadData.pFrame->KillAllTimer();
			if (MSGID_OK == MessageBoxWnd::Show(threadData.pFrame->m_hWnd, MessageContentType::LongInstallingPath))
			{
				DownloadProgress::Currentpercentage = 0;
				threadData.pFrame->m_InstallingPage->SetProgressValue(0);
				threadData.pFrame->SelectLayout(LayoutType::Home);
				return;//直接返回是为了避免IsExistFile判断无效；

			}
			else
			{
				wstring installPackgeAbePath = PathCore::smPath_Install + L"\\" + Product::smName_InstallPackage;
				PathCore::smPath_Install = PathCore::smPath_DefaultInstall;
				FileCore::SourceFileMoveToDestionPath(installPackgeAbePath, PathCore::smPath_DefaultInstall);
				if (cmd.Installcmd() == false)
				{
					if (FileCore::IsExistProductAppPath() == false)
					{
						cmd.GetVBA_UTF8();
					}

					DownloadProgress::Currentpercentage = 0;
					threadData.pFrame->m_InstallingPage->SetProgressValue(0);
					threadData.pFrame->KillAllTimer();
				}
			}

		}
		else if (FileCore::IsExistProductAppPath() == false)
		{
			MixpanelScript* mix = new MixpanelScript();
			std::string GUID = mix->GetGUID();
			std::string CPUID = mix->GetCPUID();
			mix->PostData("InstallError_Trig_Reason", CPUID, GUID, error);


			//4.2 静默安装产品，若因为未知原因安装失败，则弹出安装路径，让用户进行手动安装
			if (MSGID_OK == MessageBoxWnd::Show(threadData.pFrame->m_hWnd, MessageContentType::InstallingFailed))
			{
				wstring folderPath = L"explorer.exe     \"" + PathCore::smPath_Install + L"\"";
				char* ch = CharConvert::GetWstringToCharPtr(folderPath);
				mix->PostData("InstallError_Btn_Continue", CPUID, GUID, error);
				system(ch);
			}
			else
			{
				mix->PostData("InstallError_Btn_Close", CPUID, GUID, error);
			}
		}

		threadData.pFrame->SelectLayout(LayoutType::Installed);
		std::wstring path = L"";
		path = CLanguage::GetText(TextType::Btn_GoToFilesPath).c_str() + PathCore::smPath_Install;
		threadData.pFrame->m_InstalledPage->RefreshInstalledPath(path);

	}

	DownloadProgress::Currentpercentage = 0;
	threadData.pFrame->KillAllTimer();

	if (cmd.m_IsWin8InstallNet && IsNeedInstallNet)
	{
		threadData.pFrame->IsNeedReStartSystem = true;
		threadData.pFrame->ReStartSystem();

	}
}


void CFrameWnd::SetTimerSilen()
{
	srand(time(0));
	auto randnum = rand() % (4 - 1 + 2) + 1;

	int dprogress = (int)(DownloadProgress::Currentpercentage + randnum) * 0.7;

	if (DownloadProgress::Currentpercentage < 143)
		DownloadProgress::Currentpercentage = DownloadProgress::Currentpercentage + randnum;

	if (dprogress > 99)
	{
		dprogress = 99;
	}
	m_InstallingPage->SetProgressValue(dprogress);
}

void CFrameWnd::SetTimerInstalling()
{
	try
	{
		m_InstallingPage->NetWorkUI(NetWorkState::IsNetWorking());
	}
	catch (const std::exception&)
	{

	}

	if (CFrameWnd::m_SilenceInstallingType == SilenceInstallingType::DownLoading)
	{
		int dprogress = (int)DownloadProgress::Currentpercentage * 0.7;
		if (dprogress > 99)
		{
			dprogress = 99;
		}

		m_InstallingPage->SetProgressValue(dprogress);
	}
	else if (CFrameWnd::m_SilenceInstallingType == SilenceInstallingType::Installed)
	{
		m_InstallingPage->SetProgressValue(100);
	}
	else if (CFrameWnd::m_SilenceInstallingType == SilenceInstallingType::Installing || CFrameWnd::m_SilenceInstallingType == SilenceInstallingType::DownLoadSuccess)
	{

	}
	else if (CFrameWnd::m_SilenceInstallingType == SilenceInstallingType::DownLoadNoNetWork)
	{

	}

}
