MainFrm.cpp 28.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010

// MainFrm.cpp : implementation of the CMainFrame class
//

#include "stdafx.h"

#include "MainFrm.h"

#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <exception>

#include <boost/filesystem.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

//#include "etradeclient/boost_patch/property_tree/json_parser.hpp" // WARNIING! Make sure to include our patched version.
#include "etradeclient/mfc_ui/LoginDialog.h"
#include "etradeclient/mfc_ui/PopupBrowserDlgView.h"
#include "etradeclient/mfc_ui/ConfigDialog.h"

#include "etradeclient/utility/session.h"
#include "etradeclient/utility/logon_mgr.h"
#include "etradeclient/browser/browser_util.h"
#include "etradeclient/utility/logging.h"
#include "etradeclient/utility/application_config.h"
#include "etradeclient/utility/win_msg_define.h"
#include "etradeclient/utility/url_config.h"
#include "etradeclient/utility/string_converter.h"
#include "DialogConfig.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

namespace fs = boost::filesystem;

const int NOTICEEDIT_LEFTSPACE = 5;
const int NOTICEEDTT_RIGHTSPACE = 5;
const int SHOPNAMESTATIC_WEIGHT = 100;
const int SHOPNAMESTATIC_HEIGHT = 20;

const int MENU_BUTTON_WIDTH = 90;
const int MENU_BUTTON_HEIGHT = 40;



namespace
{
	static const uint32_t MENU_ICON_WIDTH = 32, MENU_ICON_HEIGHT = 32;
	static const uint32_t TOOLBAR_ICON_WIDTH = 32, TOOLBAR_ICON_HEIGHT = 32;

	static const std::string JSON_TAG_CODE = "code";
	static const std::string JSON_TAG_MSG = "message";
	static const std::string JSON_VAL_SUCC = "success";

	enum ToolBarBtnID // Cannot use enum class due to TBBUTTON asks for integer.
	{
		HOME_PAGE	 = 4000,
		RELOAD		 = 4001,
		USER_MESSAGE = 4002,
		USER_ACCOUNT = 4003,
	};

	// Use relative path.
	static const std::wstring TOOLBAR_ICON_FOLDER(L".\\Resource\\Toolbar\\"); // Use 'wstring' because MFC ask for this.
	static const std::wstring MENU_ICON_FOLDER = L".\\Resource\\Menu\\";

	static std::vector<TBBUTTON> kQuickAccessBtn =
	{
		{ 0, ID_SETTLE_PAY,					TBSTATE_ENABLED, BTNS_BUTTON, 0, 0 },
		{ 1, ID_GOOD_STORAGE,				TBSTATE_ENABLED, BTNS_BUTTON, 0, 0 },
		{ 2, ID_DISTRIBUTE_MANAGE_FINANCE,	TBSTATE_ENABLED, BTNS_BUTTON, 0, 0 },
		{ 3, ID_CREDIT_SALE_PAY,			TBSTATE_ENABLED, BTNS_BUTTON, 0, 0 }
	};
} // namespace

// CMainFrame

IMPLEMENT_DYNAMIC(CMainFrame, CFrameWnd)

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
	ON_WM_CREATE()
	ON_WM_SETFOCUS()
	ON_WM_CLOSE()
	ON_WM_MEASUREITEM()
	ON_WM_DRAWITEM()
	ON_WM_INITMENUPOPUP()

	ON_NOTIFY(TBN_DROPDOWN, AFX_IDW_TOOLBAR, OnToolbarDropDown)
	ON_COMMAND(ID_EXIT, OnExit)
	ON_COMMAND(ID_MODIFY_PASSWORD, OnModifyPwd)
	ON_COMMAND(ID_MODIFY_CONFIG, OnModifyConfig)
	ON_UPDATE_COMMAND_UI(USER_MESSAGE, &CMainFrame::OnUpdateToolBarMsgCount)

	ON_COMMAND_RANGE(ID_SETTLE_PAY, ID_MENU_REPORT, OnMenuBtnClicked)
	ON_COMMAND_RANGE(HOME_PAGE, USER_ACCOUNT, OnToolBarBtnClicked)
	
	ON_MESSAGE(WM_CEF_SESSION_EXPIRED, OnSessionExpired)
	ON_MESSAGE(WM_UPDATE_USER_MSG_COUNT,OnGotMsgCount)
	ON_WM_GETMINMAXINFO()

	ON_MESSAGE(WM_CRASH_CLOSE, OnCrashClose)

	ON_WM_SIZE()
	ON_WM_TIMER()
	ON_WM_CTLCOLOR()
END_MESSAGE_MAP()

static UINT indicators[] =
{
	ID_SEPARATOR,           // status line indicator
	ID_INDICATOR_CAPS,
	ID_INDICATOR_NUM,
	ID_INDICATOR_SCRL,
};

// CMainFrame construction/destruction

CMainFrame::CMainFrame() : m_is_view_closing(false), m_msg_count(0), m_DefaultColor(0)
{}

CMainFrame::~CMainFrame()
{}

