// DemoDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Demo.h"
#include "DemoDlg.h"

#include "UserInfoDlg.h"
#include "DevSNDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	CButtonST	m_btn_ok;
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	virtual BOOL OnInitDialog();
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	DDX_Control(pDX, IDOK, m_btn_ok);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDemoDlg dialog

CDemoDlg::CDemoDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CDemoDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CDemoDlg)
	m_strUserInfo = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CDemoDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CDemoDlg)
	DDX_Control(pDX, IDC_Btn_WriteSN, m_btn_writesn);
	DDX_Control(pDX, IDC_Btn_ReadSN, m_btn_readsn);
	DDX_Control(pDX, IDC_btn_Clear, m_btn_clear);
	DDX_Control(pDX, IDC_Btn_Delete, m_btn_delete);
	DDX_Control(pDX, IDC_STATIC_IMAGE3, m_static_image3);
	DDX_Control(pDX, IDC_STATIC_IMAGE2, m_static_image2);
	DDX_Control(pDX, IDC_STATIC_IMAGE1, m_static_image1);
	DDX_Control(pDX, IDC_STATIC_TIP, m_static_tip);
	DDX_Control(pDX, IDC_LIST_INFO, m_listctrl_info);
	DDX_Control(pDX, IDC_btn_version, m_btn_version);
	DDX_Control(pDX, IDC_btn_cancel, m_btn_cancel);
	DDX_Control(pDX, IDC_Btn_verify, m_btn_verify);
	DDX_Control(pDX, IDC_Btn_identify, m_btn_identify);
	DDX_Control(pDX, IDC_btn_getImage, m_btn_getImage);
	DDX_Control(pDX, IDC_Btn_getmb, m_btn_getmb);
	DDX_Text(pDX, IDC_EDIT_UserInfo, m_strUserInfo);
	DDV_MaxChars(pDX, m_strUserInfo, 32);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CDemoDlg, CDialog)
	//{{AFX_MSG_MAP(CDemoDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_CLOSE()
	ON_BN_CLICKED(IDC_btn_getImage, OnbtngetImage)
	ON_BN_CLICKED(IDC_btn_cancel, Onbtncancel)
	ON_BN_CLICKED(IDC_Btn_getmb, OnBtngetmb)
	ON_NOTIFY(NM_CLICK, IDC_LIST_INFO, OnClickListInfo)
	ON_BN_CLICKED(IDC_Btn_Delete, OnBtnDelete)
	ON_BN_CLICKED(IDC_btn_Clear, OnbtnClear)
	ON_BN_CLICKED(IDC_btn_version, Onbtnversion)
	ON_BN_CLICKED(IDC_Btn_verify, OnBtnverify)
	ON_BN_CLICKED(IDC_Btn_identify, OnBtnidentify)
	ON_BN_CLICKED(IDC_BUTTON_Get_DevLogo, OnBUTTONGetDevLogo)
	ON_BN_CLICKED(IDC_Btn_GetDeviceNo, OnBtnGetDeviceNo)
	ON_BN_CLICKED(IDC_Btn_GetUserInfo, OnBtnGetUserInfo)
	ON_BN_CLICKED(IDC_Btn_SetUserInfo, OnBtnSetUserInfo)
	ON_BN_CLICKED(IDC_btn_dll_version, Onbtndllversion)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDemoDlg message handlers
extern CString  g_szPropName;
extern HANDLE   g_hValue;
char *gszDbFile = "OpticFingerDB.mdb";

