
// SilkModuleDlg.cpp : 实现文件
//

#include "stdafx.h"
#include "SilkModule.h"
#include "SilkModuleDlg.h"
#include "DataCenter.h"
#include "UserModule.h"
#include <atlimage.h>
#include "SetParam.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#import "msado15.dll" no_namespace rename ("EOF", "adoEOF")
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

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

// 对话框数据
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

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

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CSilkModuleDlg 对话框




CSilkModuleDlg::CSilkModuleDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CSilkModuleDlg::IDD, pParent)
	, m_ListIndex(0)
	, m_errorFile(NULL)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	start();
	for(int i = 0; i < 256; i++)
	{
		m_GrayTable[i].rgbRed = i;
		m_GrayTable[i].rgbGreen = i;
		m_GrayTable[i].rgbBlue = i;
		m_GrayTable[i].rgbReserved = 0;
	}
	m_mapOp[OP_INVALID_OPERATION] = "OP_INVALID_OPERATION";
	m_mapOp[OP_CONNECT] = "OP_CONNECT";
	m_mapOp[OP_DIS_CONNECT] = "OP_DIS_CONNECT";
	m_mapOp[OP_ENROLL] = "OP_ENROLL";
	m_mapOp[OP_ENROLL_IMAGE] = "OP_ENROLL_IMAGE";
	m_mapOp[OP_ENROLL_TMP] = "OP_ENROLL_TMP";
	m_mapOp[OP_DEL_TMP] = "OP_DEL_TMP";
	m_mapOp[OP_LOAD_TMP] = "OP_LOAD_TMP";
	m_mapOp[OP_READ_TMP] = "OP_READ_TMP";
	m_mapOp[OP_DEL_USER] = "OP_DEL_USER";
	m_mapOp[OP_ADD_USER] = "OP_ADD_USER";
	m_mapOp[OP_READ_USER] = "OP_READ_USER";
	m_mapOp[OP_LOAD_USER] = "OP_LOAD_USER";
	m_mapOp[OP_DEL_DB] = "OP_DEL_DB";
	m_mapOp[OP_VERIFY] = "OP_VERIFY";
	m_mapOp[OP_LOAD_LOG] = "OP_LOAD_LOG";
	m_mapOp[OP_DEL_LOG] = "OP_DEL_LOG";
	m_mapOp[OP_SET_TIME] = "OP_SET_TIME";
	m_mapOp[OP_GET_TIME] = "OP_GET_TIME";
	m_mapOp[OP_SYS_STATUS] = "OP_SYS_STATUS";
	m_mapOp[OP_SYS_READ_PARAM] = "OP_SYS_READ_PARAM";
	m_mapOp[OP_SYS_WRITE_PARAM] = "OP_SYS_WRITE_PARAM";
	m_mapOp[OP_SYS_SAVE_PARAM] = "OP_SYS_SAVE_PARAM";
	m_mapOp[OP_SCAN_IMAGE] = "OP_SCAN_IMAGE";
	m_mapOp[OP_SCAN_TMP] = "OP_SCAN_TMP";
	m_mapOp[OP_UPDATA] = "OP_UPDATA";
	m_mapOp[NOTICE_IDENTIFY] = "NOTICE_IDENTIFY";

	m_mapRe[Result_OK] = "Result_OK";
	m_mapRe[Result_Error] = "Result_Error";
	m_mapRe[Result_hasOpened] = "Result_hasOpened";
	m_mapRe[Result_SendFail] = "Result_SendFail";
	m_mapRe[Result_NoReply] = "Result_NoReply";
	m_mapRe[Result_NoSuccess] = "Result_NoSuccess";
	m_mapRe[Result_NoFind] = "Result_NoFind";
	m_mapRe[Result_CheckSum] = "Result_CheckSum";
	m_mapRe[Result_DataError] = "Result_DataError";
	m_mapRe[Result_PackNumError] = "Result_PackNumError";
}

void CSilkModuleDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CSilkModuleDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BUTTON_CONNECT, &CSilkModuleDlg::OnBnClickedButtonConnect)
	ON_BN_CLICKED(IDC_BUTTON_DISCONNECT, &CSilkModuleDlg::OnBnClickedButtonDisconnect)
	ON_BN_CLICKED(IDC_BUTTON_ENROLL, &CSilkModuleDlg::OnBnClickedButtonEnroll)
	ON_BN_CLICKED(IDC_BUTTON_ENROLL_IMAGE, &CSilkModuleDlg::OnBnClickedButtonEnrollImage)
	ON_BN_CLICKED(IDC_BUTTON_DELETE_ALL_USER, &CSilkModuleDlg::OnBnClickedButtonDeleteAllUser)
	ON_BN_CLICKED(IDC_BUTTON_DELETE_ALL_TEM, &CSilkModuleDlg::OnBnClickedButtonDeleteAllTem)
	ON_BN_CLICKED(IDC_BUTTON_DELETE_DB, &CSilkModuleDlg::OnBnClickedButtonDeleteDb)
	ON_BN_CLICKED(IDC_BUTTON_SCAN_IMAGE, &CSilkModuleDlg::OnBnClickedButtonScanImage)
	ON_BN_CLICKED(IDC_BUTTON_GET_TIME, &CSilkModuleDlg::OnBnClickedButtonGetTime)
	ON_BN_CLICKED(IDC_BUTTON_SET_TIME, &CSilkModuleDlg::OnBnClickedButtonSetTime)
	ON_BN_CLICKED(IDC_BUTTON_READ_PARAM, &CSilkModuleDlg::OnBnClickedButtonReadParam)
	ON_BN_CLICKED(IDC_BUTTON_WRITE_PARAM, &CSilkModuleDlg::OnBnClickedButtonWriteParam)
	ON_BN_CLICKED(IDC_BUTTON_ADD_USER, &CSilkModuleDlg::OnBnClickedButtonAddUser)
	ON_BN_CLICKED(IDC_BUTTON_READ_USER, &CSilkModuleDlg::OnBnClickedButtonReadUser)
	ON_BN_CLICKED(IDC_BUTTON_LOAD_USER, &CSilkModuleDlg::OnBnClickedButtonLoadUser)
	ON_BN_CLICKED(IDC_BUTTON_ENROLL_TMP, &CSilkModuleDlg::OnBnClickedButtonEnrollTmp)
	ON_BN_CLICKED(IDC_BUTTON_LOAD_TMP, &CSilkModuleDlg::OnBnClickedButtonLoadTmp)
	ON_BN_CLICKED(IDC_BUTTON_DEL_TMP, &CSilkModuleDlg::OnBnClickedButtonDelTmp)
	ON_BN_CLICKED(IDC_BUTTON_SAVE_PARAM, &CSilkModuleDlg::OnBnClickedButtonSaveParam)
	ON_BN_CLICKED(IDC_BUTTON_DEL_USER, &CSilkModuleDlg::OnBnClickedButtonDelUser)
	ON_BN_CLICKED(IDC_BUTTON_DEL_LOG, &CSilkModuleDlg::OnBnClickedButtonDelLog)
	ON_BN_CLICKED(IDC_BUTTON_LOAD_LOG, &CSilkModuleDlg::OnBnClickedButtonLoadLog)
	ON_BN_CLICKED(IDC_BUTTON_PIN_VERIFY, &CSilkModuleDlg::OnBnClickedButtonPinVerify)
	ON_BN_CLICKED(IDC_BUTTON_IMAGE_VERIFY, &CSilkModuleDlg::OnBnClickedButtonImageVerify)
	ON_BN_CLICKED(IDC_BUTTON_READ_TMP, &CSilkModuleDlg::OnBnClickedButtonReadTmp)
	ON_BN_CLICKED(IDC_BUTTON_UPDATA, &CSilkModuleDlg::OnBnClickedButtonUpdata)
	ON_NOTIFY(NM_CUSTOMDRAW, IDC_LIST_STATUS, &CSilkModuleDlg::OnNMCustomdrawListStatus)
	ON_BN_CLICKED(IDC_BUTTON_SCAN_TEM, &CSilkModuleDlg::OnBnClickedButtonScanTem)
	ON_BN_CLICKED(IDC_BUTTON_RESET, &CSilkModuleDlg::OnBnClickedButtonReset)
END_MESSAGE_MAP()


// CSilkModuleDlg 消息处理程序

BOOL CSilkModuleDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

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

	// 设置此对话框的图标。当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	// TODO: 在此添加额外的初始化代码
	m_pUser = CDataCenter::GetInstance()->m_pUser;
	((CComboBox *)GetDlgItem(IDC_COMBO_CONNECT_TYPE))->InsertString(0, "串口");
	((CComboBox *)GetDlgItem(IDC_COMBO_CONNECT_TYPE))->InsertString(1, "USB");
	((CComboBox *)GetDlgItem(IDC_COMBO_CONNECT_TYPE))->SetCurSel(1);

	m_pListState = (CListCtrl*)GetDlgItem(IDC_LIST_STATUS);

	m_pListState->SetExtendedStyle(LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT);
	m_pListState->InsertColumn(0, "颜色", LVCFMT_CENTER, 0);
	m_pListState->InsertColumn(1, "序号", LVCFMT_CENTER, 167);
	m_pListState->SetColumnWidth(3, -2);
	m_pListState->GetHeaderCtrl()->EnableWindow(false);

	//m_pUser->setCallback(Func, this);
	m_pUser->setResultListerner(this);

	m_errorFile = fopen("error.info", "a");
	GetDlgItem(IDC_EDIT_PIN)->SetWindowText("12");

	//FILE *pf = fopen("laugh")
	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

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

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CSilkModuleDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		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;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CSilkModuleDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}