bool CMainFrame::Launch()
{
	auto& url_cfg = URLConfig::Instance();
	if (m_view.CreateBrowser(url_cfg.FullHost() + url_cfg.MainPath()))
	{
		m_user_msg_monitor.Start(); // Start the user msg monitor to monitor user msg update.
		return true;
	}
	LOG_ERROR(L"创建浏览器失败!");// Create main browser failed!

	if (!LogonMgr::Instance().DoLogout())
		LOG_ERROR(L"服务端退出请求处理失败。");
	else
		LOG_TRACE(L"退出系统成功。");

	return false;
}

void CMainFrame::UpdateStatus(LPCTSTR status)
{
#if 0
	m_status_bar.SetPaneText(0, status);
#endif
}

void CMainFrame::DoCreatMerchant()
{
	m_user_msg_monitor.Stop(); // Stop monitoring before launching the password modification dialog.
	RECT rect;
	GetWindowRect(&rect);
	CCreateMerchantView(rect).DoModal();
	m_user_msg_monitor.Start(); // Recover monitoring.
}

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
	if( !CFrameWnd::PreCreateWindow(cs) )
		return FALSE;
	// TODO: Modify the Window class or styles here by modifying
	//  the CREATESTRUCT cs

	cs.style = WS_OVERLAPPED | WS_CAPTION | FWS_ADDTOTITLE
		 | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_MAXIMIZE | WS_SYSMENU;

	cs.dwExStyle &= ~WS_EX_CLIENTEDGE;
	cs.lpszClass = AfxRegisterWndClass(0);
	return TRUE;
}

BOOL CMainFrame::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo)
{
	// let the view have first crack at the command
	if (m_view.OnCmdMsg(nID, nCode, pExtra, pHandlerInfo))
		return TRUE;

	// otherwise, do default handling
	return CFrameWnd::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);
}

// CMainFrame diagnostics
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
	CFrameWnd::AssertValid();
}

void CMainFrame::Dump(CDumpContext& dc) const
{
	CFrameWnd::Dump(dc);
}
#endif //_DEBUG

// CMainFrame message handlers

int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	do
	{
		if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
			break;
		if (!m_menu_res_auth_manager.UpdateAuth())
			break;
		if (!LogonMgr::Instance().IsFirstLogin())
		{
			if (!FilterMenuBar())
				break;
			if (!FilterQuickAccessToolBar())
				break;
		}
		if (!CreateMainFrmUI())
			break;
		
		if (!CreateNoticeEdit())
		{
			break;
		}

		/*if (!CreateShopNameStatic())
		{
			break;
		}*/
		if (!CreateToolTip())
		{
			break;
		}

		

		return 0; // Return 0 if all succeed.
	} while (0);
	return -1; // Return -1 to indicate error happens.
}

BOOL CMainFrame::CreateNoticeEdit()
{
	//m_dlgNotice.Create(IDD_DIALOG_NOTICEWND, this);
	//m_dlgNotice.ShowWindow(SW_HIDE);
	SetNoticeEditPos();
	//m_dlgNotice.SetWindowText(m_cNoticeManage.GetNotice());
	//SetTimer(1, 180000, NULL);

	return TRUE;
}

//BOOL CMainFrame::CreateShopNameStatic()
//{
//	m_staticShopName.Create(Session::Instance().GetMerName().c_str(), WS_CHILD | WS_VISIBLE | SS_NOTIFY  /*DT_SINGLELINE |*//* DT_LEFT*/ /* DT_VCENTER*/,
//		CRect(0, 0, 10, 10), this, IDC_STATIC_SHOPNAME);
//	if (IsSystemWin7())
//	{
//		m_DefaultColor = RGB(211, 218, 237);
//	}
//	else
//	{
//		CDC *pDC = m_staticShopName.GetDC();
//		m_DefaultColor = pDC->GetBkColor();
//	}
//
//	CFont *pFontStatic = new CFont;
//	pFontStatic->CreatePointFont(100, L"微软雅黑");
//	m_staticShopName.SetFont(pFontStatic);
//
//	SetShopNameStaticPos();
//	return TRUE;
//}

//void CMainFrame::SetShopNameStaticPos()
//{
//	CRect rtButton;
//	m_ex_func_tlb.GetItemRect(0, &rtButton);
//	m_ex_func_tlb.ClientToScreen(&rtButton);
//	ScreenToClient(&rtButton);
//	int iY = rtButton.top + (rtButton.Height() - SHOPNAMESTATIC_HEIGHT) / 2;
//	m_staticShopName.MoveWindow(rtButton.left, iY, rtButton.Width(), SHOPNAMESTATIC_HEIGHT);
//
//	Invalidate();
//}