BOOL CDemoDlg::OnInitDialog()
{
	//设置只能运行一个程序
	SetProp(m_hWnd,g_szPropName,g_hValue);

	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	//连接数据库
	CString strConnection;
	strConnection.Format("Driver={Microsoft Access Driver (*.mdb)};"
		"Dbq=%s;Uid=%s;Pwd=%s",gszDbFile,"","");
	if(!m_pDb.Open(strConnection))
	{
		CDialog::EndDialog(0);
		return FALSE;
	}

	//设置列表框模式
	m_listctrl_info.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES);
	//清除列表框数据
    m_listctrl_info.DeleteAllItems();	
	//清除列表框标题
    for (int i=0;i<m_listctrl_info.GetHeaderCtrl()->GetItemCount();i++)
		m_listctrl_info.DeleteColumn(0);
    //添加列表框标题
	m_listctrl_info.InsertColumn(1,"ID号",LVCFMT_CENTER,50);
	m_listctrl_info.InsertColumn(2,"姓名",LVCFMT_CENTER,130);
	m_listctrl_info.InsertColumn(3,"备注",LVCFMT_CENTER,130);
	m_listctrl_info.InsertColumn(4,"指纹",LVCFMT_CENTER,190);

	m_strUserInfo = "012345678";
	UpdateData(FALSE);
	
	CString strSql;
	CString strUserId;
	CString strUserName;
	CString strUserNotes;
	CString strUserFinger;
	int iItem=0;
	strSql.Format("select * from UserInfo");
	CADORecordset m_pRs = CADORecordset(&m_pDb);
	if(m_pRs.Open((LPCTSTR)strSql,CADORecordset::openQuery))	
	{
		while(!m_pRs.IsEof())
		{
			m_pRs.GetFieldValue("UserID",strUserId);
			m_pRs.GetFieldValue("UserName",strUserName);
			m_pRs.GetFieldValue("UserInfo",strUserNotes);
			m_pRs.GetFieldValue("UserFinger",strUserFinger);
			m_pRs.MoveNext();

			m_listctrl_info.InsertItem(iItem,strUserId);
			m_listctrl_info.SetItemText(iItem,0,strUserId);
			m_listctrl_info.SetItemText(iItem,1,strUserName);
			m_listctrl_info.SetItemText(iItem,2,strUserNotes);
			m_listctrl_info.SetItemText(iItem,3,strUserFinger);

			iItem++;
		}
		m_pRs.Close();
	}
	m_iSelItem = -1;
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CDemoDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CDemoDlg::OnPaint() 
{
/*
#if 0
	//设置背景色
	CPaintDC dc(this);
	CRect rect; 
	GetClientRect(rect); 
    	dc.FillSolidRect(rect,RGB(107,171,211)); 
#else
	//设置背景图片
	CRect rect;
	GetClientRect(rect);
	CPaintDC dc(this); 
	CBitmap bmp, *oldBmp;
	BITMAP	bmpInfo;
	CDC		dcMemory;	
	bmp.LoadBitmap(IDB_BITMAP_BG);	
	bmp.GetBitmap(&bmpInfo);
	dcMemory.CreateCompatibleDC(&dc);
	oldBmp = dcMemory.SelectObject(&bmp);
	dc.StretchBlt(0,0,rect.Width(),rect.Height(),&dcMemory,
		0,0,bmpInfo.bmWidth,bmpInfo.bmHeight,SRCCOPY);
	dcMemory.SelectObject(oldBmp);
#endif
//*/
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CDemoDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}