void CSilkModuleDlg::OnBnClickedButtonConnect()
{
	int index = ((CComboBox *)GetDlgItem(IDC_COMBO_CONNECT_TYPE))->GetCurSel();
	bool r = m_pUser->connect(index);
}

void CSilkModuleDlg::OnBnClickedButtonDisconnect()
{
	bool r = m_pUser->disConnect();
}

void CSilkModuleDlg::OnBnClickedButtonEnroll()
{
	int pin = 0;
	int flag = MD_ADD_NEW;
	CString str;
	GetDlgItem(IDC_EDIT_PIN)->GetWindowText(str);
	if (str.IsEmpty())
	{
		MessageBox("请输入用户ID");
		return;
	}
	pin = atoi(str.GetBuffer());
	m_pUser->enroll(pin, flag);
}

void CSilkModuleDlg::OnBnClickedButtonEnrollImage()
{
	CString str;
	GetDlgItem(IDC_EDIT_PIN)->GetWindowText(str);
	if (str.IsEmpty())
	{
		MessageBox("请输入用户ID");
		return;
	}
	int pin = atoi(str.GetBuffer());

	CFileDialog dlg(TRUE, 0, NULL, OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT, "(*.*)|*.*||");
	if(dlg.DoModal() == IDOK)
	{
		str = dlg.GetPathName();
	}
	else
	{
		return;
	}
	FILE *pf = fopen(str, "rb+");
	if (pf == NULL)
	{
		return;
	}
	fseek(pf, 0, SEEK_END);
	int len = ftell(pf);
	fseek(pf, 0, SEEK_SET);
	char *buf =	new char[len];
	memset(buf, 0, len);
	fread(buf, len, 1, pf);
	fclose(pf);

	DWORD offset = 0;
	DWORD width = 0;
	DWORD height = 0;
	DWORD biSizeImage = 0;
	
	memcpy(&offset, buf+10, 4);
	memcpy(&width, buf+18, 4);
	memcpy(&height, buf+22, 4);
	memcpy(&biSizeImage, buf+34, 4);

	char *p1 = new char[len];
	char *p2 = buf + len - width;
	char *p3 = p1;
	for (int i=0; i<height; i++)
	{
		memcpy(p3, p2, width);
		p3 += width;
		p2 -= width;
	}
	m_pUser->enrollByImage(p1, len-offset, pin);
	delete []buf;
	delete []p1;
}

void CSilkModuleDlg::OnBnClickedButtonDeleteAllUser()
{
	m_pUser->deleteUser();
}

void CSilkModuleDlg::OnBnClickedButtonDelUser()
{
	CString str;
	GetDlgItem(IDC_EDIT_PIN)->GetWindowText(str);
	if (str.IsEmpty())
	{
		MessageBox("请输入用户ID");
		return;
	}
	int pin = atoi(str.GetBuffer());
	m_pUser->deleteUser(pin);
}

void CSilkModuleDlg::OnBnClickedButtonDeleteAllTem()
{
	m_pUser->deleteTmp();
}

void CSilkModuleDlg::OnBnClickedButtonDelTmp()
{
	CString str;
	GetDlgItem(IDC_EDIT_PIN)->GetWindowText(str);
	if (str.IsEmpty())
	{
		MessageBox("请输入用户ID");
		return;
	}
	int pin = atoi(str.GetBuffer());
	m_pUser->deleteTmp(pin);
}


void CSilkModuleDlg::OnBnClickedButtonDeleteDb()
{
	m_pUser->deleteDB();
}

void CSilkModuleDlg::OnBnClickedButtonScanImage()
{
	bool r = m_pUser->scanFpImage();
}

void CSilkModuleDlg::OnBnClickedButtonGetTime()
{
	int year = 0;
	int month = 0;
	int day = 0;
	int hour = 0;
	int min = 0;
	int sec = 0;

	int bGet = m_pUser->getTime(year, month, day, hour, min, sec);

	int d = 0;
}