void CMainFrame::SetNoticeEditPos()
{
	CRect rtMenu;
	CRect rtButton;

	int iButtonCount = m_quick_access_tlb.GetToolBarCtrl().GetButtonCount();
	m_quick_access_tlb.GetItemRect(iButtonCount - 1, &rtButton);
	m_quick_access_tlb.ClientToScreen(&rtButton);
	ScreenToClient(&rtButton);
	int iNoticeLeft = rtButton.right + NOTICEEDIT_LEFTSPACE;
	int iNoticeHeight = rtButton.Height();
	int iNoticeTop = rtButton.top;

	m_ex_func_tlb.GetWindowRect(&rtMenu);
	ScreenToClient(&rtMenu);
	int iNoticeWidth = rtMenu.left - NOTICEEDTT_RIGHTSPACE - iNoticeLeft/* - SHOPNAMESTATIC_WEIGHT*/;

	//m_dlgNotice.MoveWindow(iNoticeLeft, iNoticeTop, iNoticeWidth, iNoticeHeight);
	//m_dlgNotice.ReSizeEdit();
}

BOOL CMainFrame::CreateToolTip()
{
	m_cTip.Create(this, TTS_ALWAYSTIP | WS_POPUP);
	m_cTip.Activate(TRUE);
	m_cTip.AddTool(&m_ex_func_tlb, /*L"this is a tip!!!!"*/Session::Instance().GetMerName().c_str());
	m_cTip.SetDelayTime(TTDT_INITIAL, 100);
	m_cTip.SetDelayTime(TTDT_AUTOPOP, 10000);

	return TRUE;
}

void CMainFrame::OnClose()
{
	if (!m_is_view_closing)
	{
		if (!Session::Instance().IsExpired()) // Only prompt notification in logged in state.
		{
			LOG_TRACE(L"退出系统确认。");
			if (IDNO == MessageBox(L"您确定要退出并关闭程序吗?", L"退出系统提示!", MB_YESNO | MB_ICONEXCLAMATION))
				return;
			if (!LogonMgr::Instance().DoLogout())
			{
				MessageBox(L"退出系统失败,若无法重新登录请联系维护人员!", L"退出系统提示!", MB_OK | MB_ICONWARNING);
				LOG_ERROR(L"服务端退出请求处理失败。程序关闭。");
			}
			else
				LOG_TRACE(L"退出系统成功。");
		}
		/* Request CETradeClientView to close.this will make view to exit cef,
		 and cef will send wm_close message to this fram window.*/
		m_view.SendMessage(WM_CLOSE); 
		m_is_view_closing = true; // Enable next time close.
		return; // And cancel this close.
	}
	m_user_msg_monitor.Stop();
	LOG_TRACE(L"程序关闭。");

	CFrameWnd::OnClose();
}

void CMainFrame::OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct)
{
	do
	{
		if ((lpMeasureItemStruct == NULL) || (lpMeasureItemStruct->CtlType != ODT_MENU))
			break; // Don't handle items other than menu.
		const uint32_t kIconWidth = 24, kIconHeight = 24; // This is the most suitable size for showing a icon.
		lpMeasureItemStruct->itemWidth = kIconWidth;
		lpMeasureItemStruct->itemHeight = kIconHeight;
	} while (0);
	CFrameWnd::OnMeasureItem(nIDCtl, lpMeasureItemStruct);
}

void CMainFrame::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct)
{
	static const int32_t OFFSET_LEFT = -6, OFFSET_TOP = -4; // This is the most suitable size.
	do
	{
		if ((lpDrawItemStruct == NULL) || (lpDrawItemStruct->CtlType != ODT_MENU))
			break; // Don't handle items other than menu.

		::DrawIconEx(lpDrawItemStruct->hDC, lpDrawItemStruct->rcItem.left + OFFSET_LEFT, lpDrawItemStruct->rcItem.top + OFFSET_TOP,
			m_authorized_menu_icons[lpDrawItemStruct->itemID], MENU_ICON_WIDTH, MENU_ICON_HEIGHT, 0, NULL, DI_NORMAL);
	} while (0);

	CFrameWnd::OnDrawItem(nIDCtl, lpDrawItemStruct);
}

void CMainFrame::OnInitMenuPopup(CMenu* pMenu, UINT nIndex, BOOL bSysMenu)
{
	CFrameWnd::OnInitMenuPopup(pMenu, nIndex, bSysMenu);

	if (bSysMenu)
		pMenu = GetSystemMenu(FALSE); // Allows the application to access the Control menu for copying and modification.

	//@{ Set menu style.
	MENUINFO mnfo;
	mnfo.cbSize = sizeof(mnfo);
	mnfo.fMask = MIM_STYLE;
	mnfo.dwStyle = MNS_CHECKORBMP | MNS_AUTODISMISS;
	pMenu->SetMenuInfo(&mnfo);
	//@}

	//@{ Set menu item attributes.
	MENUITEMINFO minfo;
	minfo.cbSize = sizeof(minfo);
	// Warning!!! Currently we have only 2 menu levels: top menu & sub menu.
	// So this algorithm is not general enough to handle a menu tree.
	// 
	for (int pos = 0; pos < pMenu->GetMenuItemCount(); ++pos)
	{
		minfo.fMask = MIIM_FTYPE | MIIM_ID;
		pMenu->GetMenuItemInfo(pos, &minfo, TRUE);
		int iID = minfo.wID;

		if (minfo.fType == MFT_SEPARATOR || minfo.wID == NULL) // Don't handle the separator.
		{
			minfo.fType = MFT_SEPARATOR;
			pMenu->SetMenuItemInfo(pos, &minfo, TRUE);
			continue;
		}
			

		if (!(minfo.fType & MFT_OWNERDRAW)) // If not a owner draw menu item.
		{
			minfo.fMask = MIIM_FTYPE | MIIM_BITMAP; // Indicates the members to be retrieved or set: the 'hbmpItem' member..
			// "HBMMENU_CALLBACK" indicates taht a bitmap that is drawn by the window that owns the menu. 
			// The application must process the WM_MEASUREITEM and WM_DRAWITEM messages.
			minfo.hbmpItem = HBMMENU_CALLBACK;
			minfo.fType = MFT_STRING; // Displays the menu item using a text string.
			pMenu->SetMenuItemInfo(pos, &minfo, TRUE);
		}
	}
	//@}
}