BOOL CAboutDlg::OnInitDialog() 
{
	CDialog::OnInitDialog();
	// TODO: Add extra initialization here
	m_btn_ok.SetIcon(IDI_ICON_OK);
	m_btn_ok.DrawTransparent(TRUE);
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

void CDemoDlg::OnClose() 
{
	// TODO: Add your message handler code here and/or call default
	if (m_pDb.IsOpen())
	{
		m_pDb.Close();
	}
	CDialog::OnClose();
}

BOOL CDemoDlg::PreTranslateMessage(MSG* pMsg) 
{
	// TODO: Add your specialized code here and/or call the base class	
	if(pMsg->message == WM_KEYDOWN)
    {
        switch(pMsg->wParam)
        {
        case VK_RETURN://屏蔽回车键
            return TRUE;
        case VK_ESCAPE://屏蔽ESC键
            return TRUE;
        }
    }
	return CDialog::PreTranslateMessage(pMsg);
}

void CDemoDlg::Onbtncancel() 
{
	// TODO: Add your control notification handler code here
	mxCancelGetImage();
}

void CDemoDlg::EnableButton(BOOL bFlag)
{
	CButton* pButton;
	pButton=(CButton* )GetDlgItem(IDC_btn_getImage);
	pButton->EnableWindow(bFlag);
	pButton=(CButton* )GetDlgItem(IDC_Btn_getmb);
	pButton->EnableWindow(bFlag);
	pButton=(CButton* )GetDlgItem(IDC_Btn_verify);
	pButton->EnableWindow(bFlag);
	pButton=(CButton* )GetDlgItem(IDC_Btn_identify);
	pButton->EnableWindow(bFlag);
	pButton=(CButton* )GetDlgItem(IDC_btn_version);
	pButton->EnableWindow(bFlag);
	pButton=(CButton* )GetDlgItem(IDC_Btn_Delete);
	pButton->EnableWindow(bFlag);
	pButton=(CButton* )GetDlgItem(IDC_btn_Clear);
	pButton->EnableWindow(bFlag);
	pButton=(CButton* )GetDlgItem(IDC_btn_dll_version);
	pButton->EnableWindow(bFlag);
	pButton=(CButton* )GetDlgItem(IDC_btn_version);
	pButton->EnableWindow(bFlag);
	pButton=(CButton* )GetDlgItem(IDC_BUTTON_Get_DevLogo);
	pButton->EnableWindow(bFlag);
	pButton=(CButton* )GetDlgItem(IDC_Btn_GetDeviceNo);
	pButton->EnableWindow(bFlag);
	pButton=(CButton* )GetDlgItem(IDC_Btn_GetUserInfo);
	pButton->EnableWindow(bFlag);
	pButton=(CButton* )GetDlgItem(IDC_Btn_SetUserInfo);
	pButton->EnableWindow(bFlag);
}

void DisplayFingerPrint(HWND hWnd,UINT wnd_id,BYTE* lpImgData,int iWidth,int iHeight)
{
	unsigned char *showImage;
	BYTE bmpHdr[1500];
	BITMAPINFO* pBmpInfo = (BITMAPINFO*)bmpHdr;
	pBmpInfo->bmiHeader.biSize   = sizeof(BITMAPINFOHEADER);
	pBmpInfo->bmiHeader.biWidth  = iWidth;
	pBmpInfo->bmiHeader.biHeight = iHeight;
	pBmpInfo->bmiHeader.biPlanes = 1;
	pBmpInfo->bmiHeader.biBitCount = 8;
	pBmpInfo->bmiHeader.biCompression = 0;
	pBmpInfo->bmiHeader.biSizeImage   = iWidth*iHeight;
	pBmpInfo->bmiHeader.biXPelsPerMeter = 0;
	pBmpInfo->bmiHeader.biYPelsPerMeter = 0;
	pBmpInfo->bmiHeader.biClrUsed = 0;
	pBmpInfo->bmiHeader.biClrImportant  = 0;
	
	for (int i=0; i<256; i++)
	{
		pBmpInfo->bmiColors[i].rgbRed = i;
		pBmpInfo->bmiColors[i].rgbGreen = i;
		pBmpInfo->bmiColors[i].rgbBlue = i;
		pBmpInfo->bmiColors[i].rgbReserved = 0;
	}
	
	showImage = (unsigned char*)malloc(iWidth*iHeight);
	//上下翻转
	for(int j=0;j<iHeight/2;j++)
	{
		memcpy(showImage+j*iWidth,lpImgData+(iHeight-1-j)*iWidth,iWidth);
		memcpy(showImage+(iHeight-1-j)*iWidth,lpImgData+j*iWidth,iWidth);
   	}
	
	HWND itemhWnd = ::GetDlgItem(hWnd, wnd_id);
	HDC hDC = ::GetDC(itemhWnd);
	::StretchDIBits(hDC, 0, 0, iWidth, iHeight, 0, 0, iWidth, iHeight, 
		showImage, pBmpInfo, DIB_RGB_COLORS, SRCCOPY);
	::ReleaseDC(::GetDlgItem(hWnd, wnd_id), hDC);
	free(showImage);
}

UINT threadGenImge(LPVOID pParam)
{
	CDemoDlg *pDlg = (CDemoDlg*)pParam;
	pDlg->getImage();
	return 0;
}

void CDemoDlg::OnbtngetImage() 
{
	// TODO: Add your control notification handler code here
	AfxBeginThread(threadGenImge,this);
}

int CDemoDlg::getImage()
{
	m_static_tip.SetWindowText("正在录图像，请按手指...");
	EnableButton(false);
	m_hBitmap=LoadBitmap(AfxGetApp()->m_hInstance,MAKEINTRESOURCE(IDB_BITMAP_FINGER));
	m_static_image1.SetBitmap(m_hBitmap);
	m_static_image2.SetBitmap(m_hBitmap);
	m_static_image3.SetBitmap(m_hBitmap);
	unsigned char *imageBuf=(unsigned char*)malloc(IMAGE_X*IMAGE_Y);
	
	CString str;
	int ret;
	ret = mxUsbGetImage(imageBuf,0);
	switch(ret)
	{
	case 0:
		str.Format("采集图像成功!");
		break;
	case -1:
		str.Format("打开USB设备失败!");
		break;
	case -2:
		str.Format("用户取消操作!");
		break;
	case -3:
		str.Format("等待手指超时!");
		break;
	case -4:
		str.Format("采集图像失败!");
		break;
	default:
		str.Format("异常!");
			break;
	}
	
	m_static_tip.SetWindowText(str);
	EnableButton(true);
	if(ret!=0)
	{
		free(imageBuf);
		return 1;
	}
	DisplayFingerPrint(m_hWnd,IDC_STATIC_IMAGE3,imageBuf,IMAGE_X,IMAGE_Y);

	free(imageBuf);
	return 0;
}

UINT threadGetMb(LPVOID pParam)
{
	CDemoDlg *pDlg = (CDemoDlg*)pParam;
	pDlg->GetFingerTemplate();
	return 0;
}

void CDemoDlg::OnBtngetmb() 
{
	// TODO: Add your control notification handler code here
	AfxBeginThread(threadGetMb,this);
}

int CDemoDlg::GetFingerTemplate()
{
	CUserInfoDlg pUserInfoDlg;
	if(pUserInfoDlg.DoModal()!=IDOK)
	{
		m_static_tip.SetWindowText("取消获取模板");
		return -1;
	}
	m_strUserId   = pUserInfoDlg.m_strUserId;
	m_strUserName = pUserInfoDlg.m_strUserName;
	m_strUserNote = pUserInfoDlg.m_strUserNote;

	EnableButton(false);
	m_hBitmap=LoadBitmap(AfxGetApp()->m_hInstance,MAKEINTRESOURCE(IDB_BITMAP_FINGER));
	m_static_image1.SetBitmap(m_hBitmap);
	m_static_image2.SetBitmap(m_hBitmap);
	m_static_image3.SetBitmap(m_hBitmap);

	unsigned char tzArray[3][TZ_SIZE+1] = {0};
	unsigned char *imageBuf=(unsigned char*)malloc(IMAGE_X*IMAGE_Y);
	int iFinger=0;
	CString str;
	int ret;
	do 
	{
	next:
		str.Format("正在录模板，请按第%d次手指!",iFinger+1);
		m_static_tip.SetWindowText(str);

		memset(imageBuf,0x00,IMAGE_X*IMAGE_Y);
		ret = mxUsbGetImage(imageBuf,0);
		switch(ret)
		{
		case 0:
			str.Format("采集图像成功!");
			break;
		case -1:
			str.Format("打开USB设备失败!");
			break;
		case -2:
			str.Format("用户取消操作!");
			break;
		case -3:
			str.Format("等待手指超时!");
			break;
		case -4:
			str.Format("采集图像失败!");
			break;
		default:
			str.Format("异常!");
				break;
		}	
		if(ret!=0)
		{
			free(imageBuf);
			m_static_tip.SetWindowText(str);
			EnableButton(true);
			m_static_image1.SetBitmap(m_hBitmap);
			m_static_image2.SetBitmap(m_hBitmap);
			m_static_image3.SetBitmap(m_hBitmap);
			return 1;
		}
		
		switch(iFinger)
		{
		case 0:
			DisplayFingerPrint(m_hWnd,IDC_STATIC_IMAGE1,imageBuf,IMAGE_X,IMAGE_Y);
			break;
		case 1:
			DisplayFingerPrint(m_hWnd,IDC_STATIC_IMAGE2,imageBuf,IMAGE_X,IMAGE_Y);	
			break;
		case 2:
			DisplayFingerPrint(m_hWnd,IDC_STATIC_IMAGE3,imageBuf,IMAGE_X,IMAGE_Y);
			break;
		}

		ret=mxGetTzBase64(imageBuf,tzArray[iFinger]);
		if(ret != 0)
		{
			str.Format("提取特征失败！");
			m_static_tip.SetWindowText(str);
			goto next;
		}
 
		str.Format("第%d次录图像录入成功!",iFinger+1);
		m_static_tip.SetWindowText(str);
		iFinger+=1;
	}while(iFinger<3);

	free(imageBuf);

	unsigned char mb[TZ_SIZE+1]={0};
	ret=mxGetMBBase64(tzArray[0],tzArray[1],tzArray[2],mb);
	if(ret != 0)
	{
		str.Format("获取模板失败！");
		m_static_tip.SetWindowText(str);
		EnableButton(true);
		m_static_image1.SetBitmap(m_hBitmap);
		m_static_image2.SetBitmap(m_hBitmap);
		m_static_image3.SetBitmap(m_hBitmap);
		return 1;
	}
// 	FILE *fp;
// 	fp = fopen("mb1.txt","w");
// 	fwrite(mb,1,TZ_SIZE,fp);
// 	fclose(fp);

	CString strMb;
	strMb.Format("%s",mb);

	BOOL bIsExist = false;
	CString strSql;
	strSql.Format("Select * from UserInfo Where UserID='%s'",m_strUserId);
	CADORecordset m_pRs = CADORecordset(&m_pDb);
	if(m_pRs.Open(strSql,CADORecordset::openQuery))	
	{
		while(!m_pRs.IsEof())
		{
			bIsExist = true;
			CString strInfo;
			strInfo.Format("该ID号%s已经存在,是否覆盖?",m_strUserId);
			if(IDOK != AfxMessageBox(strInfo,MB_OKCANCEL)) 
			{
				//保留
				m_static_tip.SetWindowText("保留原数据");
			}
			else
			{
		    	//更新
				LVFINDINFO info;
				int nIndex;
				info.flags = LVFI_PARTIAL|LVFI_STRING;
				info.psz = m_strUserId.GetBuffer(0);
				if ((nIndex=m_listctrl_info.FindItem(&info)) != -1)
				{
					m_listctrl_info.SetItemText(nIndex,1,m_strUserName);
					m_listctrl_info.SetItemText(nIndex,2,m_strUserNote);
					m_listctrl_info.SetItemText(nIndex,3,strMb);
 				}

				m_pRs.Edit();
				m_pRs.SetFieldValue("UserID",m_strUserId);
				m_pRs.SetFieldValue("UserName",m_strUserName);
				m_pRs.SetFieldValue("UserInfo",m_strUserNote);
				m_pRs.SetFieldValue("UserFinger",strMb);
				if(!m_pRs.Update())
				{
					m_static_tip.SetWindowText("错误: 更新模板失败!");		
				}
				else
				{
					m_static_tip.SetWindowText("更新模板成功!");	
				}
			}
			break;
		}
		m_pRs.Close();
	}

	if (!bIsExist)
	{
		if(m_pRs.Open("UserInfo",CADORecordset::openQuery))	
		{
			//增加
			int count;
			count=m_listctrl_info.GetItemCount();
			m_listctrl_info.InsertItem(count,m_strUserId);
			m_listctrl_info.SetItemText(count,1,m_strUserName);
			m_listctrl_info.SetItemText(count,2,m_strUserNote);
			m_listctrl_info.SetItemText(count,3,strMb);

			m_pRs.AddNew();
			m_pRs.SetFieldValue("UserID",m_strUserId);
			m_pRs.SetFieldValue("UserName",m_strUserName);
			m_pRs.SetFieldValue("UserInfo",m_strUserNote);
			m_pRs.SetFieldValue("UserFinger",strMb);
			if(!m_pRs.Update())
			{
				m_static_tip.SetWindowText("错误: 增加模板失败!");		
			}
			else
			{
				m_static_tip.SetWindowText("增加模板成功!");	
			}
		}
	}

	EnableButton(true);
	return 0;	
}

void CDemoDlg::OnClickListInfo(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// TODO: Add your control notification handler code here
	POSITION pos = m_listctrl_info.GetFirstSelectedItemPosition();
	if (pos == NULL)
	{
		m_iSelItem = -1;
		return;
	}
	else
	{
	   while (pos)
	   {
		  m_iSelItem = m_listctrl_info.GetNextSelectedItem(pos);
	   }
	}
	
	*pResult = 0;
}

void CDemoDlg::OnBtnDelete() 
{
	// TODO: Add your control notification handler code here
	if(m_iSelItem < 0)
	{
		AfxMessageBox("请先选择删除记录！");
		return;
	}
	if(IDYES==AfxMessageBox("您确定删除选中记录么？",MB_YESNO))
	{
		CString strUserId;
		strUserId = m_listctrl_info.GetItemText(m_iSelItem,0);
 		CString strSql;
 		strSql.Format("DELETE * FROM UserInfo WHERE UserID='%s'" ,strUserId);
		CString strInfo;
		if(m_pDb.Execute(strSql))
		{
			m_listctrl_info.DeleteItem(m_iSelItem);
			strInfo.Format("删除记录ID号:%s 成功",strUserId);	
		}
		else
		{
			strInfo.Format("删除记录ID号:%s 失败",strUserId);	
		}
		m_static_tip.SetWindowText(strInfo);	  
	}
	m_iSelItem = -1;
}

void CDemoDlg::OnbtnClear() 
{
	// TODO: Add your control notification handler code here
	if(IDYES==AfxMessageBox("您确定清空所有记录么？",MB_YESNO))
	{
 		CString strSql;
 		strSql.Format("DELETE * FROM UserInfo");
		if(m_pDb.Execute(strSql))
		{
			m_listctrl_info.DeleteAllItems();
			m_static_tip.SetWindowText("清空记录成功");
		}
		else
		{
			m_static_tip.SetWindowText("清空记录失败");
		}
	}	
}

void CDemoDlg::Onbtnversion() 
{
	// TODO: Add your control notification handler code here
	char version[256] = {0};
	mxGetDeviceVersion(version);
	m_static_tip.SetWindowText(version);		
}

UINT threadFingerVerify(LPVOID pParam)
{
	CDemoDlg *pDlg = (CDemoDlg*)pParam;
	pDlg->FingerVerify();
	return 0;
}

void CDemoDlg::OnBtnverify() 
{
	// TODO: Add your control notification handler code here
	AfxBeginThread(threadFingerVerify,this);
}

int CDemoDlg::FingerVerify()
{
	if(m_iSelItem < 0)
	{
		AfxMessageBox("请先选择比对记录！");
		return -1;
	}

	m_static_tip.SetWindowText("正在比对，请按手指...");
	EnableButton(false);
	m_hBitmap=LoadBitmap(AfxGetApp()->m_hInstance,MAKEINTRESOURCE(IDB_BITMAP_FINGER));
	m_static_image1.SetBitmap(m_hBitmap);
	m_static_image2.SetBitmap(m_hBitmap);
	m_static_image3.SetBitmap(m_hBitmap);
	unsigned char *imageBuf=(unsigned char*)malloc(IMAGE_X*IMAGE_Y);
	
	CString str;
	int ret;
	ret = mxUsbGetImage(imageBuf,0);
	switch(ret)
	{
	case 0:
		str.Format("采集图像成功!");
		break;
	case -1:
		str.Format("打开USB设备失败!");
		break;
	case -2:
		str.Format("用户取消操作!");
		break;
	case -3:
		str.Format("等待手指超时!");
		break;
	case -4:
		str.Format("采集图像失败!");
		break;
	default:
		str.Format("异常!");
			break;
	}
	
	m_static_tip.SetWindowText(str);
	EnableButton(true);
	if(ret != 0)
	{
		free(imageBuf);
		return 1;
	}
	DisplayFingerPrint(m_hWnd,IDC_STATIC_IMAGE3,imageBuf,IMAGE_X,IMAGE_Y);
	
	unsigned char tz[TZ_SIZE+1] = {0};
	ret=mxGetTzBase64(imageBuf,tz);
	if(ret != 0)
	{
		m_static_tip.SetWindowText("提取特征失败！");
		free(imageBuf);
		return -1;
	}
// 	FILE *fp;
// 	fp = fopen("tz1.txt","w");
// 	fwrite(tz,1,TZ_SIZE,fp);
// 	fclose(fp);

	CString strMb = m_listctrl_info.GetItemText(m_iSelItem,3);
	char mb[TZ_SIZE+1] = {0};
	sprintf(mb,"%s",strMb.GetBuffer(0));

	ret = mxFingerMatchBase64((unsigned char*)mb,tz,3);
	if(ret != 0)
	{
		m_static_tip.SetWindowText("比对失败！");
	}
	else
	{
		m_static_tip.SetWindowText("比对成功！");
	}	
    return 0;	
}

UINT threadFingerIdentify(LPVOID pParam)
{
	CDemoDlg *pDlg = (CDemoDlg*)pParam;
	pDlg->FingerIdentify();
	return 0;
}

void CDemoDlg::OnBtnidentify() 
{
	// TODO: Add your control notification handler code here
	AfxBeginThread(threadFingerIdentify,this);	
}

int CDemoDlg::FingerIdentify()
{
	m_static_tip.SetWindowText("正在搜索，请按手指...");
	EnableButton(false);
	m_hBitmap=LoadBitmap(AfxGetApp()->m_hInstance,MAKEINTRESOURCE(IDB_BITMAP_FINGER));
	m_static_image1.SetBitmap(m_hBitmap);
	m_static_image2.SetBitmap(m_hBitmap);
	m_static_image3.SetBitmap(m_hBitmap);
	unsigned char *imageBuf=(unsigned char*)malloc(IMAGE_X*IMAGE_Y);
	
	CString str;
	int ret;
	ret = mxUsbGetImage(imageBuf,0);
	switch(ret)
	{
	case 0:
		str.Format("采集图像成功!");
		break;
	case -1:
		str.Format("打开USB设备失败!");
		break;
	case -2:
		str.Format("用户取消操作!");
		break;
	case -3:
		str.Format("等待手指超时!");
		break;
	case -4:
		str.Format("采集图像失败!");
		break;
	default:
		str.Format("异常!");
			break;
	}
	
	m_static_tip.SetWindowText(str);
	EnableButton(true);
	if(ret != 0)
	{
		free(imageBuf);
		return 1;
	}
	DisplayFingerPrint(m_hWnd,IDC_STATIC_IMAGE3,imageBuf,IMAGE_X,IMAGE_Y);
	
	unsigned char tz[TZ_SIZE+1] = {0};
	ret=mxGetTzBase64(imageBuf,tz);
	if(ret != 0)
	{
		m_static_tip.SetWindowText("提取特征失败！");
		free(imageBuf);
		return -1;
	}

	CString strInfo;
	bool bIdentify = false;
	CString strMb;
	char mb[TZ_SIZE+1] = {0};
	for (int i=0;i<m_listctrl_info.GetItemCount();i++)
	{
		strMb = m_listctrl_info.GetItemText(i,3);
		int length = strMb.GetLength();
		sprintf(mb,"%s",strMb.GetBuffer(0));

		ret = mxFingerMatchBase64((unsigned char*)mb,tz,3);
		if (ret==0)
		{
			bIdentify = true;
			strInfo = m_listctrl_info.GetItemText(i,0);
			strInfo = "搜索到用户ID号：" + strInfo;
			break;
		}
	}
	if (bIdentify)
	{
		m_static_tip.SetWindowText(strInfo);
	}
	else
	{
		m_static_tip.SetWindowText("没有找到匹配指纹");	
	}
	return 0;
}


void CDemoDlg::OnBUTTONGetDevLogo() 
{
	// TODO: Add your control notification handler code here
	char szUserinfo[25] = {0};
	int ret = mxGetDeviceLogo(szUserinfo);
	if(ret==0)
	{
		m_static_tip.SetWindowText(szUserinfo);	
	}
	else
	{
		AfxMessageBox("读厂商标识失败");	
	}	
}

void CDemoDlg::OnBtnGetDeviceNo() 
{
	// TODO: Add your control notification handler code here
	char szDeviceNo[9] = {0};
	int ret = mxGetDeviceSN(szDeviceNo);
	if(ret==0)
	{
		m_static_tip.SetWindowText(szDeviceNo);	
	}
	else
	{
		AfxMessageBox("读序列号失败");	
	}	
}

void CDemoDlg::OnBtnGetUserInfo() 
{
	// TODO: Add your control notification handler code here
	char szUserinfo[33] = {0};
	int ret = mxGetUserInfo(szUserinfo);
	if(ret==0)
	{
		m_static_tip.SetWindowText(szUserinfo);	
	}
	else
	{
		AfxMessageBox("读客户信息失败");	
	}		
}

void CDemoDlg::OnBtnSetUserInfo() 
{
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);

	if (m_strUserInfo.IsEmpty())
	{
		AfxMessageBox("客户信息不能为空");
		return;
	}

	if (m_strUserInfo.GetLength()>32)
	{
		AfxMessageBox("客户信息应小于等于32个字节");
		return;
	}
	char szDeviceNo[33] = {0};
	sprintf(szDeviceNo,"%s",m_strUserInfo.GetBuffer(0));
	int ret = mxSetUserInfo(szDeviceNo);
	if(ret==0)
	{
		m_static_tip.SetWindowText("写客户信息成功");	
	}
	else
	{
		AfxMessageBox("写客户信息失败");	
	}	
}

void CDemoDlg::Onbtndllversion() 
{
	// TODO: Add your control notification handler code here
	char version[256] = {0};
	mxGetDllVersion(version);
	m_static_tip.SetWindowText(version);		
}