void CSilkModuleDlg::OnBnClickedButtonSetTime()
{
	int year = 2015;
	int month = 10;
	int day = 10;

	int hour = 12;
	int min = 20;
	int sec = 30;


	m_pUser->setTime(year, month, day, hour, min, sec);
}

void CSilkModuleDlg::OnBnClickedButtonReadParam()
{
	m_pUser->readParam();
}

void CSilkModuleDlg::OnBnClickedButtonWriteParam()
{
	CSetParam dlg;
	INT_PTR nResponse = dlg.DoModal();
	if (nResponse == IDOK)
	{
		SetParam param;

		param.iGpioLevel = dlg.m_gpioLevel + 0x30;
		param.iSaveLog = dlg.m_saveLog + 0x30;
		param.iAutoAck = dlg.m_autoAck + 0x30;
		param.iTimeout = dlg.m_timeOut + 0x30;
		param.iWorkMode = dlg.m_WorkMode + 0x30;
		param.iTmpFormat = dlg.m_TmpFormat + 0x30;
		param.iLampColor = dlg.m_LampColor;
		param.iLampTime = dlg.m_LampTime;
		m_pUser->writeParam(param);
	}
}

void CSilkModuleDlg::OnBnClickedButtonAddUser()
{
	CString str;
	GetDlgItem(IDC_EDIT_PIN)->GetWindowText(str);
	if (str.IsEmpty())
	{
		MessageBox("请输入用户ID");
		return;
	}
	int pin = atoi(str.GetBuffer());

	TUser user;
	memset(&user, 0, sizeof(TUser));
	user.PIN = pin;
	sprintf(user.Name, "hao%d", pin);
	user.Privilege = 1;
	m_pUser->addUser(user);
}

void CSilkModuleDlg::OnBnClickedButtonReadUser()
{
	CString str;
	GetDlgItem(IDC_EDIT_PIN)->GetWindowText(str);
	if (str.IsEmpty())
	{
		MessageBox("请输入用户ID");
		return;
	}
	int pin = atoi(str);
	TUser user;
	m_pUser->readUser(pin, user);
}

void CSilkModuleDlg::OnBnClickedButtonLoadUser()
{
	m_pUser->loadUser();
}

void CSilkModuleDlg::OnBnClickedButtonEnrollTmp()
{
	CString str;
	GetDlgItem(IDC_EDIT_PIN)->GetWindowText(str);
	if (str.IsEmpty())
	{
		MessageBox("请输入用户ID");
		return;
	}
	int pin = atoi(str);

	CFileDialog dlg(TRUE, 0, NULL, OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT, "(*.*)|*.*||");
	if(dlg.DoModal() == IDOK)
	{
		str = dlg.GetPathName();
	}
	else
	{
		return;
	}
	FILE *pf = fopen(str, "rb+");
	if (pf == NULL)
	{
		return;
	}
	fseek(pf, 0, SEEK_END);
	int len = ftell(pf);
	fseek(pf, 0, SEEK_SET);
	char *buf =	new char[len];
	memset(buf, 0, len);
	fread(buf, len, 1, pf);

	m_pUser->enrollTmp(pin, buf, len);
	delete []buf;
}

void CSilkModuleDlg::OnBnClickedButtonLoadTmp()
{
	m_pUser->loadTmp();
}
void CSilkModuleDlg::OnBnClickedButtonSaveParam()
{
	m_pUser->saveParam();
}

void CSilkModuleDlg::OnBnClickedButtonDelLog()
{
	m_pUser->delLog();
}

void CSilkModuleDlg::OnBnClickedButtonLoadLog()
{
	m_pUser->loadLog();
}

void CSilkModuleDlg::OnBnClickedButtonPinVerify()
{
	CString str;
	GetDlgItem(IDC_EDIT_PIN)->GetWindowText(str);
	if (str.IsEmpty())
	{
		MessageBox("请输入用户ID");
		return;
	}
	int pin = atoi(str);
	m_pUser->verifyFp(pin);
}