void CMainFrame::OnUpdateToolBarMsgCount(CCmdUI *pCmdUI)
{
	if (m_msg_count > 0)
		pCmdUI->Enable(true);
	else
		pCmdUI->Enable(false);
}

void CMainFrame::OnToolBarBtnClicked(UINT btn_id)
{
	auto& url_cfg = URLConfig::Instance();
	CString sLog;
	switch (btn_id)
	{
	case RELOAD:
		m_view.Browser().Reload();
		break;
	case HOME_PAGE:
		//add by liuye 2017.3.27
		sLog = _T("按钮id:HOME_PAGE");
		LOG_TRACE(sLog.GetBuffer());
		//
		m_view.Browser().NavigateTo(url_cfg.FullHost()+url_cfg.MainPath());
		break;
	case USER_MESSAGE:
		ShowUserMessageDlg();
		break;
	default:
		break;
	}
}

void CMainFrame::OnMenuBtnClicked(UINT btn_id)
{
	m_view.Browser().NavigateTo(MenuUrl(btn_id));
}

void CMainFrame::OnToolbarDropDown(NMHDR* pNMHDR, LRESULT* pResult)
{
	LPNMTOOLBAR tool_bar = reinterpret_cast<LPNMTOOLBAR>(pNMHDR);

	if (USER_ACCOUNT == tool_bar->iItem)
	{
		CMenu menu;
		menu.LoadMenu(IDR_ACCOUNT);
		CMenu*popup_menu = menu.GetSubMenu(0);
		ASSERT(popup_menu);

		CRect rc;
		m_ex_func_tlb.SendMessage(TB_GETRECT, tool_bar->iItem, (LPARAM)&rc);
		m_ex_func_tlb.ClientToScreen(&rc);
		popup_menu->TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_VERTICAL, rc.left, rc.bottom, this, &rc);
	}
}

void CMainFrame::OnExit()
{
	AfxGetMainWnd()->PostMessage(WM_CLOSE);
}

void CMainFrame::OnModifyPwd()
{
	LOG_TRACE(L"修改密码!");
	m_user_msg_monitor.Stop(); // Stop monitoring before launching the password modification dialog.
	RECT rect;
	GetWindowRect(&rect);
	CModifyPwdView(rect).DoModal();
	m_user_msg_monitor.Start(); // Recover monitoring.
}

void CMainFrame::OnModifyConfig()
{
	m_user_msg_monitor.Stop(); // Stop monitoring before launching the password modification dialog.
	//CConfigDialog().DoModal();
	CDialogConfig dlgConfig;
	dlgConfig.DoModal();//改用新的配置界面 add by liuye 2017.3.10
	m_user_msg_monitor.Start(); // Recover monitoring.
}

afx_msg LRESULT CMainFrame::OnSessionExpired(WPARAM wParam, LPARAM lParam)
{
	LOG_TRACE(_T("主界面登录超时!"));

	m_user_msg_monitor.Stop(); // First stop the user message monitoring.
	if (!CLoginDialog(L"当前连接已过期,请重新登录!", this).Launch())
	{
		OnExit();
		return 0;
	}
	Session::Instance().OnValid(); // If login succeeded, recover the session state to be "not expired".
	m_user_msg_monitor.Start(); // Start again after relogged in.
	return 0;
}

afx_msg LRESULT CMainFrame::OnGotMsgCount(WPARAM wParam, LPARAM lParam)
{
	m_msg_count = (int)wParam;
	return 0;
}

bool CMainFrame::FilterMenuBar()
{
	CWnd* main_wnd = AfxGetApp()->m_pMainWnd;
	CMenu* menu = main_wnd->GetMenu();

	// Remove unauthorized menu.
	// !!! Through reverse traversal, guarantee the index order will not disorderly when remove next menu item.
	MenuResAuthMgr::MenuItemsType::const_reverse_iterator criter;
	const auto& menu_items = m_menu_res_auth_manager.MenuItems();

	std::vector<uint32_t>::const_iterator menu_index_iter;
	for (criter = menu_items.crbegin(); criter != menu_items.crend(); ++criter)
	{
		if (!criter->second.is_authorized) // Remove those unauthorized menu items.
		{
			CMenu* sub_menu = menu;
			// Traverse to the parent menu of the leaf node menu(which has no more submenu).
			const auto& index_list = criter->second.index_list;
			if (index_list.empty())
				break;
			// " -1 " means only traverse to the leaf node's parent node. Then the iter will be directed to the lead node.
			// , then we can call "RemoveMenu(*menu_index_iter, MF_BYPOSITION)" to remove the leaf node.
			// This works the same to the top level menu.
			for (menu_index_iter = index_list.cbegin(); menu_index_iter != index_list.cend() - 1; ++menu_index_iter)
			{
				sub_menu = sub_menu->GetSubMenu(*menu_index_iter);
				if (NULL == sub_menu)
				{
					std::stringstream err_msg;
					err_msg << "菜单配置错误, menu resource id: " << criter->first << "; menu index: " << *menu_index_iter << "!";
					LOG_ERROR(str_2_wstr(err_msg.str()));
					break;
				}
			}

			// Here we only need to remove the sub menu, since web server will not return an empty parent menu which has none sub menu.

			if (NULL == sub_menu || !sub_menu->RemoveMenu(*menu_index_iter, MF_BYPOSITION))
				LOG_ERROR(L"移除未授权菜单失败, menu resource id = " + std::to_wstring(criter->first) + L"!");

		}
		else
		{
			auto sIconName = str_2_wstr(criter->second.icon_name);
			std::wstring file_path = MENU_ICON_FOLDER + str_2_wstr(criter->second.icon_name);
			if (!fs::exists(file_path))
			{
				LOG_ERROR(L"图片文件:" + file_path + L"不存在, 请检查!");
				break;
			}
			HICON hicon = (HICON)LoadImage(AfxGetResourceHandle(),
				file_path.c_str(), IMAGE_ICON, MENU_ICON_WIDTH, MENU_ICON_HEIGHT, LR_DEFAULTCOLOR | LR_LOADFROMFILE);

			auto ifirst = criter->first;
			auto MennuItem = criter->second;
			m_authorized_menu_icons.emplace(std::make_pair(criter->first, hicon));
			
			// 针对需要服务器端授权的菜单项,使用从服务器获取的菜单标题来更新菜单标题,
			// 对于无需服务器端授权的“本地菜单项”,则无需更新。
			if (!m_menu_res_auth_manager.IsLocalMenuItem(criter->first))
				menu->ModifyMenu(criter->first, MF_BYCOMMAND, criter->first, criter->second.remark.c_str());
		}
	}

	main_wnd->DrawMenuBar();
	return true;
}

bool CMainFrame::FilterQuickAccessToolBar()
{
	typedef MenuResAuthMgr::MenuItemsType MenuItemsT;
	const auto& menu_items = m_menu_res_auth_manager.MenuItems();
	int index = 0;
	for (auto iter = kQuickAccessBtn.begin(); iter != kQuickAccessBtn.end();)
	{
		MenuItemsT::const_iterator cit = menu_items.find(iter->idCommand);
		if (cit != menu_items.cend() && cit->second.is_authorized) // If found and authorized.
		{ 
			iter->iBitmap = index;// modify the icon index mapping.
			index++;
			++iter;
		}	
		else // If not found or unauthorized.
			iter = kQuickAccessBtn.erase(iter);
	}
	return true;
}

bool CMainFrame::CreateMainFrmUI()
{
	do
	{
		HICON frame_icon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
		// Specifies a 32 pixel by 32 pixel icon if TRUE; specifies a 16 pixel by 16 pixel icon if FALSE.
		SetIcon(frame_icon, TRUE); // Set big icon
		SetIcon(frame_icon, FALSE); // Set small icon
		// create a view to occupy the client area of the frame
		if (!m_view.Create(NULL, NULL, AFX_WS_DEFAULT_VIEW, CRect(0, 0, 0, 0), this, AFX_IDW_PANE_FIRST, NULL))
		{
			LOG_ERROR(L"Failed to create view window\n");
			break;
		}
		//@{
		if (!CreateWebNaviToolBar())
		{
			LOG_ERROR(L"Failed to create web navigation toolbar\n");
			break;      // fail to create
		}

		if (!CreateQuickAccessToolBar())
		{
			LOG_ERROR(L"Failed to create quick access toolbar\n");
			break;      // fail to create
		}

		if (!CreateExFuncToolBar())
		{
			LOG_ERROR(L"Failed to create extra function toolbar\n");
			break;      // fail to create
		}

		if (!m_re_bar.Create(this) ||
			!m_re_bar.AddBar(&m_web_navi_tlb_home_page,		NULL, NULL, RBBS_NOGRIPPER) ||
			!m_re_bar.AddBar(&m_web_navi_tlb_reload,		NULL, NULL, RBBS_NOGRIPPER) ||
			!m_re_bar.AddBar(&m_quick_access_tlb,			NULL, NULL, RBBS_NOGRIPPER) ||
			!m_re_bar.AddBar(&m_ex_func_tlb,				NULL, NULL, RBBS_NOGRIPPER))
		{
			LOG_ERROR(L"Failed to create rebar\n");
			break;      // fail to create
		}
		//@}

		m_re_bar.GetReBarCtrl().MaximizeBand(2);

		return true;
	} while (0);

	return false;
}