void CSilkModuleDlg::OnBnClickedButtonImageVerify()
{
	CString str;
	CFileDialog dlg(TRUE, 0, NULL, OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT, "(*.*)|*.*||");
	if(dlg.DoModal() == IDOK)
	{
		str = dlg.GetPathName();
	}
	else
	{
		return;
	}

	FILE *pf = fopen(str, "rb+");
	if (pf == NULL)
	{
		return;
	}
	fseek(pf, 0, SEEK_END);
	int len = ftell(pf);
	fseek(pf, 0, SEEK_SET);
	char *buf =	new char[len];
	memset(buf, 0, len);
	fread(buf, len, 1, pf);
	fclose(pf);

	DWORD offset = 0;
	DWORD width = 0;
	DWORD height = 0;
	DWORD biSizeImage = 0;

	memcpy(&offset, buf+10, 4);
	memcpy(&width, buf+18, 4);
	memcpy(&height, buf+22, 4);
	memcpy(&biSizeImage, buf+34, 4);

	char *p1 = new char[len];
	char *p2 = buf + len - width;
	char *p3 = p1;
	for (int i=0; i<height; i++)
	{
		memcpy(p3, p2, width);
		p3 += width;
		p2 -= width;
	}

	m_pUser->verifyFp(p1, len-offset);
	delete []buf;
	delete []p1;
	
}

void CSilkModuleDlg::OnBnClickedButtonReadTmp()
{
	CString str;
	GetDlgItem(IDC_EDIT_PIN)->GetWindowText(str);
	if (str.IsEmpty())
	{
		MessageBox("请输入用户ID");
		return;
	}
	int pin = atoi(str);
	m_pUser->readTmp(pin);
}
void CSilkModuleDlg::OnBnClickedButtonUpdata()
{
	CString str;
	CFileDialog dlg(TRUE, 0, NULL, OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT, "(*.*)|*.*||");
	if(dlg.DoModal() == IDOK)
	{
		str = dlg.GetPathName();
	}
	else
	{
		return;
	}
	FILE *pf = fopen(str, "rb+");
	if (pf == NULL)
	{
		return;
	}
	fseek(pf, 0, SEEK_END);
	int len = ftell(pf);
	fseek(pf, 0, SEEK_SET);
	char *buf = new char[len];
	memset(buf, 0, len);
	fread(buf, len, 1, pf);
	fclose(pf);
	pf = NULL;

	bool ret = m_pUser->updata(buf, len);
	delete []buf;
}

void CSilkModuleDlg::HeartBeat_Imp()
{
	m_queMutex.acquire();
	int size = m_pduQueue.size();
	if (size == 0)
	{
		m_queMutex.release();
		return;
	}
	CInterProtocl *pdu = m_pduQueue.front();
	m_pduQueue.pop_front();
	m_queMutex.release();

	if (pdu->m_operation == OP_SCAN_IMAGE && pdu->m_Reslut == Result_Error)
	{
		int d = 0;
	}
	if (pdu->m_operation == OP_SCAN_IMAGE && pdu->m_Reslut == Result_OK)
	{
		int width = pdu->m_nParam1;
		int height = pdu->m_nParam2;
		ShowImage(pdu->m_data, width, height);
		
	}
	pdu->recycleITP();
}

void CSilkModuleDlg::ShowImage( char *image, int width, int height )
{
	int len = width * height;
	char *pImgData = new char[len];
	char *p1 = pImgData;
	char *p2 = image + len - width;
	for (int c=0; c<height; c++)
	{
		memcpy(p1, p2, width);
		p1 += width;
		p2 -= width;
	}

	CImage img;
	img.Create(width, height, 8);	
	img.SetColorTable(0, 256, m_GrayTable);
	BYTE *pData = NULL;
	if (img.GetPitch() < 0)
	{
		pData = (BYTE*)img.GetBits()+(img.GetPitch()*(img.GetHeight()-1)); 
	}
	else
	{
		 pData = (BYTE*)img.GetBits();
	}
	memcpy(pData, pImgData, width*height);
	CDC *dc = GetDlgItem(IDC_STATIC_PICTURE)->GetDC();
	HDC hdc = dc->m_hDC;
	CRect rc;
	GetDlgItem(IDC_STATIC_PICTURE)->GetClientRect(&rc);
	img.Draw(hdc, 0, 0, rc.Width(), rc.Height(), 0, 0, width, height);
	DeleteDC(hdc);
	img.Destroy();
	delete []pImgData;
}