bool CMainFrame::CreateWebNaviToolBar()
{
	{// HOME_PAGE BUTTON
		const std::vector<std::wstring> kWebNaviIcon = { _T("home.ico")};
		std::vector<TBBUTTON> kWebNaviBtn = {
			{ 0, HOME_PAGE, TBSTATE_ENABLED, BTNS_BUTTON, 0, 0 } };

		if (!m_web_navi_tlb_home_page.CreateEx(this, TBSTYLE_TRANSPARENT))
			return false; // fail to create

		if (!m_web_navi_tlb_imgs_home_page.Create(TOOLBAR_ICON_WIDTH, TOOLBAR_ICON_HEIGHT, ILC_COLOR32 | ILC_MASK, 0, 0))
			return false;

		for (const auto& icon_name : kWebNaviIcon)
		{
			std::wstring file_path = TOOLBAR_ICON_FOLDER + icon_name;
			if (!fs::exists(file_path))
			{
				LOG_ERROR(L"图片文件:" + file_path + L"不存在, 请检查!");
				return false;
			}
			HICON icon = (HICON)LoadImage(
				AfxGetResourceHandle(), file_path.c_str(), IMAGE_ICON, TOOLBAR_ICON_WIDTH, TOOLBAR_ICON_HEIGHT, LR_DEFAULTCOLOR | LR_LOADFROMFILE);
			m_web_navi_tlb_imgs_home_page.Add(icon);
		}

		CToolBarCtrl& tbc = m_web_navi_tlb_home_page.GetToolBarCtrl();
		for (auto& btn : kWebNaviBtn)
			tbc.AddButtons(1, &btn);

		tbc.SetImageList(&m_web_navi_tlb_imgs_home_page);

		const uint32_t kPaddingWidth = 10;
		UpdateToolbarBtnSize(m_web_navi_tlb_home_page, kPaddingWidth); // Make sure to set toolbar button size after the button text has been set.
	}
	{// RELOAD BUTTON
		const std::vector<std::wstring> kWebNaviIcon = {_T("reload.ico") };
		std::vector<TBBUTTON> kWebNaviBtn = {
			{ 0, RELOAD, TBSTATE_ENABLED, BTNS_BUTTON, 0, 0 } };

		if (!m_web_navi_tlb_reload.CreateEx(this, TBSTYLE_TRANSPARENT))
			return false; // fail to create

		if (!m_web_navi_tlb_imgs_reload.Create(TOOLBAR_ICON_WIDTH, TOOLBAR_ICON_HEIGHT, ILC_COLOR32 | ILC_MASK, 0, 0))
			return false;

		for (const auto& icon_name : kWebNaviIcon)
		{
			std::wstring file_path = TOOLBAR_ICON_FOLDER + icon_name;
			if (!fs::exists(file_path))
			{
				LOG_ERROR(L"图片文件:" + file_path + L"不存在, 请检查!");
				return false;
			}
			HICON icon = (HICON)LoadImage(
				AfxGetResourceHandle(), file_path.c_str(), IMAGE_ICON, TOOLBAR_ICON_WIDTH, TOOLBAR_ICON_HEIGHT, LR_DEFAULTCOLOR | LR_LOADFROMFILE);
			m_web_navi_tlb_imgs_reload.Add(icon);
		}

		CToolBarCtrl& tbc = m_web_navi_tlb_reload.GetToolBarCtrl();
		for (auto& btn : kWebNaviBtn)
			tbc.AddButtons(1, &btn);

		tbc.SetImageList(&m_web_navi_tlb_imgs_reload);

		const uint32_t kPaddingWidth = 10;
		UpdateToolbarBtnSize(m_web_navi_tlb_reload, kPaddingWidth); // Make sure to set toolbar button size after the button text has been set.
	}
	return true;
}

bool CMainFrame::CreateQuickAccessToolBar()
{
	if (!m_quick_access_tlb.CreateEx(this, TBSTYLE_TRANSPARENT | TBSTYLE_LIST))
		return false; // fail to create
	if (!m_quick_access_tlb_imgs.Create(TOOLBAR_ICON_WIDTH, TOOLBAR_ICON_HEIGHT, ILC_COLOR32 | ILC_MASK, 0, 0))
		return false;
	
	CToolBarCtrl& tbc = m_quick_access_tlb.GetToolBarCtrl();
	tbc.SetImageList(&m_quick_access_tlb_imgs); // 注意这一句必须放在为“SetButtonText”和“UpdateToolbarBtnSize”之前,否则会出现宽度计算错误

	const auto& res_auth_map = m_menu_res_auth_manager.MenuItems();
	int index = 0;
	for (auto& btn : kQuickAccessBtn)
	{
		tbc.AddButtons(1, &btn);

		std::wstring file_path = TOOLBAR_ICON_FOLDER + str_2_wstr(res_auth_map.at(btn.idCommand).icon_name);
		if (!fs::exists(file_path))
		{
			LOG_ERROR(L"图片文件:" + file_path + L"不存在, 请检查!");
			return false;
		}
		HICON icon = (HICON)LoadImage(
			AfxGetResourceHandle(), file_path.c_str(), IMAGE_ICON, TOOLBAR_ICON_WIDTH, TOOLBAR_ICON_HEIGHT, LR_DEFAULTCOLOR | LR_LOADFROMFILE);
		m_quick_access_tlb_imgs.Add(icon);
		m_quick_access_tlb.SetButtonText(index, res_auth_map.at(btn.idCommand).remark.c_str());
		index++;
	}
	
	UpdateToolbarBtnSize(m_quick_access_tlb); // Make sure to set toolbar button size after the button text has been set.
	return true;
}

bool CMainFrame::CreateExFuncToolBar()
{
	static std::vector<std::wstring> kExFuncText =
	{
		_T("店铺"),
		_T("账户")
	};
	static const std::vector<std::wstring> kExFuncIcon =
	{
		_T("about.ico"),
		//_T("message.ico"),
		_T("user.ico")
	};
	// Icon for the disabled toolbar buttons.
	static const std::vector<std::wstring> kExFuncIconDisabled =
	{
		_T("about.ico"),
		//_T("message_d.ico"),
		_T("user_d.ico")
	};
	static std::vector<TBBUTTON> kExFuncBtn =
	{
		{ 0, USER_MESSAGE, TBSTATE_ENABLED, BTNS_AUTOSIZE | BTNS_BUTTON, 0, 0 },
		{ 1, USER_ACCOUNT, TBSTATE_ENABLED, BTNS_AUTOSIZE | BTNS_BUTTON | BTNS_WHOLEDROPDOWN, 0, 0 }
	};

	if (!m_ex_func_tlb.CreateEx(this, TBSTYLE_TRANSPARENT | TBSTYLE_LIST))
		return false; // fail to create
	if (!m_ex_func_tlb_imgs.Create(TOOLBAR_ICON_WIDTH, TOOLBAR_ICON_HEIGHT, ILC_COLOR32 | ILC_MASK, 0, 0) ||
		!m_ex_func_tlb_disabled_imgs.Create(TOOLBAR_ICON_WIDTH, TOOLBAR_ICON_HEIGHT, ILC_COLOR32 | ILC_MASK, 0, 0))
		return false;

	for (const auto& icon_name : kExFuncIcon)
	{
		std::wstring file_path = TOOLBAR_ICON_FOLDER + icon_name;
		if (!fs::exists(file_path))
		{
			LOG_ERROR(L"图片文件:" + file_path + L"不存在, 请检查!");
			return false;
		}
		HICON icon = (HICON)LoadImage(
			AfxGetResourceHandle(), file_path.c_str(), IMAGE_ICON, TOOLBAR_ICON_WIDTH, TOOLBAR_ICON_HEIGHT, LR_DEFAULTCOLOR | LR_LOADFROMFILE);
		m_ex_func_tlb_imgs.Add(icon);
	}
	

	for (const auto& icon_name : kExFuncIconDisabled)
	{
		std::wstring file_path = TOOLBAR_ICON_FOLDER + icon_name;
		if (!fs::exists(file_path))
		{
			LOG_ERROR(L"图片文件:" + file_path + L"不存在, 请检查!");
			return false;
		}
		HICON icon = (HICON)LoadImage(
			AfxGetResourceHandle(), file_path.c_str(), IMAGE_ICON, TOOLBAR_ICON_WIDTH, TOOLBAR_ICON_HEIGHT, LR_DEFAULTCOLOR | LR_LOADFROMFILE);
		m_ex_func_tlb_disabled_imgs.Add(icon);
		
	}

	CToolBarCtrl& tbc = m_ex_func_tlb.GetToolBarCtrl();
	for (auto& btn : kExFuncBtn)
		tbc.AddButtons(1, &btn);

	tbc.SetImageList(&m_ex_func_tlb_imgs);
	tbc.SetDisabledImageList(&m_ex_func_tlb_disabled_imgs);

	tbc.SetButtonSize(CSize(MENU_BUTTON_WIDTH, MENU_BUTTON_HEIGHT));
	
	int index = 0;
	for (auto& text : kExFuncText)
	{
		m_ex_func_tlb.SetButtonText(index, text.c_str());
		index++;
	}

	// 设置用户名
	const int kAccountBtnIndex = 1;
	m_ex_func_tlb.SetButtonText(kAccountBtnIndex, Session::Instance().UserName().c_str());

	//modify shop name display style. add by liuye 2017.3.27
	m_ex_func_tlb.SetButtonText(0, Session::Instance().GetMerName().c_str());
	//


	UpdateToolbarBtnSize(m_ex_func_tlb); // Make sure to set toolbar button size after the button text has been set.

	

	return true;
}

void CMainFrame::UpdateToolbarBtnSize(CToolBar& toolbar, uint32_t padding_width /*= 0*/, uint32_t padding_height /*= 0*/)
{
	CRect btn_rect;
	int total_btns_width = 0;
	int btns_count = toolbar.GetToolBarCtrl().GetButtonCount();
	if (btns_count<=0)
		return;

	for (int idx = 0; idx < btns_count; ++idx)
	{
		toolbar.GetItemRect(idx, &btn_rect);
		total_btns_width += btn_rect.Size().cx;
	}
	const int btn_size_x = total_btns_width / btns_count;// 计算按钮宽度平均值
	const int btn_size_y = btn_rect.Size().cy;
	toolbar.SetSizes(CSize(btn_size_x + padding_width, btn_size_y + padding_height), CSize(TOOLBAR_ICON_WIDTH, TOOLBAR_ICON_HEIGHT));
}