void CSilkModuleDlg::onResult( OP_Result result, ITP_OPERATION operation, char *data, int len, int nParam1/*=0*/, int nParam2/*=0*/, int nParam3/*=0*/ )
{
	if (result == Result_OK)
	{
		UpdataList("OK!", COLOR_GREEN);
	}
	else
	{
		UpdataList("Abnormal!", COLOR_RED);
		WriteErrorFile(result, operation, data, len, nParam1, nParam2);
	}
	CString str = "";
	str.Format("time=%d", nParam3);
	UpdataList(str, COLOR_PINK);
	switch (operation)
	{
	case OP_CONNECT:
		{
			if (result == Result_OK)
			{
				GetDlgItem(IDC_STATIC_CONNECT_STAUS)->SetWindowText("连接");
			}
			UpdataList("连接", COLOR_KATRED);
		}
		break;
	case OP_DIS_CONNECT:
		{
			if (result == Result_OK)
			{
				GetDlgItem(IDC_STATIC_CONNECT_STAUS)->SetWindowText("断开");
			}
			UpdataList("断开", COLOR_KATRED);
		}
		break;
	case OP_ENROLL:
		{
			str.Format("登记:pin=%d", nParam1);
			UpdataList(str, COLOR_KATRED);
		}
		break;
	case OP_ENROLL_IMAGE:
		{
			str.Format("图片登记:pin=%d", nParam1);
			UpdataList(str, COLOR_KATRED);
		}
		break;
	case NOTICE_IDENTIFY:
		{
			if (nParam1 == 0)
			{
				str.Format("不能识别");
			}
			else
			{
				str.Format("识别:pin=%d", nParam1);
			}
			UpdataList(str, COLOR_KATRED);
		}
		break;
	case OP_ENROLL_TMP:
		{
			str.Format("模板登记:pin=%d", nParam1);
			UpdataList(str, COLOR_KATRED);
		}
		break;
	case OP_DEL_TMP:
		{
			if (nParam1 == 0)
			{
				str.Format("删除全部模板");
			}
			else
			{
				str.Format("删除模板 pin=%d", nParam1);
			}
			UpdataList(str, COLOR_KATRED);
		}
		break;
	case OP_SCAN_IMAGE:
		{
			UpdataList("获取指纹图像", COLOR_KATRED);
			if (result == Result_OK)
			{	
				str.Format("width=%d height=%d", nParam1, nParam2);
				UpdataList(str, COLOR_BLUE);
			}
			else
			{
				switch (nParam1)
				{
				case 1:
					str.Format("1发送请求不成功");
					break;
				case 2:
					str.Format("2接收回复不成功");
					break;
				case 3:
					str.Format("3接收回复flag不成功");
					UpdataList(str, COLOR_BLUE);
					str.Format("flag=0x%x", nParam2);
					break;
				case 4:
					str.Format("4接收第一包不成功");
					break;
				case 5:
					str.Format("5接收第一包flag:MD_DATA_ERROR");
					break;
				case 6:
					str.Format("6count==0");
					break;
				case 7:
					str.Format("7校验和错误");
					break;
				case 8:
					str.Format("8接收数据包失败");
					break;
				case 9:
					str.Format("9接收数据包flag:MD_DATA_ERROR");
					break;
				case 10:
					str.Format("10PacketNum==0");
					break;
				}
				UpdataList(str, COLOR_BLUE);
			}
		}
		break;
	case OP_GET_TIME:
		{
			UpdataList("获取时间", COLOR_KATRED);
			int date = nParam1;
			int time = nParam2;

			int year = (date & 0xFF) + 2000;
			date >>= 8;
			int month = date & 0xFF;
			date >>= 8;
			int day = date & 0xFF;

			int hour = time & 0xFF;
			time >>= 8;
			int min = time & 0xFF;
			time >>= 8;
			int sec = time & 0xFF;
			str.Format("%d-%d-%d:%d-%d-%d", year, month, day, hour, min, sec);
			UpdataList(str, COLOR_BLUE);
		}
		break;
	case OP_SET_TIME:
		{
			UpdataList("设置时间", COLOR_KATRED);
		}
		break;
	case OP_DEL_USER:
		{
			UpdataList("删除用户", COLOR_KATRED);
			str.Format("pin=%d", nParam1);
		}
		break;
	case OP_READ_USER:
		{
			UpdataList("读取用户", COLOR_KATRED);
			if (nParam1 > 0)
			{
				TUser user;
				memcpy(&user, data, len);
				str.Format("pin=%d name=%s", user.PIN, user.Name);
			}
			else if(nParam1 == 0)
			{
				str.Format("没有此用户");
			}
			UpdataList(str, COLOR_BLUE);
		}
		break;
	case OP_LOAD_LOG:
		{
			UpdataList("下载日志", COLOR_KATRED);

			PMAttLog pLog = (PMAttLog)data;
			int count = len / sizeof(TMAttLog);
			for (int i=0; i<count; i++)
			{
				str.Format("pin=%d event=%d\r\n", pLog->PIN, pLog->Event);
				pLog++;
				UpdataList(str, COLOR_BLUE);
			}
		}
		break;
	case OP_DEL_LOG:
		{
			UpdataList("删除日志", COLOR_KATRED);
		}
		break;
	case OP_SYS_READ_PARAM:
		{
			UpdataList("读取参数", COLOR_KATRED);
			DevParam param;
			memcpy(&param, data, len);
			if (param.saveLog == 0x30)			//是否保存日志
			{
				str.Format("saveLog=off");
			}
			else if (param.saveLog == 0x31)
			{
				str.Format("saveLog=on");
			}
			else
			{
				str.Format("saveLog=unknow");
			}
			UpdataList(str, COLOR_BLUE);

			str.Format("timeOut=%d", param.timeOut-0x30);	//超时时间
			UpdataList(str, COLOR_BLUE);

			if (param.autoACK == 0x30)					//是否回应
			{
				str.Format("autoACK=无应答");
			}
			else if (param.autoACK == 0x31)
			{
				str.Format("autoACK=有应答");
			}
			else
			{
				str.Format("autoACK=unknow");
			}
			UpdataList(str, COLOR_BLUE);

			char c1 = param.fwVer >> 24;		//固件版本号
			char c2 = (param.fwVer >> 16 & 0xFF);
			char c3 = (param.fwVer >> 8 & 0xFF);
			char c4 = (param.fwVer & 0xFF);
			str.Format("fwVer=%c%c.%c%c", c1, c2, c3, c4);
			UpdataList(str, COLOR_BLUE);

			int baudrate = 0;					//波特率
			switch (param.baudrate)
			{
			case 0x31:
				str.Format("baudrate=9600");
				break;
			case 0x32:
				str.Format("baudrate=19200");
				break;
			case 0x33:
				str.Format("baudrate=38400");
				break;
			case 0x34:
				str.Format("baudrate=57600");
				break;
			case 0x35:
				str.Format("baudrate=115200");
				break;
			default:
				str.Format("baudrate=unknow");
				break;
			}
			UpdataList(str, COLOR_BLUE);

			str.Format("enrollFp=%d", param.enrollFp);
			UpdataList(str, COLOR_BLUE);

			str.Format("fpCount=%d", param.fpCount);
			UpdataList(str, COLOR_BLUE);

			str.Format("userCount=%d", param.userCount);
			UpdataList(str, COLOR_BLUE);

			str.Format("logNum=%d", param.logNum);
			UpdataList(str, COLOR_BLUE);

			str.Format("logCount=%d", param.logCount);
			UpdataList(str, COLOR_BLUE);

			int year = (param.buildTime >> 16 & 0xFF);					//创建日期
			int month = (param.buildTime >> 8 & 0xFF);
			int day = (param.buildTime & 0xFF);
			str.Format("buildTime=%x-%x-%x", year+0x2000, month, day);		
			UpdataList(str, COLOR_BLUE);

			str.Format("moduleID=%d", param.moduleID);
			UpdataList(str, COLOR_BLUE);

			switch (param.workMode)
			{
			case 0x30:
				str.Format("workMode=验证模式");
				break;
			case 0x31:
				str.Format("workMode=读头(图片)");
				break;
			case 0x32:
				str.Format("workMode=读头(模板)");
				break;
			default:
				str.Format("workMode=unknow");
				break;
			}
			UpdataList(str, COLOR_BLUE);

			switch (param.tmpFormat)
			{
			case 0x30:
			case 0x31:
				str.Format("模板格式=ZK");
				break;
			case 0x32:
				str.Format("模板格式=Ansi 378");
				break;
			case 0x33:
				str.Format("模板格式=19794-2");
				break;
			default:
				str.Format("模板格式=unknown");
			}
			UpdataList(str, COLOR_BLUE);
		}
		break;
	case OP_SYS_WRITE_PARAM:
		{
			UpdataList("设置参数", COLOR_KATRED);
		}
		break;
	case OP_SYS_SAVE_PARAM:
		{
			UpdataList("保存参数", COLOR_KATRED);
		}
		break;
	case OP_ADD_USER:
		{
			UpdataList("增加用户", COLOR_KATRED);
			str.Format("pin=%d name=%s", nParam1, data);
			UpdataList(str, COLOR_BLUE);
		}
		break;
	case OP_LOAD_USER:
		{
			UpdataList("下载用户", COLOR_KATRED);
			PUser pUser = (PUser)data;
			int count = len / sizeof(TUser);
			for (int i=0; i<count; i++)
			{
				str.Format("pin=%d name=%s", pUser->PIN, pUser->Name);
				pUser++;
				UpdataList(str, COLOR_BLUE);
			}
		}
		break;
	case OP_READ_TMP:
		{
			UpdataList("读取模板", COLOR_KATRED);
			str.Format("Tmp lenght=%d", len);
			UpdataList(str, COLOR_BLUE);
			/*str.Format("OP_READ_TMP\r\nThe len of Tmp=%d", pdu->m_len);
			SetText(pdu, str);
			FILE *pf = fopen("..\\bin\\fp.tmp", "w");
			if (pf == NULL)
			{
				return;
			}
			fwrite(pdu->m_data, pdu->m_len, 1, pf);
			fclose(pf);*/
		}
		break;
	case OP_LOAD_TMP:
		{
			UpdataList("下载模板", COLOR_KATRED);
			//PTemplate pTmp = (PTemplate)data;
			int count = len / sizeof(TTemplate);
			if (len % sizeof(TTemplate) != 0)
			{
				count++;
			}
			str.Format("Tmp count=%d", count);
			UpdataList(str, COLOR_BLUE);
		}
		break;
	case OP_VERIFY:
		{
			UpdataList("指纹识别", COLOR_KATRED);
		}
		break;
	case OP_DEL_DB:
		{
			UpdataList("删除数据库", COLOR_KATRED);
		}
		break;
	case OP_UPDATA:
		{
			UpdataList("固件升级", COLOR_KATRED);
		}
		break;
	case OP_SCAN_TMP:
		{
			UpdataList("扫描模板", COLOR_KATRED);
			str.Format("模板长度=%d", nParam1);
			UpdataList(str, COLOR_BLUE);
		}
		break;
	}
	UpdataList("------------------------", COLOR_YELLOW);
}