void CMainFrame::ShowUserMessageDlg()
{
	m_user_msg_monitor.Stop(); // Stop monitoring before launching the msg view dialog.
	RECT rect;
	GetClientRect(&rect);
	ClientToScreen(&rect);
	CUserMsgView(rect).DoModal();
	m_user_msg_monitor.Start(); // Recover monitoring.
}

std::string CMainFrame::MenuUrl(uint32_t menu_res_id) const
{
	auto& url_cfg = URLConfig::Instance();
	return url_cfg.FullHost() + m_menu_res_auth_manager.MenuItems().at(menu_res_id).url_path;
}

void CMainFrame::OnGetMinMaxInfo(MINMAXINFO* lpMMI)
{
	const LONG kMinTrackSizeX = GetSystemMetrics(SM_CXFULLSCREEN)/3*2;
	const LONG kMaxTrackSizeY = GetSystemMetrics(SM_CYFULLSCREEN)/3*2;

	if (lpMMI->ptMinTrackSize.x <= kMinTrackSizeX)
		lpMMI->ptMinTrackSize.x = kMinTrackSizeX;
	if (lpMMI->ptMinTrackSize.y <= kMaxTrackSizeY)
		lpMMI->ptMinTrackSize.y = kMaxTrackSizeY;
	
	CFrameWnd::OnGetMinMaxInfo(lpMMI);
}

LRESULT CMainFrame::OnCrashClose(WPARAM wParam, LPARAM lParam)
{
	if (!m_is_view_closing)
	{
		if (!Session::Instance().IsExpired()) // Only prompt notification in logged in state.
		{
			if (!LogonMgr::Instance().DoLogout())
			{
				MessageBox(L"退出系统失败,若无法重新登录请联系维护人员!", L"退出系统提示!", MB_OK | MB_ICONWARNING);
				LOG_ERROR(L"崩溃时,服务端退出请求处理失败。程序关闭。");
			}
			else
				LOG_TRACE(L"退出崩溃系统成功。");
		}
		/* Request CETradeClientView to close.this will make view to exit cef,
		and cef will send wm_close message to this fram window.*/
		m_view.SendMessage(WM_CLOSE);
		m_is_view_closing = true; // Enable next time close.
	}
	m_user_msg_monitor.Stop();
	LOG_TRACE(L"崩溃程序关闭。");
	CFrameWnd::OnClose();

	return 0;
}



void CMainFrame::OnSize(UINT nType, int cx, int cy)
{
	CFrameWnd::OnSize(nType, cx, cy);

	SetNoticeEditPos();
	//SetShopNameStaticPos();
}


//void CMainFrame::OnTimer(UINT_PTR nIDEvent)
//{
//	//m_dlgNotice.SetWindowText(m_cNoticeManage.GetNotice());
//
//	CFrameWnd::OnTimer(nIDEvent);
//}





BOOL CMainFrame::PreTranslateMessage(MSG* pMsg)
{
	if (pMsg->message == WM_LBUTTONDOWN || pMsg->message == WM_MOUSEMOVE || pMsg->message == WM_LBUTTONUP)
	{
		CRect rtShopName;
		m_ex_func_tlb.GetItemRect(0, &rtShopName);
		m_ex_func_tlb.ClientToScreen(&rtShopName);
		if (rtShopName.PtInRect(pMsg->pt)) // 检查在某个区域
		{
			m_cTip.Activate(TRUE);
			m_cTip.RelayEvent(pMsg);              // 接受消息响应
		}
		else
		{
			m_cTip.Activate(FALSE);
		}
	}
	return CFrameWnd::PreTranslateMessage(pMsg);
}


HBRUSH CMainFrame::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
	HBRUSH hbr = CFrameWnd::OnCtlColor(pDC, pWnd, nCtlColor);

	//if (pWnd->GetDlgCtrlID() == m_staticShopName.GetDlgCtrlID())
	//{
	//	pDC->SetBkMode(TRANSPARENT);//设置背景透明
	//	hbr = ::CreateSolidBrush(m_DefaultColor);
	//}

	return hbr;
}

//BOOL CMainFrame::IsSystemWin7()
//{
//	BOOL bResult = FALSE;
//
//	int a = 0, b = 0, i = 0, j = 0;
//	_asm
//	{
//		pushad
//			mov ebx, fs:[0x18]; get self pointer from TEB
//			mov eax, fs:[0x30]; get pointer to PEB / database
//			mov ebx, [eax + 0A8h]; get OSMinorVersion
//			mov eax, [eax + 0A4h]; get OSMajorVersion
//			mov j, ebx
//			mov i, eax
//			popad
//	}
//
//	if ((i == 6) && (j == 1))
//	{
//		bResult = TRUE;
//	}
//	return bResult;
//}