void CSilkModuleDlg::UpdataList( CString status, COLORREF color )
{
	CString str;
	COLORREF bkcolor = RGB(255, 255, 255);
	m_pListState->InsertItem(m_ListIndex, TEXT(""));
	str.Format(TEXT("%08x_%08x"), color, bkcolor);
	m_pListState->SetItemText(m_ListIndex, 0, str);

	m_pListState->SetItemText(m_ListIndex, 1, status);

	m_pListState->SetColumnWidth(3, -2);
	m_pListState->EnsureVisible(m_pListState->GetItemCount() - 1, true);
	m_ListIndex++;
}

void CSilkModuleDlg::OnNMCustomdrawListStatus(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMCUSTOMDRAW pNMCD = reinterpret_cast<LPNMCUSTOMDRAW>(pNMHDR);
	//*pResult = 0;
	LPNMLVCUSTOMDRAW pNMLVCD = (LPNMLVCUSTOMDRAW)pNMHDR;

	switch(pNMLVCD->nmcd.dwDrawStage)
	{
	case CDDS_PREPAINT:
		{
			*pResult = CDRF_NOTIFYITEMDRAW;
			return;
		}
	case CDDS_ITEMPREPAINT:
		{
			*pResult = CDRF_NOTIFYSUBITEMDRAW;
			return;
		}
	case CDDS_ITEMPREPAINT | CDDS_SUBITEM:
		{
			int item, clr = 0, bkclr = 0;
			CString str;

			item = static_cast<int>(pNMLVCD->nmcd.dwItemSpec);
			str = m_pListState->GetItemText(item, 0);
			_stscanf_s(str, "%08x_%08x", &clr, &bkclr);

			pNMLVCD->clrText = clr;
			pNMLVCD->clrTextBk = bkclr;

			*pResult = CDRF_DODEFAULT;
			return;
		}
	default:
		*pResult = CDRF_DODEFAULT;
	}
}

void CSilkModuleDlg::OnBnClickedButtonScanTem()
{
	m_pUser->scanTmp();
}

//void CSilkModuleDlg::WriteErrorFile( ITP_OPERATION operation )
void CSilkModuleDlg::WriteErrorFile( OP_Result result, ITP_OPERATION operation, char *data, int len, int nParam1/*=0*/, int nParam2/*=0*/, int nParam3/*=0*/ )
{
	CString strOp = m_mapOp[operation];
	CString strRe = m_mapRe[result];
	strOp += " ";
	strOp += strRe;
	strOp += "\r\n";
	CString str; //获取系统时间 　　
	CTime tm; 
	tm = CTime::GetCurrentTime();
	str = tm.Format("%Y-%m-%d-%H-%M-%S: ");
	str += strOp;
	fwrite(str, str.GetLength(), 1, m_errorFile);
	fflush(m_errorFile);
}
void CSilkModuleDlg::OnBnClickedButtonReset()
{
	m_pUser->reset();
}
