// YAServerDlg.cpp : 实现文件
//
#include <stdio.h>
#include <windows.h>
#include <cstdio>
#include <process.h>
#include <exception> 

#include "stdafx.h"
#include "YAServer.h"	
#include "YAServerDlg.h"
#include "afxdialogex.h"
#include <sio_client.h>
#include <condition_variable>
#include <string>
#include "def.h"
#include "socketdef.h"
#include <Functions/Functions.h>
//#include <json/json.h>

#include "MysqlConnPool.h"
#include "locate_algorithm.h"
#include <strconv/strconv.h>
#include <kalman/locate.h>
#include "log_def.h"
#include "DbSettingDlg.h"
#include "LogSetting.h"
#include "SysSetting.h"

#include "uwb_msg_def.h"

#include "ProcessRemodule.h"
#include "log_process_module.h"

#include "./system_basic_info/SystemAnalysis.h"
#include "./debug_server/debug_server_socket.h"
#include "./system_basic_info/SystemAnalysis.h"
#include "./CSVparser/CSVparser.h"
#include "./KNN/KNN.h"
#include "algorithm/Fit.h"
#include "mylog/log_module.h"

// 用来跟踪内存使用情况
#define TRACE_MEMORY_WRITELOG
#define TRACE_MEMORY_PARSE_PACKAGE
#define TRACE_MEMORY_PARSE_SERVER
#define TRACE_MEMORY_SYNCTIMEMSG
#define TRACE_MEMORY_TAGMSG
// -- 用来跟踪内存使用情况

#define STR_LEN_TIME 30

BOOL m_log_sys_status = false;

char* InavMovingStatusStr[] = {"Static", 
	"Moving"};
char *InavDirectoryStr[] = {"No Directory",
	"Forward",
	"Backward",
	"Leftward",
	"Rightward"};
char * InavAccerateStatusStr[] = {"Not Accerate",
	"Accerate",
	"SlowDown"};


#ifdef _DEBUG
#ifndef DEBUG_NEW
#define new DEBUG_NEW
#endif
#endif

// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
#include "ProcessRemodule.h"

DWORD g_tickcount;
DWORD g_diffTickCount = 0;
DWORD g_send_tickout;
DWORD g_last_send_time;
DWORD g_testtick;
bool g_is_rec_hist = false;
bool g_is_up_mine = false;

#pragma warning(disable: 4244)
#pragma warning(disable: 4018)

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

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

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

	// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}

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

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()

// CYAServerDlg 对话框

CYAServerDlg::CYAServerDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(CYAServerDlg::IDD, pParent),
	_server(this),
	_io(new client())
	, m_reader_id_hist(0)
{
	ws_init();
	init_smart_pointer_var();
	Log::init_log_module();
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CYAServerDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_BTN_START, m_btStart);
	DDX_Control(pDX, IDC_BTN_STOP, m_btStop);
	DDX_Control(pDX, IDC_LIST_READER, m_listctrl_reader);
	DDX_Control(pDX, IDC_LIST_LOG, m_list_log);	
	DDX_Text(pDX, IDC_EDIT_READERID, m_reader_id_hist);
}

BEGIN_MESSAGE_MAP(CYAServerDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BTN_START, &CYAServerDlg::OnBnStart)
	ON_BN_CLICKED(IDC_BTN_STOP, &CYAServerDlg::OnBnStop)
	ON_BN_CLICKED(IDC_BTN_EXIT, &CYAServerDlg::OnBnExit)
	ON_BN_CLICKED(IDC_BTN_SYNCTIME, &CYAServerDlg::OnBnSyncTime)
	ON_MESSAGE(WM_ON_MONITOR, on_monitor)
	ON_COMMAND(ID_START, &CYAServerDlg::OnBnStart)
	ON_COMMAND(ID_STOP, &CYAServerDlg::OnBnStop)
	ON_COMMAND(ID_EXIT, &CYAServerDlg::OnBnExit)
	ON_COMMAND(ID_MENU_DB, &CYAServerDlg::OnMenuDb)
	ON_COMMAND(ID_MENU_LOG, &CYAServerDlg::OnMenuLog)
	ON_COMMAND(ID_MENU_PARAM, &CYAServerDlg::OnMenuParam)
	ON_BN_CLICKED(IDC_BTN_HIS, &CYAServerDlg::OnBnCallHisData)
	ON_MESSAGE(WM_REFRESH_IP_LIST, &CYAServerDlg::OnMsgRefreshIpList)
	ON_MESSAGE(WM_REMOVE_SOCKET, &CYAServerDlg::OnRemoveSocket)
	ON_EN_UPDATE(IDC_EDIT_READERID, &CYAServerDlg::OnEnUpdateEditReaderid)
	ON_COMMAND(ID_ABOUT, &CYAServerDlg::OnAbout)
	ON_BN_CLICKED(IDC_BUTTON1, &CYAServerDlg::OnBnClickedButton1)
	ON_MESSAGE(WM_CARD_SEND_JSON,&CYAServerDlg::UpdateCardMessage)
END_MESSAGE_MAP()

// CYAServerDlg 消息处理程序

UINT WaitForS(int nSecond,bool bSleep=false)//用于等待一段时间的函数,普通精度的，参数单位秒	
{
	COleDateTime start_time = COleDateTime::GetCurrentTime();
	COleDateTimeSpan end_time = COleDateTime::GetCurrentTime()-start_time;
	while(end_time.GetTotalSeconds() < nSecond){
		if(!bSleep){
			MSG msg;
			PeekMessage(&msg,NULL,0,0,PM_NOREMOVE);
			TranslateMessage(&msg); 
			DispatchMessage(&msg);
			//以上四行是实现在延时或定时期间能处理其他的消息，降低CPU的占有率，但也降低延时或定时精度
		}
		Sleep(80);
		end_time = COleDateTime::GetCurrentTime()-start_time;
	}
	return 0;
}

UINT WaitForMS(int mSecond,bool bSleep=false)//高精度的等待函数，参数单位毫秒
{
	double dfFreq; 
	LARGE_INTEGER litmp; 
	QueryPerformanceFrequency(&litmp);
	dfFreq = (double)litmp.QuadPart;// 获得计数器的时钟频率

	QueryPerformanceCounter(&litmp);
	LONGLONG QPart0 = litmp.QuadPart;// 获得初始值
	while((double)(litmp.QuadPart-QPart0)/dfFreq < double(mSecond/1000)){
		if(!bSleep){
			MSG msg;
			PeekMessage(&msg,NULL,0,0,PM_NOREMOVE);
			TranslateMessage(&msg); 
			DispatchMessage(&msg);
			//以上四行是实现在延时或定时期间能处理其他的消息，降低CPU的占有率，但也降低延时或定时精度
		}
		QueryPerformanceCounter(&litmp);
	}
	return 0;
}

ULONGLONG time_send_json_counting;
ULONGLONG time_send_json_device_state;
ULONGLONG time_send_json_alarm;
ULONGLONG time_send_json_postion;
ULONGLONG time_sync_reader_time;
ULONGLONG time_clear_call_time;
ULONGLONG time_send_call;
ULONGLONG time_send_help;
ULONGLONG time_ws_connect;
ULONGLONG time_send_heart;
ULONGLONG time_driving_face_check_interval;
ULONGLONG time_send_cell;

volatile LONG g_QueueItemCount = 0;
bool g_exit=false;
long giSqlCount=0;
long giSqlThreadCount=0;
long gSqlTimes=0;
long giAllSqlCount=0;
long giAllThreadCount=0;
HANDLE hSemaHandle=NULL;

//DWORD WINAPI _exec_sql(LPVOID lparam)
DWORD WINAPI _exec_sql(const char * lparam)
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_85);
	::InterlockedIncrement(&g_QueueItemCount);
	if(NULL == lparam)
	{
		debug_print_syslog(0, "_exec_sql error: lparam is NULL");
		return 1;
	}
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);
	if(pConn == NULL)
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_86);
		::InterlockedDecrement(&g_QueueItemCount);
		return 1;
	}
	int err = 0;

	pConn->MultiExecute(lparam, err);

	if(err > 0){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_87);
		debug_print_syslog(0, "sql error: %d", err);

		debug_print_syslog(0, "sql: %s", lparam);
	}

	::InterlockedDecrement(&g_QueueItemCount);
	return 0;
}

DWORD WINAPI _write_error_log(LPVOID lparam)
{
	::InterlockedIncrement(&g_QueueItemCount);
	LogInfo* err =  (LogInfo*)lparam;
	CYAServerDlg* dlg = reinterpret_cast<CYAServerDlg*>(err->handle);
#ifdef TRACE_MEMORY_WRITELOG
	dlg->writeErrorLogEx(err->path, err->strLog, err->useTime);
#endif // TRACE_MEMORY_WRITELOG

	if(err){
		free(err->path);
		err->path = NULL;
		free(err->strLog);
		err->strLog = NULL;

		delete err;
		err = NULL;
	}
	//Sleep(1);
	::InterlockedDecrement(&g_QueueItemCount);
	return 0;
}

DWORD WINAPI _parse_package_data(LPVOID lparam)
{
	::InterlockedIncrement(&g_QueueItemCount);
	ParseData* data =  (ParseData*)lparam;
	CYAServerDlg* dlg = reinterpret_cast<CYAServerDlg*>(data->handle);
#ifdef TRACE_MEMORY_PARSE_PACKAGE
	dlg->parse_package_data(data->buf, data->len, data->dwConnID);
#endif // TRACE_MEMORY_PARSE_PACKAGE

	free(data);
	//Sleep(1);
	::InterlockedDecrement(&g_QueueItemCount);
	return 0;
}

DWORD WINAPI _parse_data_server(LPVOID lparam)
{
	::InterlockedIncrement(&g_QueueItemCount);
	ParseData* data =  (ParseData*)lparam;
	CYAServerDlg* dlg = reinterpret_cast<CYAServerDlg*>(data->handle);
#ifdef TRACE_MEMORY_PARSE_SERVER
	dlg->parse_data_server(data->buf, data->len, data->dwConnID);
#endif 
	data->handle->m_nMallocTimes--;
	delete data;
	data = NULL;
	Sleep(1);
	::InterlockedDecrement(&g_QueueItemCount);
	return 0;
}

UINT _thread_timer(LPVOID lparam)//给web发送的定时器线程
{
	CYAServerDlg* dlg = reinterpret_cast<CYAServerDlg*>(lparam);
	ULONGLONG cur_time = ::GetTickCount();
	while(!g_exit){
		cur_time =::GetTickCount();
		//send_json_counting
		//if(cur_time - time_send_json_counting > theApp.send_json_counting ){
		//	time_send_json_counting = cur_time;
		//	std::string ret = "";
		//	ret = dlg->get_json_counting();
		//	if (ret != "")
		//	{
		//		dlg->send_json_data(JSON_CMD_VALUE_PUSH, ret); // web端统计
		//	}	

		//	//推送区域总数
		//	ret = "";
		//	ret = dlg->get_json_count_area();
		//	dlg->send_json_data(JSON_CMD_VALUE_PUSH,ret);
		//}
		// send_json_alarm
		if(cur_time - time_send_json_alarm > theApp.send_json_alarm){
			time_send_json_alarm = cur_time; 

			dlg->deal_card_lost_state();
			dlg->send_json_data(JSON_CMD_VALUE_PUSH, dlg->get_json_event());
		}
		// send_json_device
		if(cur_time - time_send_json_device_state > theApp.send_json_device){
			time_send_json_device_state = cur_time; 
			dlg->deal_readers();
			dlg->send_json_data(JSON_CMD_VALUE_PUSH, dlg->get_json_device_state());
		}
		//send_json_postion
		if(cur_time - time_send_json_postion > theApp.send_json_postion){
			time_send_json_postion = cur_time;
			dlg->modify_card_speed(5);
			//dlg->package_data();
		}
		//send help 
		if(cur_time - time_send_help > theApp.send_json_alarm){
			time_send_help = cur_time;
			if(dlg->get_help_card_nums() > 0){				
				dlg->send_json_data(JSON_CMD_VALUE_PUSH,dlg->get_json_help());
			}	
		}
		// send_call_data
		if(cur_time - time_send_call > theApp.send_json_alarm){
			std::string call_list = "";
			call_list = dlg->get_json_call_list();
			if (call_list != "")
			{
				dlg->send_json_data(JSON_CMD_VALUE_PUSH,call_list);
			}

			time_send_call = cur_time;	
			dlg->send_call_info();
			dlg->clear_call_info();
		}

		if(!dlg->is_websocket_login && cur_time - time_ws_connect > theApp.ws_connect_interval){
			time_ws_connect = cur_time;
			if(!dlg->is_websocket_ok){
				dlg->ws_open();
			}
			dlg->ws_login();
		}
		
        // update driving face status
		if(cur_time - time_driving_face_check_interval > 3000){
			time_driving_face_check_interval = cur_time;	
			//check driving face shift state
			int shift_id = 0;
	        dlg->GetCurShiftStartTime(shift_id);
			
			if(shift_id != dlg->cur_shift_id)
			{
			    dlg->cur_shift_id = shift_id;
				dlg->driving_face_shift_start();
			}
			dlg->send_drivingface_card_position_json();
		}
		//if (cur_time - time_send_heart > theApp.heart_interval)
		//{
		//	time_send_heart = cur_time;
		//	//dlg->send_heart_package();
		//}
		WaitForMS(10);
	}
	return 0;
}

UINT _thread_monitor(LPVOID lparam)
{
	CYAServerDlg* dlg = reinterpret_cast<CYAServerDlg*>(lparam);
	time_t time_end = time(NULL);
	while (!g_exit){
		time_t time_current = time(NULL);
		// 判断采集状态， 20s没有接收到数据认为采集中断 
		dlg->is_server_ok = (difftime(time_current, dlg->m_time_last_rec) > 20) ? false : true;
		dlg->set_run_state(); // 更新采集运行状态

		if(!IsWindow(theApp.m_hwnd_monitor)){ // 监控程序没有打开
			theApp.m_hwnd_monitor = NULL;
			//// 启动监控程序
			//if(strlen(theApp.m_path_monitor)<=0){
			//	strcpy(theApp.m_path_monitor, "YAMonitor.exe");//启动同目录下的monitor
			//}
			//WinExec(theApp.m_path_monitor, SW_HIDE);
		}
		// 发送给监控程序
		if(theApp.m_hwnd_monitor && dlg->is_start_tcp ){
			WPARAM wpSERVERSTATE=WPARAM(dlg->m_uint_state);
			::PostMessage(theApp.m_hwnd_monitor, WM_ON_MONITOR, wpSERVERSTATE, LPARAM(dlg->m_hWnd));
		}else{

		}
		WaitForS(10);
	}
	return 0;
}

UINT thread_cell(LPVOID lparam)//处理格子的移动和写库
{
	CYAServerDlg* dlg = reinterpret_cast<CYAServerDlg*>(lparam);
	int i = 0;
	while (true)
	{
		//处理格子信息
		int nRet = dlg->ModifyCardInfo();
		//nRet表示有多少张卡参与了补格子
		if (nRet)
		{
			SetEvent(dlg->hEvent);
		}
	}
	return 0;
}

UINT thread_send_cell_data(LPVOID lparam)
{
	CYAServerDlg* dlg = reinterpret_cast<CYAServerDlg*>(lparam);

	while (false)
	{
		//等待有信号状态
		//WaitForSingleObject(dlg->hEvent,INFINITE);
		////置为无信号状态
		//ResetEvent(dlg->hEvent);
		////将新增的格子存入数据库
		//dlg->SaveCellData2DB();
		////将新增的格子发送json
		//dlg->package_data();
		//SetEvent(dlg->hEvent);
	}

	return 0;
}

BOOL CYAServerDlg::OnInitDialog()
{
	CDialogEx::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);
		}
	}

	//加载系统配置
	m_bUseFilter = theApp.use_filter;
	if(m_bUseFilter){
		m_nFilterType = FILTER_KALMAN;
	}else{
		m_nFilterType = NO_FILTER;
	}

	m_log_sys_status = theApp.log_sys_status;
	m_log_raw_data   = theApp.log_raw_data;
	m_log_parse_data = theApp.log_parse_data;
	m_log_send_package = theApp.log_send_package;
	m_log_recv_package = theApp.log_recv_package;
	m_log_locate_data  = theApp.log_locate_data;

	m_reader_interval_time = theApp.reader_interval_time * 1.0 / 1000.0;
	cur_shift_id = 0;

	m_nMallocTimes = 0;

	//初始化线程池
	//m_LogThreadPool.Initialize((void*)100,THREADPOOL_SIZE);
	// 设置此对话框的图标。当应用程序主窗口不是对话框时，框架将自动
	// 执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	init_queuestring();
	init_param();
	init_ui();

	init_base_data();
	load_his_data();

	theApp.set_server_handle(this->m_hWnd);	
	theApp.load_monitor_conf();

	RECT rc;
	GetWindowRect(&rc);
	rc.left=rc.right;
	rc.right+=250;

	//创建菜单
	m_mnMain.LoadMenu(IDR_MENUMAIN);
	SetMenu(&m_mnMain);
	CString strInfo;

	//// 将图标放入系统托盘
	//nd.cbSize	= sizeof (NOTIFYICONDATA);
	//nd.hWnd	= m_hWnd;
	//nd.uID	= IDI_ICON;
	//nd.uFlags	= NIF_ICON|NIF_MESSAGE|NIF_TIP;
	//nd.uCallbackMessage= WM_NOTIFYICON;
	//nd.hIcon	= m_hIcon;

	//strcpy(nd.szTip, "采集应用服务器");
	//Shell_NotifyIcon(NIM_ADD, &nd);

	m_thread_monitor = ::AfxBeginThread(_thread_monitor, this, THREAD_PRIORITY_HIGHEST);

	time_send_json_counting = time_send_json_device_state=time_send_json_alarm=time_send_json_postion=::GetTickCount();
	time_sync_reader_time=time_clear_call_time=time_send_call=time_send_help=::GetTickCount();
	time_driving_face_check_interval=::GetTickCount();
	//发送数据20170705
	m_thread_timer = ::AfxBeginThread(_thread_timer, this, THREAD_PRIORITY_HIGHEST);

	pCellThread = ::AfxBeginThread(thread_cell,this,THREAD_PRIORITY_NORMAL);
	pSendCellThread = ::AfxBeginThread(thread_send_cell_data,this,THREAD_PRIORITY_NORMAL);

	hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
	ResetEvent(hEvent);
	bSend = false;

	SetWindowText(_T("永安信通数据采集系统"));
	OnBnStart();

#ifndef _DEBUG
	((CButton*)GetDlgItem(IDC_BUTTON1))->ShowWindow(SW_HIDE);
#endif

	UpdateData(FALSE);
	debug_print_syslog(0, "Server dialog init success.");
	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

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

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

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

		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
	{
		CDialogEx::OnPaint();
	}
}

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

/*
* 点击启动按钮
*		登录websocket服务器
*		启动tcp server
*
* param
*		无
*
* return
*		无
*
*/
void CYAServerDlg::OnBnStart()
{
<<<<<<< HEAD
#ifndef _DEBUG
	ReadFileTest();
#endif // !_DEBUG
=======
>>>>>>> newprotocal
	if(!is_websocket_login){
		ws_login();
	}
	start_tcp_server();
}

/*
* 点击停止按钮
*		退出websocket服务器
*		停止tcp server
*
* param
*		无
*
* return
*		无
*
*/
void CYAServerDlg::OnBnStop()
{
	stop_tcp_server();
	if(is_websocket_login){
		ws_logout();
	}
}

LRESULT CYAServerDlg::on_monitor(WPARAM wParam, LPARAM lParam)
{
	if(is_start_tcp){
		m_uint_state = wParam ;
	}
	if(wParam == 0xFFFF){
		stop_and_exit();
	}
	return S_OK;
}

int CYAServerDlg::init_smart_pointer_var()
{
	mp_reader_path_list_tdoa = std::make_shared<TDOAReaderPathMap>();
	mp_reader_path_list = std::make_shared<ReaderPathMap>();

	mp_card_list_over_time_person = std::make_shared<CardMap>();
	mp_card_list_forbidden_person = std::make_shared<CardMap>();
	mp_card_list_help = std::make_shared<CardMap>();
	mp_card_list_area_over_time_person = std::make_shared<CardMap>();
	mp_card_list_forbidden_vehicle = std::make_shared<CardMap>();
	mp_card_list_over_time_vehicle = std::make_shared<CardMap>();
	mp_card_list_over_speed_vehicle = std::make_shared<CardMap>();
	mp_card_list_area_over_time_vehicle = std::make_shared<CardMap>();
	mp_card_list_over_count_person = std::make_shared<CardMap>();

	mp_area_over_count_person = std::make_shared<AreaMap>();
	mp_area_over_time_person = std::make_shared<AreaMap>();
	mp_area_forbidden_person = std::make_shared<AreaMap>();
	mp_area_over_count_vehicle = std::make_shared<AreaMap>();
	mp_area_over_time_vehicle = std::make_shared<AreaMap>();
	mp_area_forbidden_vehicle = std::make_shared<AreaMap>();

	mp_event_list = std::make_shared<EventMap>();
	mp_light_call_list = std::make_shared<LightCallMap>();

	return 0;
}
#ifdef CERTIFY_READER_RANGE_AREA
int CYAServerDlg::init_reader_range_area()
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);
	if(pConn == NULL){
		return 1;
	}
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	

	sprintf_s(strsql, "SELECT reader_range_area_id, name, map_id, path \
					  FROM dat_reader_range_area;");

	pRes = pConn->Execute(strsql, err);

	if (err)
	{
		return 1;
	}

	std::shared_ptr<Area> pArea = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		AreaMap::iterator it = mp_reader_range_area_list.find(atoi(pRow[0]));		
		if(it != mp_reader_range_area_list.end()){
			pArea = it->second;
		}else{
			pArea = std::make_shared<Area>();
			pArea->area_id = atoi(pRow[0]);
			mp_reader_range_area_list.insert(make_pair(pArea->area_id, pArea));
			nRow++;
		}

		pArea->map_id = atoi(pRow[2]);
		MapInfoMap::iterator map_it = mp_map_list.find(pArea->map_id);
		if(map_it != mp_map_list.end()){
			AreaMap::iterator area_it = map_it->second->map_area_list.find(pArea->area_id);
			if(area_it == map_it->second->map_area_list.end()){
				map_it->second->map_area_list.insert(make_pair(pArea->area_id, pArea));
			}
		}

		pArea->area_name = pRow[1];
		pArea->path = pRow[3]; // 多边形
		pArea->init_border(pRow[3]);
	}
	mysql_free_result(pRes);

	//CString strlog;
	//strlog.Format(_T("%s%d%s"), _T(LOG_INIT_AREA), nRow, _T(LOG_RECORD_COUNT));
	//show_log(strlog);
	return 0;
}
#endif // CERTIFY_READER_RANGE_AREA

/*
* 初始化对话框ui
*
* param
*		无
*
* return
*		无
*
*/
void CYAServerDlg::init_ui()
{
	set_app_state(ST_STOPPED);
	m_listctrl_reader.SetColumnHeader(_T("分站号,50;分站地址,100;状态,50;类型,60"));
	m_listctrl_reader.SetGridLines(TRUE);
	m_listctrl_reader.SetEditable(FALSE);
	m_listctrl_reader.SetSortable(FALSE);

	Invalidate(FALSE);
}

void CYAServerDlg::set_app_state( EnAppState eas )
{
	m_enState = eas;

	if(this->GetSafeHwnd() == nullptr)
		return;

	m_btStart.EnableWindow(m_enState == ST_STOPPED);
	m_btStop.EnableWindow(m_enState == ST_STARTED);

	GetDlgItem(IDC_BTN_HIS)->EnableWindow(m_enState == ST_STARTED);
	GetDlgItem(IDC_BTN_SYNCTIME)->EnableWindow(m_enState == ST_STARTED);

	CMenu* pMenu = GetMenu();
	ASSERT_VALID (pMenu);
	if(m_enState == ST_STOPPED){
		pMenu->EnableMenuItem(ID_START,MF_BYCOMMAND | MF_ENABLED);//启用
		pMenu->EnableMenuItem(ID_STOP,MF_BYCOMMAND | MF_GRAYED);//禁用
	}else if(m_enState == ST_STARTED){
		pMenu->EnableMenuItem(ID_START,MF_BYCOMMAND | MF_GRAYED);//禁用
		pMenu->EnableMenuItem(ID_STOP,MF_BYCOMMAND | MF_ENABLED);//启用		
	}
}

void CYAServerDlg::init_param()
{
	::SetMainWnd(this);
	::SetInfoList(&m_list_log);
	g_last_send_time = ::GetTickCount();
	m_time_last_rec = time(NULL);

	m_nPort = PORT_SERVER_MASTER;
	m_nCountClick = 0;
	m_ws_url = TEST_WS_URL;
	m_tcp_host = LOCAL_ADDRESS;

	is_server_ok = true;
	is_start_tcp = false;
	g_exit = false;

	GetCurShiftStartTime(m_shift_id);
	umpRootSyncNum.swap(unordered_map<unsigned long long, unsigned short>());

	for(int i = 0; i < MINE_EVENT_COUNT; i++){
		m_event_list[i] = 0;
	}

	InitializeCriticalSectionAndSpinCount(&m_csWriteLog, MAXCRITICALSECTIONSPINCOUNT);
	InitializeCriticalSectionAndSpinCount(&m_csRefreshList, MAXCRITICALSECTIONSPINCOUNT);	
	InitializeCriticalSectionAndSpinCount(&m_csRemoveSocket, MAXCRITICALSECTIONSPINCOUNT);
	InitializeCriticalSectionAndSpinCount(&m_csParseDataServer, MAXCRITICALSECTIONSPINCOUNT);
	InitializeCriticalSectionAndSpinCount(&m_csSyncTime, MAXCRITICALSECTIONSPINCOUNT);
	InitializeCriticalSectionAndSpinCount(&m_csCallInfo, MAXCRITICALSECTIONSPINCOUNT);

	//从配置中读取(regedit)
	load_param_from_ini();
	database_connect();
}

void CYAServerDlg::stop_and_exit()
{
	if(is_start_tcp){
		stop_tcp_server();
	}
	if(is_websocket_login){
		ws_logout();
	}

	g_exit = true;
	if(m_thread_monitor){
		WaitForSingleObject(m_thread_monitor->m_hThread, 0);
	}
	m_thread_monitor = NULL;
	if(m_thread_timer){
		WaitForSingleObject(m_thread_timer->m_hThread, 0);
	}
	m_thread_timer = NULL;

	if (pCellThread)
	{
		WaitForSingleObject(pCellThread->m_hThread,0);
	}
	pCellThread = NULL;

	if(m_qsmSQL){
		m_qsmSQL->Execute();
	}

	CString strlog;
	while(g_QueueItemCount >0){
		strlog.Format(_T("%s: %d"), _T(LOG_LEFT_THREAD), g_QueueItemCount);
		show_log(strlog);
		WaitForMS(3000);
	}

	::SetMainWnd(NULL);
	::SetInfoList(NULL);

	clear_all_list();
	GetConnPool().CloseAllConn();

	DeleteCriticalSection(&m_csWriteLog);
	DeleteCriticalSection(&m_csParseDataServer);
	DeleteCriticalSection(&m_csRemoveSocket);
	DeleteCriticalSection(&m_csRefreshList);
	DeleteCriticalSection(&m_csSyncTime);
	DeleteCriticalSection(&m_csCallInfo);

	CDialogEx::OnCancel();
	exit(0);
}

void CYAServerDlg::set_run_state()
{
	m_uint_state = 0;
	if(!is_server_ok){
		m_uint_state |= 0x10; // 长时间未接收到采集数据（网络故障，采集故障）
	}
}

int CYAServerDlg::init_staffer(string staff_id /* = "" */, bool is_card /*= false*/ )
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);
	if(pConn == NULL){
		return 1;
	}
	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	if(staff_id.length() == 0){
		sprintf_s(buf, "SELECT staff_id, s.card_id, c.card_type_id, s.name, \
					   s.dept_id, s.group_id, s.occupation_id,s.certification, \
					   d.name as dname, g.name as gname, ol.name as oname, ol.occupation_level_id \
					   FROM dat_staff s \
					   LEFT JOIN dat_card c ON s.card_id = c.card_id \
					   LEFT JOIN dat_dept d ON s.dept_id = d.dept_id \
					   LEFT JOIN dat_group g ON s.group_id = g.group_id \
					   LEFT JOIN dat_occupation o ON s.occupation_id = o.occupation_id \
					   LEFT join dat_occupation_level ol on ol.occupation_level_id = o.occupation_level_id \
					   WHERE c.card_type_id = 1 and s.duty_id = 0;");
	}else if(is_card){
		sprintf_s(buf, "SELECT staff_id, s.card_id, c.card_type_id, s.name, \
					   s.dept_id, s.group_id, s.occupation_id, s.certification,\
					   d.name as dname, g.name as gname, o.name as oname, ol.occupation_level_id \
					   FROM dat_staff s \
					   LEFT JOIN dat_card c ON s.card_id = c.card_id \
					   LEFT JOIN dat_dept d ON s.dept_id = d.dept_id \
					   LEFT JOIN dat_group g ON s.group_id = g.group_id \
					   LEFT JOIN dat_occupation o ON s.occupation_id = o.occupation_id \
					   LEFT join dat_occupation_level ol on ol.occupation_level_id = o.occupation_level_id \
					   WHERE c.card_type_id = 1 and s.duty_id = 0 AND s.card_id = '%s';", staff_id.c_str());
	}else{
		sprintf_s(buf, "SELECT staff_id, s.card_id, c.card_type_id, s.name, \
					   s.dept_id, s.group_id, s.occupation_id, s.certification,\
					   d.name as dname, g.name as gname, o.name as oname, ol.occupation_level_id \
					   FROM dat_staff s \
					   LEFT JOIN dat_card c ON s.card_id = c.card_id \
					   LEFT JOIN dat_dept d ON s.dept_id = d.dept_id \
					   LEFT JOIN dat_group g ON s.group_id = g.group_id \
					   LEFT JOIN dat_occupation o ON s.occupation_id = o.occupation_id \
					   LEFT join dat_occupation_level ol on ol.occupation_level_id = o.occupation_level_id \
					   WHERE c.card_type_id = 1 and s.duty_id = 0 AND staff_id = '%s';", staff_id.c_str());
	}

	pRes = pConn->Execute(buf, err);

	if (err > 0)
	{
		return 1;
	}

	std::shared_ptr<Card> pCard = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))	{
		CardMap::iterator it = mp_card_list_all.find(pRow[1]);
		if(it != mp_card_list_all.end()){
			pCard = it->second;
		}else{
			pCard = std::make_shared<Card>(pRow[1], atoi(pRow[2]), theApp.z_offset);
#ifdef ALGORITHM_TYPE_TOF
			pCard->set_reader_path_tof(mp_reader_path_list);
#elif defined ALGORITHM_TYPE_TDOA
			pCard->set_reader_path_tdoa(mp_reader_path_list_tdoa);
#endif
			mp_card_list_all.insert(make_pair(pCard->card_id, pCard));
		}
		nRow++;
		pCard->id = pRow[0];
		pCard->name = (pRow[3] == NULL ? "": pRow[3]);
		pCard->dept_id = atoi(pRow[4]);
		pCard->group_id = atoi(pRow[5]);
		pCard->number = (pRow[7] == NULL)?"":pRow[7];
		pCard->department = (pRow[8] == NULL?"":pRow[8]);
		pCard->group = (pRow[9] == NULL ? "": pRow[9]);
		pCard->occupation = (pRow[10] == NULL ? "": pRow[10]);
		pCard->occlevel_id = (pRow[11] == NULL) ? 0 : atoi(pRow[11]);

		if(m_bUseFilter){
			if(theApp.use_filter_odd){
				std::string temp = pRow[1];
				int a = atoi(temp.substr(temp.length() - 1 , 1).c_str());
				if(0 == a%2){
					pCard->EnableFilter(m_nFilterType);
				}
			}else{
				pCard->EnableFilter(m_nFilterType);
			}
		}
	}
	mysql_free_result(pRes);

	CString strlog = _T("");
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_STAFF), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

/*
* 初始化所有车卡信息
*
* param
*		vehicle_id ------	车卡id
*      is_card    ------	是否是卡
*
* return
*		成功返回0，失败返回1
*
*/
int CYAServerDlg::init_vehicle(string vehicle_id /* = "" */, bool is_card /*= false*/)
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	if(pConn == NULL){
		return 1;
	}

	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	if(vehicle_id.length() == 0){
		sprintf_s(buf, "SELECT vehicle_id, v.card_id, c.card_type_id, v.name, v.number, \
					   v.dept_id, v.group_id, v.vehicle_type_id, \
					   d.name as dname, g.name as gname, vt.name as vtname, vt.is_railroad as vt_is_railroad\
					   FROM dat_vehicle v \
					   LEFT JOIN dat_card c ON v.card_id = c.card_id \
					   LEFT JOIN dat_dept d ON v.dept_id = d.dept_id \
					   LEFT JOIN dat_group g ON v.group_id = g.group_id \
					   LEFT JOIN dat_vehicle_type vt ON v.vehicle_type_id = vt.vehicle_type_id \
					   WHERE c.card_type_id = 2 and v.state = 0;");
	}else if(is_card){
		sprintf_s(buf, "SELECT vehicle_id, v.card_id, c.card_type_id, v.name, v.number, \
					   v.dept_id, v.group_id, v.vehicle_type_id, \
					   d.name as dname, g.name as gname, vt.name as vtname, vt.is_railroad as vt_is_railroad \
					   FROM dat_vehicle v \
					   LEFT JOIN dat_card c ON v.card_id = c.card_id \
					   LEFT JOIN dat_dept d ON v.dept_id = d.dept_id \
					   LEFT JOIN dat_group g ON v.group_id = g.group_id \
					   LEFT JOIN dat_vehicle_type vt ON v.vehicle_type_id = vt.vehicle_type_id \
					   WHERE c.card_type_id = 2 and v.state = 0 AND v.card_id ='%s';", vehicle_id.c_str());
	}else{
		sprintf_s(buf, "SELECT vehicle_id, v.card_id, c.card_type_id, v.name, v.number, \
					   v.dept_id, v.group_id, v.vehicle_type_id, \
					   d.name as dname, g.name as gname, vt.name as vtname, vt.is_railroad as vt_is_railroad \
					   FROM dat_vehicle v \
					   LEFT JOIN dat_card c ON v.card_id = c.card_id \
					   LEFT JOIN dat_dept d ON v.dept_id = d.dept_id \
					   LEFT JOIN dat_group g ON v.group_id = g.group_id \
					   LEFT JOIN dat_vehicle_type vt ON v.vehicle_type_id = vt.vehicle_type_id \
					   WHERE c.card_type_id = 2 and v.state = 0 AND vehicle_id='%s';", vehicle_id.c_str());
	}
	pRes = pConn->Execute(buf, err);

	if (err > 0)
	{
		return 1;
	}

	std::shared_ptr<Card> pCard = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		CardMap::iterator it = mp_card_list_all.find(pRow[1]);
		if(it != mp_card_list_all.end()){
			pCard = it->second;
		}else{
			pCard = std::make_shared<Card>(pRow[1], atoi(pRow[2]), theApp.z_offset);
#ifdef ALGORITHM_TYPE_TOF
			pCard->set_reader_path_tof(mp_reader_path_list);
#elif defined ALGORITHM_TYPE_TDOA
			pCard->set_reader_path_tdoa(mp_reader_path_list_tdoa);
#endif
			mp_card_list_all.insert(make_pair(pCard->card_id, pCard));
		}
		nRow++;
		pCard->id = (pRow[0] == NULL) ? "" : pRow[0];
		pCard->name = (pRow[3] == NULL) ? "" : pRow[3];
		pCard->number = (pRow[4] == NULL) ? "" : pRow[4];
		pCard->dept_id = atoi(pRow[5]);
		pCard->group_id = atoi(pRow[6]);
		pCard->department = (pRow[8] == NULL) ? "" : pRow[8];
		pCard->group = (pRow[9] == NULL) ? "" : pRow[9];
		pCard->worktype = (pRow[10] == NULL) ? "" : pRow[10];
		pCard->m_nIsRailroad = (pRow[11] == NULL)? 0:atoi(pRow[11]);

		if(m_bUseFilter){
			if(theApp.use_filter_odd){
				std::string temp = pRow[1];
				int a = atoi(temp.substr(temp.length() - 1 , 1).c_str());
				if(0 == a%2){
					pCard->EnableFilter(m_nFilterType);
				}
			}else{
				pCard->EnableFilter(m_nFilterType);
			}
		}
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_VEHICLE), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

/*
* 初始化所有自组网卡信息
*
* param
*		adhoc_id   ------	自组网卡id
*       is_card    ------	是否是卡
*
* return
*		成功返回0，失败返回1
*
*/
int CYAServerDlg::init_adhoc(string adhoc_id /*= ""*/,bool is_card /*= false*/)
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);
	if(pConn == NULL){
		return 1;
	}

	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	if(adhoc_id.length() == 0){
		sprintf_s(buf,"select adhoc_id,v.card_id,v.dept_id, \
					  d.name as dname \
					  from dat_adhoc v \
					  LEFT JOIN dat_card c ON v.card_id = c.card_id \
					  LEFT JOIN dat_dept d ON v.dept_id = d.dept_id \
					  where c.card_type_id = 3 and v.state = 0 ;");
	}else if(is_card){
		sprintf_s(buf,"select adhoc_id,v.card_id,v.dept_id, \
					  d.name as dname \
					  from dat_adhoc v \
					  LEFT JOIN dat_card c ON v.card_id = c.card_id \
					  LEFT JOIN dat_dept d ON v.dept_id = d.dept_id \
					  where c.card_type_id = 3 and v.state = 0 and v.card_id ='%s';",adhoc_id.c_str());
	}else{
		sprintf_s(buf,"select adhoc_id,v.card_id,v.dept_id, \
					  d.name as dname \
					  from dat_adhoc v \
					  LEFT JOIN dat_card c ON v.card_id = c.card_id \
					  LEFT JOIN dat_dept d ON v.dept_id = d.dept_id \
					  where c.card_type_id = 3 and v.state = 0 and v.adhoc_id ='%s';",adhoc_id.c_str());
	}

	pRes = pConn->Execute(buf, err);

	if(pRes == NULL){
		return 1;
	}

	std::shared_ptr<Card> pCard = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		CardMap::iterator it = mp_card_list_all.find(pRow[1]);
		if(it != mp_card_list_all.end()){
			pCard = it->second;
		}else{
			pCard = std::make_shared<Card>(pRow[1], CT_ADHOC, theApp.z_offset);
			mp_card_list_all.insert(make_pair(pCard->card_id, pCard));
		}
		pCard->id = (pRow[0] == NULL) ? "" : pRow[0];
		pCard->card_id = (pRow[1] == NULL) ? "" : pRow[1];
		pCard->dept_id = (pRow[2] == NULL) ? 0:atoi(pRow[2]);
		pCard->department = (pRow[3] == NULL) ? "" : pRow[3];
		nRow++;
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_ADHOC), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);


	return 0;
}

int CYAServerDlg::init_map(int map_id /*= 0*/)
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);
	if(pConn == NULL){
		return 1;
	}
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	if(map_id == 0){
		sprintf_s(strsql, "SELECT map_id, name, scale FROM dat_map;");
	}else{
		sprintf_s(strsql, "SELECT map_id, name, scale FROM dat_map WHERE map_id = %d; ", map_id);
	}
	pRes = pConn->Execute(strsql, err);

	if (err > 0)
	{
		return err;
	}

	//MapInfo* pMap = NULL;
	std::shared_ptr<MapInfo> pMap = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		MapInfoMap::iterator it = mp_map_list.find(atoi(pRow[0]));
		if(it != mp_map_list.end()){
			pMap = it->second;
		}else{
			pMap = std::make_shared<MapInfo>();
			pMap->map_id = atoi(pRow[0]);
			mp_map_list.insert(make_pair(pMap->map_id, pMap));
			nRow++;
		}
		pMap->map_name = pRow[1];
		pMap->map_scale = atof(pRow[2]);
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_MAP), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

int CYAServerDlg::init_area(int area_id /* = 0 */)
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);
	if(pConn == NULL){
		return 1;
	}
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	if(area_id == 0){
		sprintf_s(strsql, "SELECT area_id, name, map_id, area_type_id, path, \
						  over_count_person, over_count_vehicle, over_time_person, over_time_vehicle, over_speed_vehicle, is_attendance \
						  FROM dat_area;");
	}else{
		sprintf_s(strsql, "SELECT area_id, name, map_id, area_type_id, path, \
						  over_count_person, over_count_vehicle, over_time_person, over_time_vehicle, over_speed_vehicle, is_attendance \
						  FROM dat_area WHERE area_id = %d; ", area_id);
	}
	pRes = pConn->Execute(strsql, err);
	std::shared_ptr<Area> pArea = nullptr;

	if (err > 0)
	{
		return 0;
	}

	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		AreaMap::iterator it = mp_area_list.find(atoi(pRow[0]));		
		if(it != mp_area_list.end()){
			pArea = it->second;
		}else{
			pArea = std::make_shared<Area>();
			pArea->area_id = atoi(pRow[0]);
			mp_area_list.insert(make_pair(pArea->area_id, pArea));
			nRow++;
		}

		pArea->map_id = atoi(pRow[2]);
		MapInfoMap::iterator map_it = mp_map_list.find(pArea->map_id);
		if(map_it != mp_map_list.end()){
			AreaMap::iterator area_it = map_it->second->map_area_list.find(pArea->area_id);
			if(area_it == map_it->second->map_area_list.end()){
				map_it->second->map_area_list.insert(make_pair(pArea->area_id, pArea));
			}
		}

		pArea->area_name = pRow[1];
		pArea->area_type_id = atoi(pRow[3]);
		pArea->path = pRow[4]; // 多边形
		pArea->over_count_person = atoi(pRow[5]);
		pArea->over_count_vehicle = atoi(pRow[6]);
		pArea->over_time_person = atoi(pRow[7]) * 60; // 转为秒
		pArea->over_time_vehicle = atoi(pRow[8]) * 60; // 转为秒
		pArea->over_speed_vehicle = atof(pRow[9]);
		pArea->is_att = atoi(pRow[10]);
		pArea->init_border(pRow[4]);
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_AREA), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}

int CYAServerDlg::init_special_area_entry(void)
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);
	if(pConn == NULL){
		return 1;
	}
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	sprintf_s(strsql, "SELECT serial_num, start_point_x, start_point_y, start_point_z, end_point_x, end_point_y, \
					  end_point_z, special_area_id FROM dat_special_area_entry;");

	pRes = pConn->Execute(strsql, err);

	if (err > 0)
	{
		return 1;
	}

	std::shared_ptr<SpecialAreaEntry> pSpecialAreaEntry = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		SpecilaAreaEntryMap::iterator it = mp_special_area_entry_list.find(atoi(pRow[0]));		
		if(it != mp_special_area_entry_list.end()){
			pSpecialAreaEntry = it->second;
		}else{
			pSpecialAreaEntry = std::make_shared<SpecialAreaEntry>();
			mp_special_area_entry_list.insert(make_pair(atoi(pRow[0]), pSpecialAreaEntry));
			nRow++;
		}

		pSpecialAreaEntry->start_point_x = atof(pRow[1]);
		pSpecialAreaEntry->start_point_y = atof(pRow[2]);
		pSpecialAreaEntry->start_point_z = atof(pRow[3]);
		pSpecialAreaEntry->end_point_x = atof(pRow[4]);
		pSpecialAreaEntry->end_point_y = atof(pRow[5]);
		pSpecialAreaEntry->end_point_z = atof(pRow[6]);
		pSpecialAreaEntry->special_area_id = atoi(pRow[7]);
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_AREA), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}


int CYAServerDlg::init_drivingface_render(void)
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);
	if(pConn == NULL){
		return 1;
	}
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	sprintf_s(strsql, "SELECT drivingface_id, reader_id, vertical_distance, time, user_id, x, \
					  y, z FROM dat_drivingface_render;");

	pRes = pConn->Execute(strsql, err);

	if (err > 0)
	{
		return 1;
	}

	std::shared_ptr<DrivingfaceRender> pDrivingfaceRender = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		DrivingfaceRenderMap::iterator it = mp_driving_face_render_list.find(atoi(pRow[1]));		
		if(it != mp_driving_face_render_list.end()){
			pDrivingfaceRender = it->second;
		}else{
			pDrivingfaceRender = std::make_shared<DrivingfaceRender>();
			mp_driving_face_render_list.insert(make_pair(atoi(pRow[1]), pDrivingfaceRender));
			nRow++;
		}

		pDrivingfaceRender->drivingface_id = atoi(pRow[0]);
		pDrivingfaceRender->vertical_distance = atof(pRow[2]);
		pDrivingfaceRender->x = atof(pRow[5]);
		pDrivingfaceRender->y = atof(pRow[6]);
		pDrivingfaceRender->z = atof(pRow[7]);
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_AREA), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}


void CYAServerDlg::init_drivingface_card_curshift_position()
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);
	if(pConn == NULL){
		return;
	}
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	int nRow = 0;
	char strsql[LENGTH_SQL] = {0};
	int shift_id = 0;
	time_t start_time_t = GetCurShiftStartTime(shift_id);
	this->cur_shift_id = shift_id;
	struct tm* cur_shift_time = localtime(&start_time_t);

	//current shift history is exist
	sprintf_s(strsql, "select * from his_drivingface_his where card_id = 0020000001014 and start_time = '%d-%d-%d %d:%d:%d' order by start_time desc limit 1;", 
		cur_shift_time->tm_year + 1900,
		cur_shift_time->tm_mon + 1,
		cur_shift_time->tm_mday,
		cur_shift_time->tm_hour,
		cur_shift_time->tm_min,
		cur_shift_time->tm_sec);
	debug_print_syslog(0, "init driving face by current shift data: %s", strsql);

	pRes = pConn->Execute(strsql, err);
	if (err > 0)
	{
		return;
	}
	
	std::shared_ptr<DrivingfaceRender> pDrivingfaceRender = nullptr;
	while(pRow = mysql_fetch_row(pRes))
	{
		CardMap::iterator it = mp_card_list_all.find(pRow[1]);
		if(it != mp_card_list_all.end())
		{
		    it->second->driving_face_id = atoi(pRow[0]);
		    it->second->driving_face_cur_shift_start_x = atof(pRow[6]);
    		it->second->driving_face_cur_shift_start_y = atof(pRow[7]);
    		it->second->driving_face_cur_shift_start_z = atof(pRow[8]);
			it->second->driving_face_cur_shift_x = atof(pRow[9]);
			it->second->driving_face_cur_shift_y = atof(pRow[10]);
			it->second->driving_face_cur_shift_z = atof(pRow[11]);
			it->second->x = atof(pRow[9]);
			it->second->y = atof(pRow[10]);
			it->second->z = atof(pRow[11]);
			it->second->drving_face_cur_shift_max_speed = 0;
			debug_print_syslog(0, "current shift driving face start point, drivingface_id: %s, start_x: %s, start_y: %s, start_z: %s", 
				pRow[0], pRow[9], pRow[10], pRow[11]);
			write_drivingface_shift_start_data(it->second);
		}
		debug_print_syslog(0, "init driving face start point error.");
		nRow++;
	}

	if(0 == nRow)
	{
    	sprintf_s(strsql, "select * from his_drivingface_his where card_id = 0020000001014 and start_time < '%d-%d-%d %d:%d:%d' order by start_time desc limit 1;", 
    		cur_shift_time->tm_year + 1900,
    		cur_shift_time->tm_mon + 1,
    		cur_shift_time->tm_mday,
    		cur_shift_time->tm_hour,
    		cur_shift_time->tm_min,
    		cur_shift_time->tm_sec);
    	debug_print_syslog(0, "init cur shift driving face by last log: %s", strsql);
    
    	pRes = pConn->Execute(strsql, err);
    	if (err > 0)
    	{
    		return;
    	}
    	
    	std::shared_ptr<DrivingfaceRender> pDrivingfaceRender = nullptr;
    	int nRow = 0;
    	while(pRow = mysql_fetch_row(pRes))
    	{
    		CardMap::iterator it = mp_card_list_all.find(pRow[1]);
    		if(it != mp_card_list_all.end())
    		{
    		    it->second->driving_face_id = atoi(pRow[0]);
    		    it->second->driving_face_cur_shift_start_x = atof(pRow[9]);
        		it->second->driving_face_cur_shift_start_y = atof(pRow[10]);
        		it->second->driving_face_cur_shift_start_z = atof(pRow[11]);
				it->second->driving_face_cur_shift_x = atof(pRow[9]);
			    it->second->driving_face_cur_shift_y = atof(pRow[10]);
			    it->second->driving_face_cur_shift_z = atof(pRow[11]);
				it->second->x = atof(pRow[9]);
			    it->second->y = atof(pRow[10]);
			    it->second->z = atof(pRow[11]);
    			it->second->drving_face_cur_shift_max_speed = 0;
    			debug_print_syslog(0, "init driving face start point, drivingface_id: %s, start_x: %s, start_y: %s, start_z: %s", 
    				pRow[0], pRow[9], pRow[10], pRow[11]);
				write_drivingface_shift_start_data(it->second);
    		}
    		debug_print_syslog(0, "init driving face start point error.");
    		nRow++;
    	}
	}
	return;
}


int CYAServerDlg::init_landmark(void)
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);
	if(pConn == NULL){
		return 1;
	}
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	sprintf_s(strsql, "select landmark_id, name, map_id, x, y, z from dat_landmark;");

	pRes = pConn->Execute(strsql, err);

	if (err > 0)
	{
		return 1;
	}

	std::shared_ptr<LandmarkInfo> pLandmarkInfo = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		LandmarkInfoMap::iterator it = mp_landmark_list.find(atoi(pRow[0]));		
		if(it != mp_landmark_list.end()){
			pLandmarkInfo = it->second;
		}else{
			pLandmarkInfo = std::make_shared<LandmarkInfo>();
			mp_landmark_list.insert(make_pair(atoi(pRow[0]), pLandmarkInfo));
			nRow++;
		}

		pLandmarkInfo->landmark_id = atoi(pRow[0]);
		pLandmarkInfo->landmark_name = pRow[1];
		pLandmarkInfo->map_id = atoi(pRow[2]);
		pLandmarkInfo->x = atof(pRow[3]);
		pLandmarkInfo->y = atof(pRow[4]);
		pLandmarkInfo->z = atof(pRow[5]);
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_AREA), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	debug_print_syslog(0, "Init landmark info num: %d", nRow);
	return 0;
}

int CYAServerDlg::init_map_direction(void)
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);
	if(pConn == NULL){
		return 1;
	}
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	sprintf_s(strsql, "select map_direction_id, map_id, north_angle from dat_map_direction;");

	pRes = pConn->Execute(strsql, err);

	if (err > 0)
	{
		return 1;
	}

	std::shared_ptr<MapDirectionInfo> pMapDirectionInfo = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		MapDirectionInfoMap::iterator it = mp_map_direction_list.find(atoi(pRow[1]));		
		if(it != mp_map_direction_list.end()){
			pMapDirectionInfo = it->second;
		}else{
			pMapDirectionInfo = std::make_shared<MapDirectionInfo>();
			mp_map_direction_list.insert(make_pair(atoi(pRow[1]), pMapDirectionInfo));
			nRow++;
		}

		pMapDirectionInfo->map_direction_id = atoi(pRow[0]);
		pMapDirectionInfo->map_id = atoi(pRow[1]);
		pMapDirectionInfo->north_angle = atoi(pRow[2]);
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_AREA), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}


int CYAServerDlg::init_reader(int reader_id /* = 0 */)
{
	// 从数据库中读取
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);
	if(pConn == NULL){
		return 1;
	}
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	if(reader_id == 0){
		sprintf_s(strsql, "SELECT reader_id, map_id, area_id, name, x, y, z, angle, \
						  state, ip, device_type_id, reader_type_id, isSpecial \
						  FROM dat_reader WHERE state=0;");
	}else{
		sprintf_s(strsql, "SELECT reader_id, map_id, area_id, name, x, y, z, angle, \
						  state, ip, device_type_id, reader_type_id,isSpecial \
						  FROM dat_reader WHERE state=0 AND reader_id = %d; ", reader_id);
	}
	pRes = pConn->Execute(strsql, err);

	if (err > 0)
	{
		return 1;
	}

	std::shared_ptr<Reader> pReader = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))	{
		ReaderMap::iterator it = mp_reader_list.find(atoi(pRow[0]));		
		if(it != mp_reader_list.end()){
			pReader = it->second;
		}else{
			pReader = std::make_shared<Reader>();
			pReader->reader_interval_time = m_reader_interval_time;
			pReader->reader_id = atoi(pRow[0]);
			mp_reader_list.insert(make_pair(pReader->reader_id, pReader));
			nRow++;
		}

		pReader->map_id = atoi(pRow[1]);
		MapInfoMap::iterator map_it = mp_map_list.find(pReader->map_id);
		if(map_it != mp_map_list.end()){
			ReaderMap::iterator reader_it = map_it->second->map_reader_list.find(pReader->reader_id);
			if(reader_it == map_it->second->map_reader_list.end()){
				map_it->second->map_reader_list.insert(make_pair(pReader->reader_id, pReader));
			}
			pReader->map_scale = map_it->second->map_scale;
		}
		pReader->area_id = atoi(pRow[2]);
		pReader->reader_name = pRow[3];
		pReader->reader_x = atof(pRow[4]);
		pReader->reader_y = atof(pRow[5]);
		pReader->reader_z = atof(pRow[6]);
		pReader->reader_angle = atof(pRow[7]) * M_PI /180;
		pReader->ip = pRow[9];
		pReader->device_type_id = atoi(pRow[10]);
		pReader->pos_state = atoi(pRow[11]);
		pReader->m_nIsSpecial = atoi(pRow[12]);

		//初始化天线
		//分站天线赋值
		std::shared_ptr<Antenna> ant = std::make_shared<Antenna>();
		ant->antenna_id = 0;
		ant->antenna_x = pReader->reader_x;
		ant->antenna_y = pReader->reader_y;
		ant->antenna_z = pReader->reader_z;
		ant->antenna_angle = pReader->reader_angle;
		pReader->ant[0] = pReader->ant[1] = ant;
		pReader->ant[1]->antenna_id = 1;
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_READER), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

int CYAServerDlg::init_ctrl_reader( int reader_id /*= 0*/ )
{
	// 从数据库中读取
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);
	if(pConn == NULL){
		return 1;
	}
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	if(reader_id == 0){
		sprintf_s(strsql, "SELECT ctrl_reader_id, map_id, area_id, name, x, y, z, angle, \
						  state, ip, device_type_id, reader_type_id,isSpecial \
						  FROM dat_ctrl_reader WHERE state=0;");
	}else{
		sprintf_s(strsql, "SELECT ctrl_reader_id, map_id, area_id, name, x, y, z, angle, \
						  state, ip, device_type_id, reader_type_id,isSpecial \
						  FROM dat_ctrl_reader WHERE state=0 AND ctrl_reader_id = %d; ", reader_id);
	}
	pRes = pConn->Execute(strsql, err);

	if (err > 0)
	{
		return 1;
	}

	std::shared_ptr<Reader> pReader = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))	{
		ReaderMap::iterator it = mp_ctrl_reader_list.find(atoi(pRow[0]));		
		if(it != mp_ctrl_reader_list.end()){
			pReader = it->second;
		}else{
			pReader = std::make_shared<Reader>();
			pReader->reader_interval_time = m_reader_interval_time;
			pReader->reader_id = atoi(pRow[0]);
			mp_ctrl_reader_list.insert(make_pair(pReader->reader_id, pReader));
			nRow++;
		}

		pReader->map_id = atoi(pRow[1]);
		MapInfoMap::iterator map_it = mp_map_list.find(pReader->map_id);
		if(map_it != mp_map_list.end()){
			ReaderMap::iterator reader_it = map_it->second->map_ctrl_reader_list.find(pReader->reader_id);
			if(reader_it == map_it->second->map_ctrl_reader_list.end()){
				map_it->second->map_ctrl_reader_list.insert(make_pair(pReader->reader_id, pReader));
			}
			pReader->map_scale = map_it->second->map_scale;
		}
		pReader->area_id = atoi(pRow[2]);
		pReader->reader_name = pRow[3];
		pReader->reader_x = atof(pRow[4]);
		pReader->reader_y = atof(pRow[5]);
		pReader->reader_z = atof(pRow[6]);
		pReader->reader_angle = atof(pRow[7]) * M_PI /180;
		pReader->ip = pRow[9];
		pReader->device_type_id = atoi(pRow[10]);
		pReader->pos_state = atoi(pRow[11]);
		pReader->m_nIsSpecial = atoi(pRow[12]);
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_CTRL_READER), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}

//int CYAServerDlg::init_antenna(int reader_id /* = 0 */)
//{
//	CMysqlConn* pConn = NULL;
//	CDBConnGuard pDbGuard(pConn);
//	if(pConn == NULL){
//		return 1;
//	}
//	MYSQL_ROW pRow;
//	MYSQL_RES *pRes = NULL;
//	int err = 0;
//	char strsql[LENGTH_SQL] = {0};	
//	if(reader_id == 0){
//		sprintf_s(strsql, "SELECT antenna_id, a.reader_id, reader_idx, a.x, a.y, a.z, a.angle \
//						  FROM dat_antenna a, dat_reader r \
//						  WHERE a.reader_id = r.reader_id;");
//	}else{
//		sprintf_s(strsql, "SELECT antenna_id, a.reader_id, reader_idx, a.x, a.y, a.z, a.angle \
//						  FROM dat_antenna a, dat_reader r \
//						  WHERE a.reader_id = r.reader_id AND reader_id = %d; ", reader_id);
//	}
//	pRes = pConn->Execute(strsql,err);
//
//	if (err)
//	{
//		return 1;
//	}
//
//	int nRow = 0;
//	while(pRow = mysql_fetch_row(pRes)){
//		ReaderMap::iterator it = mp_reader_list.find(atoi(pRow[1]));
//		if(it != mp_reader_list.end()){
//			std::shared_ptr<Antenna> ant = std::make_shared<Antenna>();
//			ant->antenna_id = atoi(pRow[0]);
//			ant->antenna_x = atof(pRow[3]);
//			ant->antenna_y = atof(pRow[4]);
//			ant->antenna_z = atof(pRow[5]);
//			ant->antenna_angle = atof(pRow[6]) * M_PI / 180.0;
//			int idx = (atoi(pRow[2]) == 1) ? 0 : 1;		
//			std::shared_ptr<Reader> pReader = nullptr;
//			pReader = it->second;
//			pReader->ant[idx] = ant;
//			//it->second->ant[idx] = ant;
//			nRow++;
//		}
//	}
//	mysql_free_result(pRes);
//
//	CString strlog;
//	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_ANTENNA), nRow, _T(LOG_RECORD_COUNT));
//	show_log(strlog);
//
//	return 0;
//}

int CYAServerDlg::init_dev_adhoc( int reader_id /*= 0*/ )
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);
	if(pConn == NULL){
		return 1;
	}
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	if(reader_id == 0){//dat_dev_adhoc
		sprintf_s(strsql, "select ad.id, ad.reader_id, ad.level, ad.x, ad.y, ad.z from dat_dev_adhoc ad, dat_reader r \
						  where ad.reader_id = r.reader_id;");
	}else{
		sprintf_s(strsql, "select ad.id, ad.reader_id, ad.level, ad.x, ad.y, ad.z from dat_dev_adhoc ad, dat_reader r \
						  where ad.reader_id = r.reader_id and ad.reader_id = %d; ", reader_id);
	}
	pRes = pConn->Execute(strsql,err);

	if(err){
		return 1;
	}
	int nRow = 0;
	int idx = 0;

	while(pRow = mysql_fetch_row(pRes)){
		ReaderMap::iterator it = mp_reader_list.find(atoi(pRow[1]));
		if(it != mp_reader_list.end()){
			std::shared_ptr<Adhoc> adhoc = std::make_shared<Adhoc>();
			adhoc->adhoc_id = atoi(pRow[0]);
			adhoc->idx = atoi(pRow[2]);
			adhoc->x = atof(pRow[3]);
			adhoc->y = atof(pRow[4]);
			adhoc->z = atof(pRow[5]);
			idx = (adhoc->idx < ADHOC_COUNT)?adhoc->idx:0;
			it->second->adhoc[idx] = adhoc;
			nRow++;
		}
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_ADHOC_LOCATE), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

/*
* 函数名：init_all_readers_coverage
* 从数据库的dat_reader_path表中读取指定map_id和reader_id的地图范围集，
* 将此分站的地图范围集保存在分站类中的readerCoverage中；
* 如果指定了相同的地图范围集的reader_id,则直接将指定的reader_id的地图范围集赋值给此reader_id的地图范围集
* 然后将地图集赋值给station
* 
*
* @param
*		reader_id		分站id号
*
* @return
*		-1，表示在分站map中未找到此分站信息或者未正常执行；0，表示正常执行
*
*/
int CYAServerDlg::init_all_readers_coverage(int reader_id)
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	//如果无可用数据库连接，不执行后续操作
	if(pConn == NULL){
		return 1;
	}

	char sql[LENGTH_SQL] = {0};
	if(reader_id == 0){
		sprintf_s(sql, "select p.start_reader_id,p.end_reader_id,p.idx,p.x,p.y,p.z,p.is_bezier from dat_reader_path_tdoa p ,dat_reader r where p.start_reader_id = r.reader_id;");
	}else{
		sprintf_s(sql, "select p.start_reader_id,p.end_reader_id,p.idx,p.x,p.y,p.z,p.is_bezier from dat_reader_path_tdoa p ,dat_reader r where p.start_reader_id = %d; ", reader_id);
	}

	MYSQL_RES* pRes = NULL;
	MYSQL_ROW pRow;
	int err = 0;
	int nRow = 0;
	//查询数据库
	pRes = pConn->Execute(sql,err);

	if (err)
	{
		return 1;
	}

	//从数据库获得信息赋给分站对象的地图集
	while(pRow = mysql_fetch_row(pRes)){
		int nReaderId = atoi(pRow[1]);
		ReaderMap::iterator it = mp_reader_list.find(nReaderId);

		int nSameConfigReader = atoi(pRow[0]);
		int nIdx = atoi(pRow[2]);
		//判断地图集信息是否可利用其它分站的覆盖范围，如果可用，则使用其它分站的覆盖范围
		//-1表示不可用，否则表示可复用分站id号为nSameConfigReader的地图集覆盖范围
		if(nSameConfigReader == -1){
			_point p;
			p.x = atof(pRow[3]);
			p.y = atof(pRow[4]);
			p.z = atof(pRow[5]);
			it->second->readerCoveragePath.insert(make_pair(nIdx,p));
			it->second->bIsInitCoverage = true;
			nRow++;
		}else{
			it->second->readerCoveragePath = mp_reader_list.find(nSameConfigReader)->second->readerCoveragePath;
			it->second->bIsInitCoverage = true;
			nRow++;
		}
	}
	mysql_free_result(pRes);

	//输出操作数据库的日志信息
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_READER_PATH), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	//根据获得地图集将其赋给mp_reader_path_list
	ReaderMap::iterator it = mp_reader_list.begin();
	for(it;it!=mp_reader_list.end();it++){
		if(it->second->bIsInitCoverage){
			int nReaderId = it->second->reader_id - 1;

			double dMapScale = mp_map_list.find(it->second->map_id)->second->map_scale;

			std::shared_ptr<ReaderPath> pReaderPath = nullptr;
			ReaderPathMap::iterator prpIt = mp_reader_path_list->find(nReaderId);
			if(prpIt != mp_reader_path_list->end()){
				pReaderPath = prpIt->second;
			}else{
				pReaderPath = std::make_shared<ReaderPath>();
				mp_reader_path_list->insert(make_pair(nReaderId,pReaderPath));
			}
			pReaderPath->nRealCalcPoints = it->second->readerCoveragePath.size();
			for(int i=0;i<2;i++){
				pReaderPath->x[i] = it->second->ant[i]->antenna_x*dMapScale;
				pReaderPath->y[i] = it->second->ant[i]->antenna_y*dMapScale;
				pReaderPath->z[i] = it->second->ant[i]->antenna_z*dMapScale;
			}

			for(size_t j = 1;j <= it->second->readerCoveragePath.size(); j++){
				pReaderPath->px[j - 1] = it->second->readerCoveragePath.find(j)->second.x*dMapScale;
				pReaderPath->py[j - 1] = it->second->readerCoveragePath.find(j)->second.y*dMapScale;
				pReaderPath->pz[j - 1] = it->second->readerCoveragePath.find(j)->second.z*dMapScale;
			}
		}
	}

	return 0;
}

/*
* 函数名：init_tdoa_all_readers_coverage
* 实现初始化TDOA方式的地图集描述，并存储冗余数据
* 冗余数据的主要作用在于：例如存在分站<B1,B2>之间的地图集描述，那么也存在<B2,B1>的对应关系
*
* param 
*		reader_id	------	分站id号
*
* return
*		执行失败，返回1
*		正确执行，返回0
*
*/
int CYAServerDlg::init_tdoa_all_readers_coverage(int reader_id)
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	//无可用数据库连接
	if(pConn == NULL){
		return 1;
	}

	char sql[LENGTH_SQL] = {0};
	if(reader_id == 0){
		sprintf_s(sql, "select p.start_reader_id,p.end_reader_id,p.idx,p.x,p.y,p.z,p.is_bezier from dat_reader_path_tdoa p ,dat_reader r where p.start_reader_id = r.reader_id;"); 
	}else{
		sprintf_s(sql, "select start_reader_id,end_reader_id,idx,x,y,z,is_bezier from dat_reader_path_tdoa where p.start_reader_id =%d; ", reader_id);
	}

	MYSQL_RES* pRes = NULL;
	MYSQL_ROW pRow;
	int err = 0;
	int nRow = 0;

	//查询数据库
	pRes = pConn->Execute(sql,err);

	if (err)
	{
		return 1;
	}

	double mapScale = 0.0;
	while(pRow = mysql_fetch_row(pRes)){
		int start_reader_id = atoi(pRow[0]);
		int end_reader_id   = atoi(pRow[1]);
		int ndx = atoi(pRow[2]);

		int nTotal = get_map_path_nums(start_reader_id,end_reader_id);

		ReaderMap::iterator it_reader = mp_reader_list.find(start_reader_id);
		if (it_reader == mp_reader_list.end())
		{
			continue;
		}
		it_reader = mp_reader_list.find(end_reader_id);
		if (it_reader == mp_reader_list.end())
		{
			continue;
		}

		//后缀_r都为冗余信息
		std::shared_ptr<ReaderPath> prp = nullptr;
		std::shared_ptr<ReaderPath> prp_r = nullptr;

		TDOAReaderPathMap::iterator it = mp_reader_path_list_tdoa->find(start_reader_id);	

		if(it == mp_reader_path_list_tdoa->end()){
			std::shared_ptr<ReaderPathMap> prpm = std::make_shared<ReaderPathMap>();
			std::shared_ptr<ReaderPath> prp1 = std::make_shared<ReaderPath>();
			prpm->insert(make_pair(end_reader_id,prp1));
			mp_reader_path_list_tdoa->insert(make_pair(start_reader_id,prpm));	

			//冗余数据
			std::shared_ptr<ReaderPathMap> prpm_r = std::make_shared<ReaderPathMap>();
			std::shared_ptr<ReaderPath> prp1_r = std::make_shared<ReaderPath>();
			prpm_r->insert(make_pair(start_reader_id,prp1_r));
			mp_reader_path_list_tdoa->insert(make_pair(end_reader_id,prpm_r));		
		}else{
			ReaderPathMap::iterator it2;
			it2 = it->second->find(end_reader_id);
			if(it2 == it->second->end()){
				std::shared_ptr<ReaderPath> prp1 = std::make_shared<ReaderPath>();
				it->second->insert(make_pair(end_reader_id,prp1));		
			}
		}

		TDOAReaderPathMap::iterator it_r = mp_reader_path_list_tdoa->find(end_reader_id);
		if(it_r == mp_reader_path_list_tdoa->end()){
			std::shared_ptr<ReaderPathMap> prpm = std::make_shared<ReaderPathMap>();
			std::shared_ptr<ReaderPath> prp1 = std::make_shared<ReaderPath>();
			prpm->insert(make_pair(start_reader_id,prp1));
			mp_reader_path_list_tdoa->insert(make_pair(end_reader_id,prpm));	
		}else{
			ReaderPathMap::iterator it2;
			it2 = it_r->second->find(start_reader_id);
			if(it2 == it_r->second->end()){
				std::shared_ptr<ReaderPath> prp1 = std::make_shared<ReaderPath>();
				it_r->second->insert(make_pair(start_reader_id,prp1));		
			}
		}

		ReaderPathMap::iterator it_rpm = mp_reader_path_list_tdoa->find(start_reader_id)->second->find(end_reader_id);
		if(it_rpm!=mp_reader_path_list_tdoa->find(start_reader_id)->second->end()){
			prp = it_rpm->second;
		}else{
			prp = std::make_shared<ReaderPath>();
			mp_reader_path_list_tdoa->find(start_reader_id)->second->insert(make_pair(end_reader_id,prp));
		}

		//冗余信息
		ReaderPathMap::iterator it_rpm_r = mp_reader_path_list_tdoa->find(end_reader_id)->second->find(start_reader_id);
		if(it_rpm_r!=mp_reader_path_list_tdoa->find(end_reader_id)->second->end()){
			prp_r = it_rpm_r->second;
		}else{
			prp_r = std::make_shared<ReaderPath>();
			mp_reader_path_list_tdoa->find(end_reader_id)->second->insert(make_pair(start_reader_id,prp));
		}

		//获得地图比例
		int map_id = mp_reader_list.find(start_reader_id)->second->map_id;
		MapInfoMap::iterator mit = mp_map_list.find(map_id);
		if(mit == mp_map_list.end()){
			//没有相关地图信息，要输出错误日志
			AfxMessageBox(_T("分站所在地图不存在！"));
			break;
		}
		mapScale = mp_map_list.find(map_id)->second->map_scale;

		if(prp->nRealCalcPoints < ndx){
			prp->nRealCalcPoints = ndx;
		}
		if(prp_r->nRealCalcPoints < ndx){
			prp_r->nRealCalcPoints = ndx;
		}

		if(!prp->bIsInit){
			//获得分站坐标，其中索引0表示起始分站坐标，索引1表示结束分站坐标
			prp->x[0] = mp_reader_list.find(start_reader_id)->second->reader_x*mapScale;
			prp->y[0] = mp_reader_list.find(start_reader_id)->second->reader_y*mapScale;
			prp->z[0] = 0;
			prp->x[1] = mp_reader_list.find(end_reader_id)->second->reader_x*mapScale;
			prp->y[1] = mp_reader_list.find(end_reader_id)->second->reader_y*mapScale;
			prp->z[1] = 0;	
			prp->bIsInit = true;
		}
		if(prp->px[ndx-1] == 0){
			prp->px[ndx-1] = atof(pRow[3])*mapScale;
			prp->py[ndx-1] = atof(pRow[4])*mapScale;
		}

		if(!prp_r->bIsInit){
			//冗余信息
			prp_r->x[0] = mp_reader_list.find(end_reader_id)->second->reader_x*mapScale;
			prp_r->y[0] = mp_reader_list.find(end_reader_id)->second->reader_y*mapScale;
			prp_r->z[0] = 0;
			prp_r->x[1] = mp_reader_list.find(start_reader_id)->second->reader_x*mapScale;
			prp_r->y[1] = mp_reader_list.find(start_reader_id)->second->reader_y*mapScale;
			prp_r->z[1] = 0;

			prp_r->bIsInit = true;
		}
		if(prp_r->px[nTotal - ndx] == 0){
			prp_r->px[nTotal - ndx] = atof(pRow[3])*mapScale;
			prp_r->py[nTotal - ndx] = atof(pRow[4])*mapScale;
		}
		nRow++;
	}
	mysql_free_result(pRes);

	//输出操作结果信息
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_MAP_PATH), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

/*
* 初始化硐室表
*
* param
*		无
*
* return
*		成功返回0，失败返回1
*
*/
int CYAServerDlg::init_chamber(int chamber_id)
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	//无可用数据库连接
	if(pConn == NULL){
		return 1;
	}

	char sql[LENGTH_SQL] = {0};
	if (chamber_id == 0)
	{
		sprintf_s(sql, "select chamber_id,path,name,is_used,section_id,map_id from dat_chamber;"); 
	} 
	else
	{
		sprintf_s(sql, "select chamber_id,path,name,is_used,section_id,map_id from dat_chamber where chamber_id = %d;",chamber_id); 
	}


	MYSQL_RES* pRes = NULL;
	MYSQL_ROW pRow;
	int err = 0;
	int nRow = 0;

	//查询数据库
	pRes = pConn->Execute(sql,err);

	if (err)
	{
		return 1;
	}

	while (pRow = mysql_fetch_row(pRes))
	{
		std::shared_ptr<Chamber> pChamber = nullptr;

		int chamber_id = atoi(pRow[0]);
		ChamberMap::iterator it_chamber = mp_chamber_list.find(chamber_id);
		if (it_chamber != mp_chamber_list.end())
		{
			pChamber = it_chamber->second;
		}else{
			pChamber = std::make_shared<Chamber>();
			mp_chamber_list.insert(make_pair(chamber_id,pChamber));
		}

		pChamber->m_nID = chamber_id;
		pChamber->m_strPath = pRow[1];
		pChamber->m_strName = pRow[2];
		pChamber->m_nIsUsed = atoi(pRow[3]);
		pChamber->m_nSectionID = atoi(pRow[4]);
		pChamber->m_nMapID = atoi(pRow[5]);

		if (pChamber->m_strPath!="")
		{
			pChamber->init_border(pChamber->m_strPath);
		}

		MapInfoMap::iterator it_map = mp_map_list.find(pChamber->m_nMapID);
		if (it_map != mp_map_list.end())
		{
			ChamberMap::iterator it_chamber = it_map->second->map_chamber_list.find(pChamber->m_nID);
			if (it_chamber == it_map->second->map_chamber_list.end())
			{
				it_map->second->map_chamber_list.insert(make_pair(pChamber->m_nID,pChamber));
			}
		}

		nRow++;
	}
	mysql_free_result(pRes);

	//输出操作结果信息
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_CHAMBER), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

/*
* 初始化红绿灯表
*
* param
*		无
*
* return 
*		成功返回0，失败返回1
*
*/
int CYAServerDlg::init_traffic_lights(int light_id)
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	//无可用数据库连接
	if(pConn == NULL){
		return 1;
	}

	char sql[LENGTH_SQL] = {0};
	if (light_id == 0)
	{
		sprintf_s(sql, "select light_id,ip,x,y,z,name,label,map_id,area_id,section_id,ctrl_reader_id,group_id,port,device_type_id,stream from dat_light where state = 0;"); 
	} 
	else
	{
		sprintf_s(sql, "select light_id,ip,x,y,z,name,label,map_id,area_id,section_id,ctrl_reader_id,group_id,port,device_type_id,stream from dat_light where state = 0 and light_id = %d;",light_id); 
	}


	MYSQL_RES* pRes = NULL;
	MYSQL_ROW pRow;
	int err = 0;
	int nRow = 0;

	//查询数据库
	pRes = pConn->Execute(sql,err);

	if (err)
	{
		return 1;
	}

	while (pRow = mysql_fetch_row(pRes))
	{
		std::shared_ptr<Light> pLight = nullptr;

		int light_id = atoi(pRow[0]);
		LightMap::iterator it_light = mp_light_list.find(light_id);
		if (it_light != mp_light_list.end())
		{
			pLight = it_light->second;
		}else{
			pLight = std::make_shared<Light>();
			mp_light_list.insert(make_pair(light_id,pLight));
		}

		pLight->m_nID = light_id;
		pLight->m_strIP = pRow[1];
		pLight->x = atof(pRow[2]);
		pLight->y = atof(pRow[3]);
		pLight->z = atof(pRow[4]);
		pLight->m_strName = pRow[4]!=NULL?pRow[5]:NULL;
		pLight->m_strLabel= pRow[5]!=NULL?pRow[6]:NULL;
		pLight->m_nMapID = atoi(pRow[7]);
		pLight->m_nAreaID = atoi(pRow[8]);
		pLight->m_nSectionID = atoi(pRow[9]);
		pLight->m_nReaderID = atoi(pRow[10]);
		pLight->m_nLightsGroupID = atoi(pRow[11]);
		pLight->m_nPort = atoi(pRow[12]);
		pLight->device_type_id = atoi(pRow[13]);
		pLight->m_nStream = atoi(pRow[14]);

		MapInfoMap::iterator it_map = mp_map_list.find(pLight->m_nMapID);
		if (it_map != mp_map_list.end())
		{
			LightMap::iterator it_light = it_map->second->map_light_list.find(pLight->m_nID);
			if (it_light == it_map->second->map_light_list.end())
			{
				it_map->second->map_light_list.insert(make_pair(pLight->m_nID,pLight));
			}
		}

		nRow++;
	}
	mysql_free_result(pRes);

	//输出操作结果信息
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_LIGHTS), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

/*
* 初始化路段表
*
* param
*		无
*
* return
*		成功返回0，失败返回1
*
*/
int CYAServerDlg::init_section(int section_id)
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	//无可用数据库连接
	if(pConn == NULL){
		return 1;
	}

	char sql[LENGTH_SQL] = {0};
	if (section_id == 0)
	{
		sprintf_s(sql, "select id,path,name,label,map_id,property from dat_section;"); 
	} 
	else
	{
		sprintf_s(sql, "select id,path,name,label,map_id,property from dat_section where id = %d;",section_id); 
	}

	MYSQL_RES* pRes = NULL;
	MYSQL_ROW pRow;
	int err = 0;
	int nRow = 0;

	//查询数据库
	pRes = pConn->Execute(sql,err);

	if (err)
	{
		return 1;
	}

	while (pRow = mysql_fetch_row(pRes))
	{
		std::shared_ptr<Section> pSection = nullptr;
		int nSectionId = atoi(pRow[0]);

		SectionMap::iterator it = mp_section_list.find(nSectionId);
		if (it != mp_section_list.end())
		{
			pSection = it->second;
		} 
		else
		{
			pSection = make_shared<Section>();
			mp_section_list.insert(make_pair(nSectionId,pSection));
		}

		pSection->m_nID = atoi(pRow[0]);
		pSection->m_strPath  = pRow[1];
		pSection->m_strName  = pRow[2];
		pSection->m_strLabel = pRow[3];
		pSection->m_nMapId   = atoi(pRow[4]);

		if (pSection->m_strPath != "")
		{
			pSection->init_border(pSection->m_strPath);
		}

		LightMap::iterator it_light = mp_light_list.begin();
		for (;it_light != mp_light_list.end();++it_light)
		{
			if (it_light->second->m_nSectionID == pSection->m_nID)
			{
				pSection->mp_light_list.insert(make_pair(it_light->second->m_nID,it_light->second));
			}
		}

		ChamberMap::iterator it_chamber = mp_chamber_list.begin();
		for (;it_chamber!=mp_chamber_list.end();++it_chamber)
		{
			if (it_chamber->second->m_nMapID == pSection->m_nMapId && it_chamber->second->m_nSectionID == pSection->m_nID)
			{
				//从硐室表找到和路段相同地图，且硐室信息中的路段id和此id相同的数据
				ChamberMap::iterator it_section_chamber = pSection->mp_champer_list.find(it_chamber->second->m_nID);
				if (it_section_chamber == pSection->mp_champer_list.end())
				{
					std::shared_ptr<Chamber> pChamber(it_chamber->second);
					pSection->mp_champer_list.insert(make_pair(pChamber->m_nID,pChamber));
				}
			}
		}

		MapInfoMap::iterator it_map = mp_map_list.find(pSection->m_nMapId);
		if (it_map != mp_map_list.end())
		{
			SectionMap::iterator it_section = it_map->second->map_section_list.find(pSection->m_nID);
			if (it_section == it_map->second->map_section_list.end())
			{
				it_map->second->map_section_list.insert(make_pair(pSection->m_nID,pSection));
			}
		}
		nRow++;
	}

	mysql_free_result(pRes);

	//输出操作结果信息
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_SECTIONS), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

/*
* 初始化红绿灯组
*
* param
*		无
*
* return
*		成功返回0，失败返回1
*
*/
int CYAServerDlg::init_light_group(int group_id /*= 0*/)
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	//无可用数据库连接
	if(pConn == NULL){
		return 1;
	}

	char sql[LENGTH_SQL] = {0};
	if (group_id == 0)
	{
		sprintf_s(sql,"select lights_group_id,name,label,state,section_id from dat_lights_group where state = 0;");
	} 
	else
	{
		sprintf_s(sql,"select lights_group_id,name,label,state,section_id from dat_lights_group where state = 0 and group_id = %d;",group_id);
	}

	MYSQL_RES* pRes = NULL;
	MYSQL_ROW pRow;
	int err = 0;
	int nRow = 0;

	//查询数据库
	pRes = pConn->Execute(sql,err);

	if (err)
	{
		return 1;
	}

	while (pRow = mysql_fetch_row(pRes))
	{
		std::shared_ptr<LightsGroup> pLightGroup = nullptr;

		int nGroupId = atoi(pRow[0]);

		LightGroupMap::iterator it = mp_light_group_list.find(nGroupId);
		if (it!=mp_light_group_list.end())
		{
			pLightGroup = it->second;
		} 
		else
		{
			pLightGroup = make_shared<LightsGroup>();
			mp_light_group_list.insert(make_pair(nGroupId,pLightGroup));
		}

		pLightGroup->m_nID = nGroupId;
		pLightGroup->m_strName = pRow[1];
		pLightGroup->m_strLabel = pRow[2];
		pLightGroup->m_nState = atoi(pRow[3]);
		pLightGroup->m_nSectionId = atoi(pRow[4]);

		LightMap::iterator it_light = mp_light_list.begin();
		for (;it_light != mp_light_list.end();++it_light)
		{
			if (it_light->second->m_nLightsGroupID == pLightGroup->m_nID)
			{
				std::shared_ptr<Light> pLight(it_light->second);
				pLightGroup->mp_lights_list.insert(make_pair(pLight->m_nID,pLight));
			}
		}

		SectionMap::iterator it_section = mp_section_list.find(pLightGroup->m_nSectionId);
		if (it_section != mp_section_list.end())
		{
			MapInfoMap::iterator it_map = mp_map_list.find(it_section->second->m_nMapId);
			if (it_map != mp_map_list.end())
			{
				LightGroupMap::iterator it_light_group = it_map->second->map_light_group_list.find(pLightGroup->m_nID);
				if (it_light_group == it_map->second->map_light_group_list.end())
				{
					it_map->second->map_light_group_list.insert(make_pair(pLightGroup->m_nID,pLightGroup));
				}
			}
		}


		nRow++;
	}

	mysql_free_result(pRes);

	//输出操作结果信息
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_LIGHTS_GROUP), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

int CYAServerDlg::init_light_state(CONNID dwConnID,std::string strIp)
{
	std::string ip = strIp;
	if (ip == "")
	{
		return 1;
	}

	bool is_exist = false;

	ReaderMap::iterator it_reader = mp_ctrl_reader_list.begin();
	for (it_reader;it_reader!=mp_ctrl_reader_list.end();++it_reader)
	{
		if(it_reader->second->ip == ip){
			is_exist = true;
			break;
		}
	}

	if (!is_exist)
	{
		return 1;
	}

	if (!it_reader->second->init_ctrl_reader_state)
	{
		for (it_reader;it_reader!=mp_ctrl_reader_list.end();++it_reader)
		{
			LightMap::iterator it_light = mp_light_list.begin();
			for (it_light;it_light!=mp_light_list.end();++it_light)
			{
				if(it_light->second->m_nReaderID == it_reader->second->reader_id){
					send_call_light(CC_REQ_LIGTHS_STATE,it_light->second->m_nID,LIGHT_CTRL_STATE::CTRL_STATE_AUTO,1,0);
					it_reader->second->init_ctrl_reader_state = true;
				}
			}
		}
	}

	return 0;
}

void CYAServerDlg::ws_init()
{
	is_websocket_ok = false;
	is_websocket_login = false;

	_io->set_reconnect_attempts(0);
	using std::placeholders::_1;
	using std::placeholders::_2;
	using std::placeholders::_3;
	using std::placeholders::_4;   
	socket::ptr sock = _io->socket();

	sock->on(JSON_CMD_VALUE_USER, sio::socket::event_listener_aux(std::bind(&CYAServerDlg::OnLogin, this, _1,_2,_3,_4)));
	sock->on(JSON_CMD_VALUE_CALL, sio::socket::event_listener_aux(std::bind(&CYAServerDlg::OnCallMessage,this,_1,_2,_3,_4)));
	sock->on(JSON_CMD_VALUE_PUSH, sio::socket::event_listener(std::bind(&CYAServerDlg::OnPushMessage, this)));

	//default socket opened, also we have "set_open_listener" for monitoring physical connection opened.
	_io->set_socket_open_listener(std::bind(&CYAServerDlg::OnConnected, this));
	//physical connection closed or drop.
	_io->set_close_listener(std::bind(&CYAServerDlg::OnClosed,this, std::placeholders::_1));
	_io->set_reconnect_listener(std::bind(&CYAServerDlg::OnReConnect, this, std::placeholders::_1, std::placeholders::_2));
	//physical connection fail to establish.
	_io->set_fail_listener(std::bind(&CYAServerDlg::OnFailed,this));
}

void CYAServerDlg::ws_close()
{
}

void CYAServerDlg::ws_login()
{
	USES_CONVERSION;
	CC2UTF8 conv = (char*)get_json_login().c_str();
	string szlogin = conv.c_str();
	_io->socket()->emit(JSON_CMD_VALUE_USER, szlogin, [&](sio::message::list const& msglist){
		message::ptr msg_ptr = msglist[0];
		int n =(int)msg_ptr->get_map()["code"]->get_int();
		is_websocket_login = (0 == n) ? true : false;
		CString strlog;
		wchar_t* p_url = CFunctions::c2wc(m_ws_url.c_str());
		if(is_websocket_login){
			strlog.Format(_T("%s: %s"), _T(LOG_LOGIN_WEB_SERVER), p_url);
		}else{
			p_url = CFunctions::c2wc(m_ws_url.c_str());
			strlog.Format(_T("%s: %s, err: %d"), _T(LOG_LOGIN_WEB_SERVER_FAILED), p_url, n);
		}
		show_log(strlog);

		if(p_url){
			free(p_url);
			p_url = NULL;
		}
	});
}

void CYAServerDlg::ws_logout()
{
	USES_CONVERSION;
	CC2UTF8 conv = (char*)get_json_logout().c_str();
	string szlogout = conv.c_str();
	_io->socket()->emit(JSON_CMD_VALUE_USER, szlogout, [&](sio::message::list const& msglist){
		message::ptr msg_ptr = msglist[0];
		int n =(int)msg_ptr->get_map()["code"]->get_int();
		CString strlog;
		wchar_t* p_url = CFunctions::c2wc(m_ws_url.c_str());
		if(n == 0){
			strlog.Format(_T("%s: %s"), _T(LOG_LOGOUT_WEB_SERVER), p_url);
			is_websocket_login = false;
		}else{
			p_url = CFunctions::c2wc(m_ws_url.c_str());
			strlog.Format(_T("%s: %s, err: %d"), _T(LOG_LOGOUT_WEB_SERVER_FAILED), p_url, n);
		}
		show_log(strlog);

		if(p_url){
			free(p_url);
			p_url = NULL;
		}
	});
}

void CYAServerDlg::start_tcp_server()
{
	if(m_enState == ST_STARTED){
		return;
	}

	set_app_state(ST_STARTING);

	if(_server.Start(m_tcp_host, PORT_SERVER_MASTER))
	{
		::LogServerStart(m_tcp_host, PORT_SERVER_MASTER);
		set_app_state(ST_STARTED);
		is_start_tcp = true;
	}
	else
	{
		::LogServerStartFail(_server.GetLastError(), _server.GetLastErrorDesc());
		set_app_state(ST_STOPPED);
	}
}

void CYAServerDlg::stop_tcp_server()
{
	if(m_enState == ST_STOPPED){
		return;
	}
	set_app_state(ST_STOPPING);
	if(_server.Stop()){
		::LogServerStop();
		set_app_state(ST_STOPPED);
		is_start_tcp = false;
	}
	else{
		//ASSERT(FALSE);
	}
}

void CYAServerDlg::clear_listener()
{
}

void CYAServerDlg::clear_all_list()
{
	// 清空创建的对象
}

void CYAServerDlg::parse_package_data(BYTE* DataBuffer, int nLen, DWORD dwConnID )
{
	if(DataBuffer == NULL){
		return;
	}

	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_36);

	std::string strBuf = "";
	if(m_log_raw_data){
		formatByteArray(strBuf, DataBuffer, nLen);
<<<<<<< HEAD
		//writeErrorLog(_T("RAW_S"), strBuf, false);
#ifdef ENABLE_MY_LOG
		char* chLog = CFunctions::CString2char(strBuf);
		Log::write_log(FILE_TYPE::RAW_S,chLog);
		free(chLog);
#else
		writeErrorLog(_T("RAW_S"), strBuf, false);
#endif // ENABLE_MY_LOG

		strBuf.Empty();
=======
		Log::write_log(FILE_TYPE::RAW_S, strBuf, false);
>>>>>>> newprotocal
	}

	int nCurPos = 0;
	nCurPos += sizeof(WORD);
	nLen -= sizeof(WORD); // 减去数据长度 

	WORD wCrc = CFunctions::getCRC(&DataBuffer[nCurPos], nLen - sizeof(WORD)); // CRC校验码
	WORD w ;

	CFunctions::getWord(&DataBuffer[nCurPos], &w, nLen - sizeof(WORD));
#ifndef _DEBUG
	if( w  != wCrc ){ // 校验不对
		if(m_log_raw_data){
<<<<<<< HEAD
			strBuf = _T("CRC校验不通过");
			//writeErrorLog(_T("RAW_S"), strBuf);
#ifdef ENABLE_MY_LOG
			char* chLog = CFunctions::CString2char(strBuf);			
			Log::write_log(FILE_TYPE::SYS_S,chLog);
			free(chLog);
#else
			writeErrorLog(_T("RAW_S"), strBuf);
#endif // ENABLE_MY_LOG

			strBuf.Empty();
=======
			strBuf = "CRC校验不通过";
			Log::write_log(FILE_TYPE::RAW_S, strBuf, false);
>>>>>>> newprotocal
		}
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_37);
		return;
	}
#endif // !_DEBUG
	WORD wChr = 0;
	CFunctions::getWord(DataBuffer, &wChr, nCurPos);
	nCurPos += sizeof(WORD);

	int reader_id = 0;
	int nTick = 0;
	CString strtime = _T("");
	INT codeType = wChr;
	//debug_print_syslog(0, "receive msg code: 0x%x", codeType);
	switch (wChr){
	case CHAR_LOCATEDATA: // 定位数据
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_0);
			parse_data_locate_reader(DataBuffer, nCurPos, nLen, dwConnID, reader_id);
			ReaderMap::iterator it = mp_reader_list.find(reader_id);
			if(it != mp_reader_list.end()){
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_61);
				while(nCurPos < nLen - (int)sizeof(WORD)){ // 减去crc // 可能会有死循环
					LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_13);
					if (parse_data_locate_card(DataBuffer, nCurPos, reader_id, wChr)){
						LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_234);
						break;
					}
				}
			}
			else
			{
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_62);
				//debug_print_syslog(0, "CHAR_LOCATEDATA reader_id:%d\n", reader_id);
			}
			break;
		}
	case CHAR_LOCATEDATA_TDOA:
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_1);
			parse_data_locate_reader(DataBuffer, nCurPos, nLen, dwConnID, reader_id);

			ReaderMap::iterator it = mp_reader_list.find(reader_id);
			if(it != mp_reader_list.end()){
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_63);
				while(nCurPos < nLen - (int)sizeof(WORD)){ // 减去crc
					LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_14);
					if(parse_data_locate_card(DataBuffer, nCurPos, reader_id, wChr))
					{
						LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_235);
						break;
					}
				}
			}
			else
			{
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_35);
				//debug_print_syslog(0, "CHAR_LOCATEDATA_TDOA reader_id:%d\n", reader_id);
			}
			break;
		}
	case CHAR_LOCATEDATAHIS:
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_2);
			g_is_rec_hist = true;
			parse_data_locate_reader_his(DataBuffer, nLen, nCurPos, reader_id, nTick, strtime, wChr);
			while(nCurPos < nLen - (int)sizeof(WORD)){ // 减去crc
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_64);
				//debug_print_syslog(0, "CHAR_LOCATEDATAHIS reader_id:%d\n", reader_id);
				parse_data_locate_card_his(DataBuffer, nCurPos, reader_id, nTick, strtime, wChr);
			}
			break;
		}
	case CHAR_LOCATEDATAHIS_TDOA:
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_3);
			g_is_rec_hist = true;
			parse_data_locate_reader_his(DataBuffer, nLen, nCurPos, reader_id, nTick, strtime, wChr);

			BYTE* bt = new BYTE[nLen];
			while(nCurPos < nLen - (int)sizeof(WORD)){ // 减去crc
				// 获取一条记录的长度
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_65);
				WORD wframelen  = 0;
				CFunctions::getWord(DataBuffer, &wframelen, nCurPos);
				nCurPos += sizeof(WORD);

				if(bt){
					LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_66);
					memset(bt, 0, nLen);
					memcpy(bt, &DataBuffer[nCurPos], wframelen);
					parse_data_locate_card_his_tdoa(bt, wframelen, reader_id, nTick, strtime);
				}
				nCurPos += nLen;
			}
			delete[] bt;
			bt = NULL;
			break;
		}
	case CHAR_HIST_DATA_FINISH:
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_4);
			g_is_rec_hist = false;
			// 完成历史数据上传，可点名下一分站
		}
	case CHAR_READER_SYNC_TIME:
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_5);
			parse_data_reader_synctime(DataBuffer, nLen, nCurPos, CHAR_READER_SYNC_TIME);
			break;
		}
	case CHAR_READER_SYNC_TIME_ROOT:
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_6);
			parse_data_reader_synctime(DataBuffer, nLen, nCurPos, CHAR_READER_SYNC_TIME_ROOT);
			break;
		}
	case CHAR_ADHOC:
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_7);
			parse_data_locate_reader(DataBuffer, nCurPos, nLen, dwConnID, reader_id);
			ReaderMap::iterator it = mp_reader_list.find(reader_id);
			if(it != mp_reader_list.end()){
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_67);
				while(nCurPos < nLen - (int)sizeof(WORD)){ // 减去crc
					LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_68);
					parse_data_adhoc(DataBuffer, nCurPos, reader_id);
				}
			}
			break;
		}
	case CHAR_CTRL_READER_CMD:
		{
			parse_data_ctrl_reader(DataBuffer, nCurPos, nLen, dwConnID, reader_id);
			ReaderMap::iterator it = mp_ctrl_reader_list.find(reader_id);
			if(it != mp_ctrl_reader_list.end()){
				while (nCurPos < nLen - (int)sizeof(WORD)){
					parse_data_lights_state(DataBuffer, nCurPos, reader_id, CHAR_CTRL_READER_CMD);
				}
			}
			break;
		}
	case INAV_LOCATE_DATA:
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_230);
			int card_num = parse_inav_msg((INAVLocateMsg *)DataBuffer);
			deal_inav_locate_msg((INAVLocateMsg *)DataBuffer, card_num);

		}
	default:
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_8);
		break;
	}
	strtime.ReleaseBuffer();
}

void CYAServerDlg::parse_data_locate_reader(BYTE * DataBuffer, int& nCurPos, int nLen, DWORD dwConnID, int& reader_id )
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_15);
	// 分站号
	DWORD dwReaderID;
	CFunctions::getDWord(DataBuffer, &dwReaderID, nCurPos);
	nCurPos += sizeof(DWORD);

	reader_id = dwReaderID;
	ReaderMap::iterator itReader = mp_reader_list.find(dwReaderID);
	std::shared_ptr<Reader> pReader = nullptr;
	bool isErrorReader = false;

	if(itReader != mp_reader_list.end()){
		pReader = itReader->second;
		add_socket_to_list(dwConnID, reader_id, DEVICE_TYPE::DT_CARD_READER);
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_16);
	}else{
		pReader = std::make_shared<Reader>();
		pReader->reader_id = dwReaderID;
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_17);
	}

	// 接收数据时间
	pReader->rec_time = time(NULL); 
	m_time_last_rec = pReader->rec_time; // 更新最后信号时间
	// 分站时间戳
	WORD wTickCount = 0;
	CFunctions::getWord(DataBuffer, &wTickCount, nCurPos);
	nCurPos += sizeof(WORD);
	pReader->tick_count = wTickCount;
	// 分站时间
	// 7字节 从第一个字节开始，分别表示秒、分、时、天、周、月、年
	BYTE btSec = 0;
	memcpy(&btSec, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btMin = 0;
	memcpy(&btMin, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btHour = 0;
	memcpy(&btHour, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btDay = 0;
	memcpy(&btDay, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btWeek = 0;
	memcpy(&btWeek, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btMonth = 0;
	memcpy(&btMonth, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btYear = 0;
	memcpy(&btYear, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	struct tm reader_time;
	reader_time.tm_sec = btSec;
	reader_time.tm_min = btMin;
	reader_time.tm_hour = btHour;
	reader_time.tm_mday = btDay;
	reader_time.tm_wday = btWeek;
	reader_time.tm_mon = btMonth - 1;
	reader_time.tm_year = btYear + 100;  // + 2000 - 1900
	pReader->reader_time = mktime(&reader_time);

	// 温度
	BYTE btTemperature = 0;	
	memcpy(&btTemperature, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	pReader->temperature = btTemperature;
	// 状态
	WORD wState = 0;
	CFunctions::getWord(DataBuffer, &wState, sizeof(WORD));
	nCurPos += sizeof(WORD);

	if(m_log_parse_data){
		char chlog[MAX_LOG_LENGTH];
		sprintf_s(chlog, "id:%d, n:%d, %.2d-%.2d-%.2d %.2d:%.2d:%.2d, tep:%d, sta:%d",
			dwReaderID, wTickCount, btYear, btMonth, btDay, btHour, btMin, btSec, btTemperature, wState);
		std::string strlog = chlog;
		Log::write_log(FILE_TYPE::PARSE_S, strlog, true);
	}
}

void CYAServerDlg::parse_data_ctrl_reader( BYTE * DataBuffer, int& nCurPos, int nLen, DWORD dwConnID, int& reader_id )
{
	DWORD dwReaderID;
	CFunctions::getDWord(DataBuffer, &dwReaderID, nCurPos);
	nCurPos += sizeof(DWORD);

	reader_id = dwReaderID;
	ReaderMap::iterator itReader = mp_ctrl_reader_list.find(dwReaderID);
	std::shared_ptr<Reader> pReader = nullptr;
	bool isErrorReader = false;

	if(itReader != mp_ctrl_reader_list.end()){
		pReader = itReader->second;
		add_socket_to_list(dwConnID, reader_id, DEVICE_TYPE::DT_CTRL_READER);
		init_light_state(dwConnID,itReader->second->ip);
	}else{
		pReader = std::make_shared<Reader>();
		pReader->reader_id = dwReaderID;
	}

	// 接收数据时间
	pReader->rec_time = time(NULL); 
	m_time_last_rec = pReader->rec_time; // 更新最后信号时间
	// 分站时间戳
	WORD wTickCount = 0;
	CFunctions::getWord(DataBuffer, &wTickCount, nCurPos);
	nCurPos += sizeof(WORD);
	pReader->tick_count = wTickCount;
	// 分站时间
	// 7字节 从第一个字节开始，分别表示秒、分、时、天、周、月、年
	BYTE btSec = 0;
	memcpy(&btSec, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btMin = 0;
	memcpy(&btMin, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btHour = 0;
	memcpy(&btHour, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btDay = 0;
	memcpy(&btDay, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btWeek = 0;
	memcpy(&btWeek, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btMonth = 0;
	memcpy(&btMonth, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btYear = 0;
	memcpy(&btYear, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	struct tm reader_time;
	reader_time.tm_sec = btSec;
	reader_time.tm_min = btMin;
	reader_time.tm_hour = btHour;
	reader_time.tm_mday = btDay;
	reader_time.tm_wday = btWeek;
	reader_time.tm_mon = btMonth - 1;
	reader_time.tm_year = btYear + 100;  // + 2000 - 1900
	pReader->reader_time = mktime(&reader_time);

	// 温度
	BYTE btTemperature = 0;	
	memcpy(&btTemperature, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	pReader->temperature = btTemperature;
	// 状态
	WORD wState = 0;
	CFunctions::getWord(DataBuffer, &wState, sizeof(WORD));
	nCurPos += sizeof(WORD);

	if(m_log_parse_data){
		char chlog[MAX_LOG_LENGTH];
		sprintf_s(chlog, "id:%d, n:%d, %.2d-%.2d-%.2d %.2d:%.2d:%.2d, tep:%d, sta:%d",
			dwReaderID, wTickCount, btYear, btMonth, btDay, btHour, btMin, btSec, btTemperature, wState);
		std::string strlog = chlog;
		Log::write_log(FILE_TYPE::PARSE_S, strlog, true);
	}
}

int CYAServerDlg::parse_inav_msg(INAVLocateMsg* msgPtr)
{
	if(NULL == msgPtr)
	{
		return -1;
	}
	int len = sizeof(INAVLocateMsg);
	int len_header = sizeof(MsgHeader);
	int len_anchor = sizeof(LocateAnchorInfo);
	int len_one_inav = sizeof(INAVLocateData);
	msgPtr->Header.MsgCode = ntohs(msgPtr->Header.MsgCode);
	msgPtr->Header.MsgLen = ntohs(msgPtr->Header.MsgLen);
	msgPtr->AnchorInfo.AnchorNum = ntohl(msgPtr->AnchorInfo.AnchorNum);
	msgPtr->AnchorInfo.MsgSerialNum = ntohs(msgPtr->AnchorInfo.MsgSerialNum);
	msgPtr->AnchorInfo.State = ntohs(msgPtr->AnchorInfo.State);

	int msg_len = msgPtr->Header.MsgLen - sizeof(MsgHeader) - sizeof(LocateAnchorInfo);
	int card_num = msg_len / sizeof(INAVLocateData);
	for(int i=0; i < card_num ; i++)
	{
		msgPtr->INAVLocateInfo[i].CardId = ntohl(msgPtr->INAVLocateInfo[i].CardId);
		msgPtr->INAVLocateInfo[i].INAVPeriod= ntohs(msgPtr->INAVLocateInfo[i].INAVPeriod);
		msgPtr->INAVLocateInfo[i].AccerateData_X= ntohs(msgPtr->INAVLocateInfo[i].AccerateData_X);
		msgPtr->INAVLocateInfo[i].AccerateData_Y= ntohs(msgPtr->INAVLocateInfo[i].AccerateData_Y);
		msgPtr->INAVLocateInfo[i].AccerateData_Z= ntohs(msgPtr->INAVLocateInfo[i].AccerateData_Z);
		msgPtr->INAVLocateInfo[i].MagneticData_X= ntohs(msgPtr->INAVLocateInfo[i].MagneticData_X);
		msgPtr->INAVLocateInfo[i].MagneticData_Y= ntohs(msgPtr->INAVLocateInfo[i].MagneticData_Y);
		msgPtr->INAVLocateInfo[i].MagneticData_Z= ntohs(msgPtr->INAVLocateInfo[i].MagneticData_Z);
		msgPtr->INAVLocateInfo[i].Gyroscope_X= ntohs(msgPtr->INAVLocateInfo[i].Gyroscope_X);
		msgPtr->INAVLocateInfo[i].Gyroscope_Y= ntohs(msgPtr->INAVLocateInfo[i].Gyroscope_Y);
		msgPtr->INAVLocateInfo[i].Gyroscope_Z= ntohs(msgPtr->INAVLocateInfo[i].Gyroscope_Z);
		msgPtr->INAVLocateInfo[i].Displacement_X= ntohs(msgPtr->INAVLocateInfo[i].Displacement_X);
		msgPtr->INAVLocateInfo[i].Displacement_Y= ntohs(msgPtr->INAVLocateInfo[i].Displacement_Y);
		msgPtr->INAVLocateInfo[i].Displacement_Z= ntohs(msgPtr->INAVLocateInfo[i].Displacement_Z);
		msgPtr->INAVLocateInfo[i].AngleChange_X= ntohs(msgPtr->INAVLocateInfo[i].AngleChange_X);
		msgPtr->INAVLocateInfo[i].AngleChange_Y= ntohs(msgPtr->INAVLocateInfo[i].AngleChange_Y);
		msgPtr->INAVLocateInfo[i].AngleChange_Z= ntohs(msgPtr->INAVLocateInfo[i].AngleChange_Z);
	}
	msg_len = 0;
	return card_num;
}

int g_magic_offset_x = 0;
int g_magic_offset_y = 0;
int g_magic_offset_z = 0;

int tmp_magic_max_x = 0;
int tmp_magic_min_x = 0;
int tmp_magic_max_y = 0;
int tmp_magic_min_y = 0;
int tmp_magic_max_z = 0;
int tmp_magic_min_z = 0;

int init_times = 100;

int g_magic_is_init = 0;

bool init_magic_offset(INAVLocateData cardData)
{
	if(init_times > 0)
	{
		return false;
	}
	else
	{
		g_magic_offset_x = (tmp_magic_max_x + tmp_magic_min_x) / 2;
		g_magic_offset_y = (tmp_magic_max_y + tmp_magic_min_y) / 2;
		g_magic_offset_z = (tmp_magic_max_z + tmp_magic_min_z) / 2;
		debug_print_syslog(0, "Magic init successful: magic_offset_x: %d, magic_offset_x: %d, magic_offset_x: %d", 
			g_magic_offset_x, g_magic_offset_y, g_magic_offset_z);
		return true;
	}
	if(cardData.MagneticData_X > tmp_magic_max_x)
	{
		tmp_magic_max_x = cardData.MagneticData_X;
	}
	if(cardData.MagneticData_Y> tmp_magic_max_y)
	{
		tmp_magic_max_y = cardData.MagneticData_X;
	}
	if(cardData.MagneticData_Z > tmp_magic_max_z)
	{
		tmp_magic_max_z = cardData.MagneticData_Z;
	}
	if(cardData.MagneticData_X < tmp_magic_min_x)
	{
		tmp_magic_min_x = cardData.MagneticData_X;
	}
	if(cardData.MagneticData_X < tmp_magic_min_y)
	{
		tmp_magic_min_y = cardData.MagneticData_X;
	}
	if(cardData.MagneticData_Z < tmp_magic_min_z)
	{
		tmp_magic_min_z = cardData.MagneticData_Z;
	}

	init_times--;

}

void write_magic_locate_map(INAVLocateData* msgPtr, std::shared_ptr<Card> card)
{
	csv::Parser file = csv::Parser("magic_locate_data.csv");  
	vector<string> tmpRow;
	int magic_x = msgPtr->MagneticData_X;
	int magic_y = msgPtr->MagneticData_Y;
	int magic_z = msgPtr->MagneticData_Z;
	int x = card->x;
	int y = card->y;
	int z = card->z;
	char str[20];
	sprintf_s(str,"%d", magic_x);
	tmpRow.push_back(str);
	sprintf_s(str,"%d", magic_y);
	tmpRow.push_back(str);
	sprintf_s(str,"%d", magic_z);
	tmpRow.push_back(str);
	sprintf_s(str,"%d", x);
	tmpRow.push_back(str);
	sprintf_s(str,"%d", y);
	tmpRow.push_back(str);
	//sprintf_s(str,"%d", z);
	//tmpRow.push_back(str);
	file.addRow(0, tmpRow);
	file.sync();
}

void CYAServerDlg::deal_inav_locate_msg(INAVLocateMsg* msgPtr, int card_num)
{
	if(NULL == msgPtr)
	{
		return;
	}
	for(int i=0; i<card_num; i++)
	{
		string str_card_id = CFunctions::getstrwithzero(msgPtr->INAVLocateInfo[i].CardType, 3) + CFunctions::getstrwithzero(msgPtr->INAVLocateInfo[i].CardId, 10);

		std::shared_ptr<Card> card = nullptr;
		bool isErrorCard = false;

		CardMap::iterator it_card = mp_card_list_all.find(str_card_id);
		if(it_card != mp_card_list_all.end())
		{
			card = it_card->second;
		}
		else
		{
			isErrorCard = true;
			card = std::make_shared<Card>(str_card_id, 
				msgPtr->INAVLocateInfo[i].CardType, 
				theApp.z_offset);
#ifdef ALGORITHM_TYPE_TOF
			card->set_reader_path_tof(mp_reader_path_list);
#elif defined ALGORITHM_TYPE_TDOA
			card->set_reader_path_tdoa(mp_reader_path_list_tdoa);
#endif		
		}
#if 0

		std::shared_ptr<MapInfo> pMap = nullptr;
		MapInfoMap::iterator it = mp_map_list.find(card->map_id);
		if(it != mp_map_list.end()){
			pMap = it->second;
		}
		else
		{
			return;
		}
		card->x = card->x + msgPtr->INAVLocateInfo[i].Displacement_X / 1000 / pMap->map_scale;
		card->y= card->y + msgPtr->INAVLocateInfo[i].Displacement_Y / 1000 / pMap->map_scale;
		card->z= card->z + msgPtr->INAVLocateInfo[i].Displacement_Z / 1000 / pMap->map_scale;

		//init magic offset
		if(init_magic_offset(msgPtr->INAVLocateInfo[i]))
		{
			g_magic_is_init = 1;
		}
		//write magic data
		if(1 == g_magic_is_init)
		{
			write_magic_locate_map(INAVLocateMsg* msgPtr, std::shared_ptr<Card> card)
		}
#else if

		card->x = card->x + msgPtr->INAVLocateInfo[i].Displacement_X / 1000;
		card->y= card->y + msgPtr->INAVLocateInfo[i].Displacement_Y / 1000;
		card->z= card->z + msgPtr->INAVLocateInfo[i].Displacement_Z / 1000;
#endif
		INAV_STATUS card_state = calculate_inav_state(&(msgPtr->INAVLocateInfo[i]));
		//calculate_inav_locate_by_magic(card, &(msgPtr->INAVLocateInfo[i]));
		//write_inav_locate_magic_data(card, &(msgPtr->INAVLocateInfo[i]));
		log_card_inav_state(card_state, str_card_id);
		save_card_postion(card);
		card_enter_map(card); // 切换地图
		card_enter_area(card);
		card_enter_mine(card);
		deal_card_state(card);
		if (card->card_type == CT_VEHICLE)
		{
			deal_traffic_lights(card);
			//select_pos_output(card);
		}
		card->isdealed = true;
		if(LT_READER != theApp.locate_type){
			card->issent = false;
		}
	}

	return;
}

INAV_STATUS CYAServerDlg::calculate_inav_state(INAVLocateData* cardData)
{
	INAV_STATUS state = {INAV_STATIC, INAV_NO_DIRECTORY, INAV_NO_ACCERATE};
	double accelerate_x = cardData->AccerateData_X * 2 * GRAVITY_ACCERATION / INAV_READING_MAX;
	double accelerate_y = cardData->AccerateData_Y * 2 * GRAVITY_ACCERATION / INAV_READING_MAX;
	double accelerate_z = cardData->AccerateData_Z * 2 * GRAVITY_ACCERATION / INAV_READING_MAX;

	double join_accerate = sqrt(pow(accelerate_x, 2) + pow(accelerate_y, 2) + pow(accelerate_z, 2));

	debug_print_syslog(0, "displacement_x: %d, displacement_y: %d, displacement_z: %d", 
		cardData->Displacement_X, cardData->Displacement_Y, cardData->Displacement_Z);
	double join_diff = abs(join_accerate - GRAVITY_ACCERATION);
	debug_print_syslog(0, "joint force: %10f", join_diff);
	if(join_diff > JOIN_ACCERATE_THRESHOLD)
	{
		state.Status = INAV_MOVING;
	}
	else
	{
		state.Status = INAV_STATIC;
	}

	if(INAV_MOVING == state.Status)
	{
		//X+ is the forward
#if 0
		bool right_forward_condition = (abs(accelerate_x) > MOVING_THRESHOLD) &&(abs(accelerate_y) < MOVING_THRESHOLD) && (accelerate_x < 0);
		bool left_forward_condition = (abs(accelerate_x) > MOVING_THRESHOLD) && (abs(accelerate_y) < MOVING_THRESHOLD) && (accelerate_x > 0);
		bool forward_condition      = (abs(accelerate_y) > MOVING_THRESHOLD) && (abs(accelerate_x) < MOVING_THRESHOLD) && (accelerate_y < 0);
		bool backward_condition     = (abs(accelerate_y) > MOVING_THRESHOLD) && (abs(accelerate_x) < MOVING_THRESHOLD) && (accelerate_y > 0);
#endif
		bool forward_condition = (abs(accelerate_x) > MOVING_THRESHOLD) &&(abs(accelerate_y) < MOVING_THRESHOLD) && (accelerate_x > 0);
		bool backward_condition = (abs(accelerate_x) > MOVING_THRESHOLD) && (abs(accelerate_y) < MOVING_THRESHOLD) && (accelerate_x < 0);
		bool left_forward_condition      = (abs(accelerate_y) > MOVING_THRESHOLD) && (abs(accelerate_x) < MOVING_THRESHOLD) && (accelerate_y < 0);
		bool right_forward_condition     = (abs(accelerate_y) > MOVING_THRESHOLD) && (abs(accelerate_x) < MOVING_THRESHOLD) && (accelerate_y > 0);
		debug_print_syslog(0, "accelerate_x: %f, accelerate_y: %f", 
			accelerate_x, accelerate_y);
		debug_print_syslog(0, "right_forward_condition: %d, left_forward_condition: %d, forward_condition: %d, backward_condition: %d", 
			right_forward_condition, left_forward_condition, forward_condition, backward_condition);
		bool displace_forward_condition = (abs(cardData->Displacement_X) > DISPLACE_MENT_MOVING_THRESHOLD) &&(abs(cardData->Displacement_Y) < DISPLACE_MENT_MOVING_THRESHOLD) && (cardData->Displacement_X > 0);
		bool displace_backward_condition = (abs(cardData->Displacement_X) > DISPLACE_MENT_MOVING_THRESHOLD) && (abs(cardData->Displacement_Y) < DISPLACE_MENT_MOVING_THRESHOLD) && (cardData->Displacement_X < 0);
		bool displace_left_forward_condition      = (abs(cardData->Displacement_Y) > DISPLACE_MENT_MOVING_THRESHOLD) && (abs(cardData->Displacement_X) < DISPLACE_MENT_MOVING_THRESHOLD) && (cardData->Displacement_Y < 0);
		bool displace_right_forward_condition     = (abs(cardData->Displacement_Y) > DISPLACE_MENT_MOVING_THRESHOLD) && (abs(cardData->Displacement_X) < DISPLACE_MENT_MOVING_THRESHOLD) && (cardData->Displacement_Y > 0);

		debug_print_syslog(0, "displacement right_forward_condition: %d, displacement left_forward_condition: %d, displacement forward_condition: %d, displacement backward_condition: %d", 
			displace_right_forward_condition, displace_left_forward_condition, displace_forward_condition, displace_backward_condition);
		if(right_forward_condition)
		{
			state.Directory = INAV_RIGHTWARD;
		}
		if(left_forward_condition)
		{
			state.Directory = INAV_LEFTWARD;
		}
		if(forward_condition)
		{
			state.Directory = INAV_FORWARD;
		}
		if(backward_condition)
		{
			state.Directory = INAV_BACKWARD;
		}
	}
	if(INAV_MOVING == state.Status)
	{
		if(cardData->Displacement_Y > 0 && accelerate_y > MOVING_THRESHOLD)
		{
			state.AccerateStatus = INAV_ACCERATE;
		}
		if(cardData->Displacement_Y > 0 && accelerate_y < -1 * MOVING_THRESHOLD)
		{
			state.AccerateStatus = INAV_SLOW_DOWN;
		}
		if(cardData->Displacement_Y < 0 && accelerate_y > MOVING_THRESHOLD)
		{
			state.AccerateStatus = INAV_ACCERATE;
		}
		if(cardData->Displacement_Y < 0 && accelerate_y < -1 * MOVING_THRESHOLD)
		{
			state.AccerateStatus = INAV_SLOW_DOWN;
		}
	}

	return state;
}

void CYAServerDlg::calculate_inav_locate_by_magic(std::shared_ptr<Card> card, INAVLocateData* cardData)
{
	int magic_x = cardData->MagneticData_X;
	int magic_y = cardData->MagneticData_Y;
	int magic_z = cardData->MagneticData_Z;
	KNN knn(magic_x, magic_y, magic_z);  
	knn.get_all_distance();  
	tLabel tmp_lable = knn.get_max_freq_label();
	debug_print_syslog(0, "magic__x: %10d, magic_y: %10d, magic_z: %10d", magic_x, magic_y, magic_z);
	debug_print_syslog(0, "magic_position_x: %10d, magic_position_y: %10d", tmp_lable.x, tmp_lable.y);
	return;
}

void CYAServerDlg::write_inav_locate_magic_data(std::shared_ptr<Card> card, INAVLocateData* cardData)
{
	csv::Parser file = csv::Parser("d:/magic_map/trainning_data_magic.csv");  
	vector<string> tmpRow;
	int magic_x = cardData->MagneticData_X;
	int magic_y = cardData->MagneticData_Y;
	int magic_z = cardData->MagneticData_Z;
	int x = card->x;
	int y = card->y;
	char str[10];
	sprintf_s(str,"%d",magic_x);
	tmpRow.push_back(str);
	sprintf_s(str,"%d",magic_y);
	tmpRow.push_back(str);
	sprintf_s(str,"%d",magic_z);
	tmpRow.push_back(str);
	sprintf_s(str,"%d",x);
	tmpRow.push_back(str);
	sprintf_s(str,"%d",y);
	tmpRow.push_back(str);

	file.addRow(0, tmpRow);
	file.sync();
	return;
}

void CYAServerDlg::log_card_inav_state(INAV_STATUS card_state, string card_id)
{
	char card_log_str[2000] = {'\0'};
	sprintf_s(card_log_str, 2000, 
		"Card %s: Moving status: %s, Directory: %s, Accerate status: %s", 
		card_id.c_str(),
		InavMovingStatusStr[card_state.Status],
		InavDirectoryStr[card_state.Directory - INAV_NO_DIRECTORY],
		InavAccerateStatusStr[card_state.AccerateStatus - INAV_NO_ACCERATE]);
	debug_print_syslog(0, "%s", card_log_str);
	return;
}

int CYAServerDlg::get_locate_msg_type(BYTE* DataBuffer)
{
	if(NULL == DataBuffer)
	{
		return -1;
	}
	TofLocateMsg* msgPtr = (TofLocateMsg *)DataBuffer;
	int msgLen = ntohs(msgPtr->Header.MsgLen);

	if((msgLen < sizeof(MsgHeader) + sizeof(LocateAnchorInfo) + sizeof(TofCardInfo))
		|| (msgLen > sizeof(TofLocateMsg)))
	{
		return -1;
	}

	return (msgPtr->TofCardInfo[0].MsgType_BatterInfo >> 4) & 0x0f;
}
std::shared_ptr<Card> CYAServerDlg::parse_tof_locate_msg(TofLocateMsg* DataBuffer, int cardNum)
{
    LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_258);
	TofLocateMsg msgLocatBuf = {0};
	int length = sizeof(TofLocateMsg);
	memcpy(&msgLocatBuf, DataBuffer, sizeof(TofLocateMsg));

	msgLocatBuf.Header.MsgCode = ntohs(msgLocatBuf.Header.MsgCode);
	msgLocatBuf.Header.MsgLen= ntohs(msgLocatBuf.Header.MsgLen);
	msgLocatBuf.AnchorInfo.AnchorNum = ntohl(msgLocatBuf.AnchorInfo.AnchorNum);
	msgLocatBuf.AnchorInfo.MsgSerialNum = ntohs(msgLocatBuf.AnchorInfo.MsgSerialNum);
	msgLocatBuf.AnchorInfo.State = ntohs(msgLocatBuf.AnchorInfo.State);

	msgLocatBuf.TofCardInfo[cardNum].CardId = ntohl(msgLocatBuf.TofCardInfo[cardNum].CardId);
	msgLocatBuf.TofCardInfo[cardNum].MsgSerialNum = ntohs(msgLocatBuf.TofCardInfo[cardNum].MsgSerialNum);

	LONG64 flyTime = 0;
	DWORD dwTemp = 0;
	CFunctions::getDWord(msgLocatBuf.TofCardInfo[cardNum].LocateTimeStamp, &dwTemp, 0);
	flyTime = dwTemp;
	flyTime =  (flyTime & 0xffffffff);
	flyTime = flyTime<<8;
	flyTime = flyTime + msgLocatBuf.TofCardInfo[cardNum].LocateTimeStamp[4];

	double dist = CFunctions::getDistance(flyTime, CFunctions::TOF);

	string str_card_id = CFunctions::getstrwithzero(msgLocatBuf.TofCardInfo[cardNum].CardType, 3) 
		+ CFunctions::getstrwithzero(msgLocatBuf.TofCardInfo[cardNum].CardId, 10);

	std::shared_ptr<Card> card = nullptr;
	bool isErrorCard = false;

	ReaderMap::iterator it = mp_reader_list.find(msgLocatBuf.AnchorInfo.AnchorNum);
	CardMap::iterator it_card = mp_card_list_all.find(str_card_id);
	if(it_card != mp_card_list_all.end()){
		card = it_card->second;
	}else{
		isErrorCard = true;
		card = std::make_shared<Card>(str_card_id, msgLocatBuf.TofCardInfo[cardNum].CardType, theApp.z_offset);

		card->set_reader_path_tof(mp_reader_path_list);

	}
	// 设置当前分站， 进入分站时间、进入区域时间，当前区域，当前地图
	std::shared_ptr<Reader> pReader(it->second);
	int n = it->second.use_count();
	card->set_reader(pReader);
	card->reader_tickcount = pReader->tick_count;
	card->time_stamp = msgLocatBuf.TofCardInfo[cardNum].MsgSerialNum;
	card->ranging_type = msgLocatBuf.TofCardInfo[cardNum].MsgType_BatterInfo & 0x0f;
	card->power_state = (msgLocatBuf.TofCardInfo[cardNum].MsgType_BatterInfo >> 4) & 0x0f;
	card->accelerate_state = msgLocatBuf.TofCardInfo[cardNum].AccelerateSpeed;
	card->flying_time = flyTime;
	card->antenna_id = ((msgLocatBuf.TofCardInfo[cardNum].AntNum & 0xFF) == 1) ? 0 : 1;
	card->distance = dist;
	card->is_hist = false;
	card->state_moving = 1;

	if(m_log_raw_data)
	{
		save_raw_data_card_tof(card);
	}
	
	return card;
}

int CYAServerDlg::parse_data_locate_card(BYTE* DataBuffer, int& nCurPos, int reader_id, unsigned short wChr)
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_18);
	ReaderMap::iterator it = mp_reader_list.find(reader_id);
	if (it == mp_reader_list.end())
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_70);
		return 1;  // 可能会死循环
	}
	// 卡类型
	BYTE btCardType = 0;
	memcpy(&btCardType, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	// 卡号
	DWORD dwCardId;
	CFunctions::getDWord(DataBuffer, &dwCardId, nCurPos);//我擦 dwcardid不存在
	nCurPos += sizeof(DWORD);
	// 获取标识卡编号, 3位卡类型 + 10位卡号
	string str_card_id = CFunctions::getstrwithzero(btCardType, 3) + CFunctions::getstrwithzero(dwCardId, 10);

	std::shared_ptr<Card> card = nullptr;
	bool isErrorCard = false;

	CardMap::iterator it_card = mp_card_list_all.find(str_card_id);
	if(it_card != mp_card_list_all.end()){
		card = it_card->second;
	}else{
		isErrorCard = true;
		card = std::make_shared<Card>(str_card_id, btCardType, theApp.z_offset);
#ifdef ALGORITHM_TYPE_TOF
		card->set_reader_path_tof(mp_reader_path_list);
#elif defined ALGORITHM_TYPE_TDOA
		card->set_reader_path_tdoa(mp_reader_path_list_tdoa);
#endif			
	}
	// 设置当前分站， 进入分站时间、进入区域时间，当前区域，当前地图
	std::shared_ptr<Reader> pReader(it->second);
	int n = it->second.use_count();
	//std::weak_ptr<Reader> wpReader(pReader);
	card->set_reader(pReader);
	card->reader_tickcount = pReader->tick_count;
	card->is_hist = false;

#if 1
	int msg_type = get_locate_msg_type(DataBuffer);
	if(msg_type == CFunctions::TOF)
	{
		TofLocateMsg* msgPtr = (TofLocateMsg *)DataBuffer;
		int msgLen = ntohs(msgPtr->Header.MsgLen);
		int msgHeadLen = sizeof(MsgHeader);
		int locateAnchorMsgLen = sizeof(LocateAnchorInfo);
		int cardMsgLen = sizeof(TofCardInfo);
		int cardNum = (msgLen - sizeof(MsgHeader) - sizeof(LocateAnchorInfo)) / sizeof(TofCardInfo);
		for(int i = 0; i < cardNum; i++)
		{
		    LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_257);
			card = parse_tof_locate_msg(msgPtr, i);
			
			calculate_card_postion_by_tof(card); // 计算位置

			card_enter_map(card); // 切换地图
			card_enter_area(card);
			save_card_postion(card);
			write_his_drivingface_real(card);
			if(0 == card->is_driving_face_start)
			{
				process_driving_face_start_service(card);
				CardMap::iterator it_card = mp_card_list_down_vehicle.find(card->card_id);
				if(it_card == mp_card_list_down_vehicle.end())
				{
					mp_card_list_down_vehicle.insert(make_pair(card->card_id, card));
				}
			}
			card_enter_mine(card);
			deal_card_state(card);
			//if (card->card_type == CT_VEHICLE)
			//{
			//	deal_traffic_lights(card);
			//	//select_pos_output(card);
			//}
			card->isdealed = true;
			if(LT_READER != theApp.locate_type){
				card->issent = false;
			}
			//send_json_data(JSON_CMD_VALUE_PUSH, get_json_drivingface_card_position(card));
		}
		return 2;
	}
#endif

	switch(btCardType)
	{
	case CT_VEHICLE: 
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_19);
			parse_data_locate_card_vehicle(DataBuffer, nCurPos, card, wChr);
			deal_card_msg(card);
			break;
		}
	case CT_PERSON://20170705night
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_20);
			parse_data_locate_card_vehicle(DataBuffer, nCurPos, card, wChr);
			deal_card_msg(card);
			break;
		}
	default:
		{
			// 无法识别的数据
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_21);
			break;
		}
	}
	return 0;
}

void CYAServerDlg::parse_data_locate_card_vehicle(BYTE* DataBuffer, int& nCurPos, std::shared_ptr<Card> card /*Card* card*/, unsigned short wChr )
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_22);
	if(LT_READER == theApp.locate_type){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_23);
		card->isdealed = false;
		card->isreceive = true;
		card->issent = false;
	}
	// 报文时间
	WORD wCardTickCount;
	CFunctions::getWord(DataBuffer, &wCardTickCount, nCurPos);
	nCurPos += sizeof(WORD);

	BYTE btTypeAndPower;
	memcpy(&btTypeAndPower, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	//报文类型
	BYTE btType;
	btType = (btTypeAndPower >>4) & 0x0F;

	//电池电量
	BYTE btPower;
	btPower = btTypeAndPower & 0x0F;	//0代表100%，1代表50%，2代表20%

	//保留
	//呼叫呼救状态位
	//0x10全员一般；0x11为全员紧急；
	//0x20为定员一般呼叫；0x21为定员紧急呼叫
	BYTE btCallType = 0;
	memcpy(&btCallType, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	//加速度
	BYTE btAcceleration;
	memcpy(&btAcceleration, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	//定位时间戳Tsp // 字序
	LONG64 lTime1 = 0;
	BYTE btTemp = 0;
	int nRangingPos = nCurPos;
	memcpy(&btTemp, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	DWORD dwTemp = 0;
	CFunctions::getDWord(DataBuffer, &dwTemp, nCurPos);
	nCurPos += sizeof(DWORD);
	lTime1 = btTemp;
	lTime1 = lTime1 << 32;
	lTime1 |=  ((long long)dwTemp & 0xffffffff);
	// 距离
	double dldist = 0;
	// 天线
	BYTE btAntenna;
	memcpy(&btAntenna, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	WORD wSyncNum = 0;
	WORD wStrength = 0;
	if(CHAR_LOCATEDATA_TDOA == wChr){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_24);
		// 分站时间同步序列号 
		CFunctions::getWord(DataBuffer, &wSyncNum, nCurPos);
		nCurPos += sizeof(WORD);
		// 信号强度		
		CFunctions::getWord(DataBuffer, &wStrength, nCurPos);
		nCurPos += sizeof(WORD);
	}else if(CHAR_LOCATEDATA == wChr){
		dldist = CFunctions::getDistance(lTime1);
		if(-1 == dldist)
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_71);
		}
	}

	if(LT_COORDINATE == theApp.locate_type){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_25);
		card->time_stamp = wCardTickCount;
		card->ranging_type = btType;
		card->power_state = btPower;
		card->call_type = btCallType;
		if (btCallType!=0)
		{
			card->vt_deal_call_reader_id.push_back(card->reader_id);
			if (btCallType == 0x80)
			{
				card->status_help = STATUS_ERROR;
			}
		}
		card->accelerate_state = btAcceleration;
		card->flying_time = lTime1;
		card->sync_num = wSyncNum;
		card->antenna_id = ((btAntenna & 0xFF) == 1) ? 0 : 1;
		card->distance = dldist;

		if(m_log_parse_data){
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_26);
			char chlog[MAX_LOG_LENGTH];
			sprintf_s(chlog, "id:%s, n:%d, type:%d, power:%d, acc:%d, ft:%I64u, d:%f, ant:%d, sn:%d, strength:%d",
				card->card_id.c_str(), wCardTickCount, btType, btPower, btAcceleration, lTime1, dldist, btAntenna, wSyncNum, wStrength);
			std::string strlog = chlog;
			Log::write_log(FILE_TYPE::PARSE_S, strlog, true);
		}
	}else if(LT_READER == theApp.locate_type){
		if(card->time_stamp < 0xFF && card->time_stamp < wCardTickCount){
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_27);
			card->time_stamp = wCardTickCount;
			card->ranging_type = btType;
			card->power_state = btPower;
			card->accelerate_state = btAcceleration;
			card->flying_time = lTime1;
			card->sync_num = wSyncNum;
			card->antenna_id = ((btAntenna & 0xFF) == 1) ? 0 : 1;
			card->distance = dldist;
		}else if(0xFF == card->time_stamp && wCardTickCount == 0){
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_28);
			card->time_stamp = wCardTickCount;
			card->ranging_type = btType;
			card->power_state = btPower;
			card->accelerate_state_last = card->accelerate_state;
			card->accelerate_state = btAcceleration;
			card->flying_time = lTime1;
			card->sync_num = wSyncNum;
			card->antenna_id = ((btAntenna & 0xFF) == 1) ? 0 : 1;
			card->distance = dldist;
		}
	}
}

void CYAServerDlg::parse_data_adhoc( BYTE* DataBuffer, int& nCurPos, int reader_id )
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_29);
	ReaderMap::iterator it = mp_reader_list.find(reader_id);

	BYTE nlen = 0, nDeal = nCurPos;
	//获取自组网数据长度,1字节
	memcpy(&nlen, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	while (nlen > nCurPos - nDeal){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_30);
		//获取命令字，1字节
		BYTE btCmd = 0;
		memcpy(&btCmd, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		btCmd = btCmd&0x3F;
		//获取源地址ID，1字节
		BYTE btId = 0;
		memcpy(&btId, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		//时间戳，1字节
		BYTE btTickcount = 0;
		memcpy(&btTickcount, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		//节点级别，1字节
		BYTE btIdx = 0;
		memcpy(&btIdx, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);

		if(btId != 0){
			string str_card_id = CFunctions::getstrwithzero(CT_ADHOC, 3) + CFunctions::getstrwithzero(btId, 10);
			std::shared_ptr<Card> card = nullptr;
			CardMap::iterator it_card = mp_card_list_all.find(str_card_id);
			if(it_card != mp_card_list_all.end()){
				card = it_card->second;
			}else{
				card = std::make_shared<Card>(str_card_id, CT_ADHOC, theApp.z_offset);
				mp_card_list_all.insert(make_pair(str_card_id, card));
			}
			CardMap::iterator it_adhoc_card = mp_card_list_down_adhoc.find(str_card_id);
			if(it_adhoc_card==mp_card_list_down_adhoc.end()&&it_card!=mp_card_list_all.end()){
				if(card == NULL){
					mp_card_list_down_adhoc.insert(make_pair(str_card_id, it_card->second));
				}else{
					mp_card_list_down_adhoc.insert(make_pair(str_card_id, card));
				}
			}
			//设置当前分站， 进入分站时间、进入区域时间，当前区域，当前地图
			std::shared_ptr<Reader> pReader(it->second);
			card->set_reader(pReader);
			//card->set_reader(it->second);
			if(btIdx < 0 || btIdx >= ADHOC_COUNT){
				btIdx = 0;
			}
			if(it->second->adhoc[btIdx]){
				card->x = it->second->adhoc[btIdx]->x;
				card->y = it->second->adhoc[btIdx]->y;
				card->z = it->second->adhoc[btIdx]->z;
			}

			if(btCmd & 0x01){ // 呼救
				card->status_help = STATUS_ERROR;
			}else if(btCmd & 0x02){ // 呼叫应答，即呼叫成功
				//if(STATUS_NORMAL == card->status_call){
				//	card->state_biz = STATUS_NORMAL;
				//}
				card->status_call = STATUS_NORMAL;
				card->status_help = STATUS_NORMAL;
			}else {
				card->status_call = STATUS_NORMAL;
				card->status_help = STATUS_NORMAL;
			}
			card->issent = false;

			deal_card_msg(card);
		}
	}
}

void CYAServerDlg::add_socket_to_list(DWORD dwConnID, DWORD reader_id, DEVICE_TYPE rt)
{
	if(m_enState != ST_STARTED){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_38);
		return;
	}
	TCHAR szAddress[40];
	int iAddressLen = sizeof(szAddress) / sizeof(TCHAR);
	USHORT usPort;
	if(	_server.GetRemoteAddress(dwConnID, szAddress, iAddressLen, usPort)){
		SocketMap::iterator itSock = mp_socket_list.find(szAddress);
		if(itSock != mp_socket_list.end()){
			itSock->second->dwConnID = dwConnID;
			itSock->second->state = 0;
			itSock->second->reader_type = rt;
			itSock->second->reader_id = reader_id;
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_39);
		}else{
			std::shared_ptr<_SOCK> sock = std::make_shared<_SOCK>();
			sock->sip = szAddress;
			sock->dwConnID = dwConnID;
			sock->state = 0;
			sock->reader_type = rt;
			sock->reader_id = reader_id;
			mp_socket_list.insert(make_pair(sock->sip, sock));

			::PostMessage(this->GetSafeHwnd(), WM_REFRESH_IP_LIST, 1, 0);
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_40);
		}
	}
}

void CYAServerDlg::remove_socket(DWORD dwConnID )
{
	EnterCriticalSection(&m_csRemoveSocket);
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_41);
	bool bNeedRefresh = false;
	SocketMap::iterator _sock = mp_socket_list.begin();
	while(_sock != mp_socket_list.end()){
		if(_sock->second->dwConnID == dwConnID){
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_42);
			//删除之前，判断此连接是否为信号灯控制分站，如果是，则需要将此控制分站所控制的红绿灯的状态设置为不可用
			/*ReaderMap::iterator it_reader = mp_ctrl_reader_list.find(_sock->second->reader_id);
			if (it_reader != mp_ctrl_reader_list.end())
			{
			for (LightMap::iterator it_light = mp_light_list.begin(); it_light != mp_light_list.end();++it_light)
			{
			if(it_light->second->m_strIP == it_reader->second->ip){
			it_light->second->m_nState = STATUS_ERROR;
			}
			}
			}*/
			_sock = mp_socket_list.erase(_sock);
			bNeedRefresh = true;
		}else{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_43);
			++_sock;
		}
	}
	if(bNeedRefresh){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_44);
		::PostMessage(this->GetSafeHwnd(), WM_REFRESH_IP_LIST, 0, 0);
	}
	LeaveCriticalSection(&m_csRemoveSocket);
}

// 获取设备状态信息, 分站、红绿灯、道岔、扩音器
std::string CYAServerDlg::get_json_device_state()
{
	std::string ret = "";
	Json::Value root;	
	Json::Value data;

	MapInfoMap::iterator it_map = mp_map_list.begin();

	for(; it_map != mp_map_list.end(); ++it_map){
		//定位分站列表
		ReaderMap::iterator it_reader = mp_reader_list.begin();
		for (it_reader;it_reader!=mp_reader_list.end();++it_reader)
		{
			if (it_reader->second->map_id != it_map->second->map_id)
			{
				continue;
			}

			if(it_reader->second->reader_state != it_reader->second->reader_state_old || difftime(time(NULL), it_reader->second->last_send_time) > READER_SEND_STATE_TIMEOUT)
			{
				Json::Value state_dev;
				state_dev.append(it_reader->second->reader_id);
				state_dev.append(it_reader->second->device_type_id);
				state_dev.append(it_reader->second->reader_state);
				int ms = 1000; //转为ms
				//入井时间戳
				double t = *((int64_t*)&it_reader->second->rec_time)*ms;
				state_dev.append(t);
				state_dev.append(it_map->second->map_id);
				state_dev.append(it_reader->second->reader_state);
				data.append(state_dev);

				it_reader->second->reader_state_old = it_reader->second->reader_state;
				it_reader->second->last_send_time = time(NULL);
			}
		}

		//通信分站列表
		ReaderMap::iterator it_ctrl_reader = mp_ctrl_reader_list.begin();
		for (it_ctrl_reader;it_ctrl_reader!=mp_ctrl_reader_list.end();++it_ctrl_reader)
		{
			if (it_ctrl_reader->second->map_id != it_map->second->map_id)
			{
				continue;
			}

			//实现增量上报，按时上报
			if(it_ctrl_reader->second->reader_state != it_ctrl_reader->second->reader_state_old || difftime(time(NULL), it_ctrl_reader->second->last_send_time) > READER_SEND_STATE_TIMEOUT)
			{
				Json::Value state_dev;
				state_dev.append(it_ctrl_reader->second->reader_id);
				state_dev.append(it_ctrl_reader->second->device_type_id);
				state_dev.append(it_ctrl_reader->second->reader_state);
				int ms = 1000; //转为ms
				//入井时间戳
				double t = *((int64_t*)&it_ctrl_reader->second->rec_time)*ms;
				state_dev.append(t);
				state_dev.append(it_map->second->map_id);
				state_dev.append(it_ctrl_reader->second->reader_state);
				data.append(state_dev);
				it_ctrl_reader->second->reader_state_old = it_ctrl_reader->second->reader_state;
				it_ctrl_reader->second->last_send_time = time(NULL);
			}
		} 
		//红绿灯
		LightMap::iterator it_light = mp_light_list.begin();
		for (it_light;it_light!=mp_light_list.end();++it_light)
		{
			if (it_light->second->m_nMapID != it_map->second->map_id)
			{
				continue;
			}

			if (it_light->second->m_nState != it_light->second->m_nOldState || difftime(time(NULL), it_light->second->last_send_time) > READER_SEND_STATE_TIMEOUT)
			{
				Json::Value state_dev;
				state_dev.append(it_light->second->m_nID);
				state_dev.append(it_light->second->device_type_id);
				state_dev.append(it_light->second->m_nShape);
				ReaderMap::iterator it_ctrl_reader = mp_ctrl_reader_list.find(it_light->second->m_nReaderID);
				double t = 0;
				if (it_ctrl_reader != mp_ctrl_reader_list.end())
				{
					int ms = 1000; //转为ms
					//入井时间戳
					t = *((int64_t*)&it_ctrl_reader->second->rec_time)*ms;				
				}
				state_dev.append(t);
				state_dev.append(it_map->second->map_id);
				state_dev.append(it_light->second->m_nState);
				data.append(state_dev);
				it_light->second->m_nOldState = it_light->second->m_nOldState;
				it_light->second->last_send_time = time(NULL);
			}
		}
	}

	if (data.size() > 0)
	{
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_DEV_STATE;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		root[JSON_ROOT_KEY_DATA] = data;
		ret = root.toFastString();
	}

	return ret;
}

int CYAServerDlg::get_help_card_nums()
{
	/*if (mp_card_list_down_adhoc.size() == 0)
	{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_55);
	return 0;
	}

	int nRet = 0;
	CardMap::iterator it = mp_card_list_down_adhoc.begin();
	for(it;it!=mp_card_list_down_adhoc.end();++it){
	if(it->second->status_help == STATUS_ERROR){
	nRet++;
	}
	}
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_56);*/

	int nRet = 0;

	//统计自组网卡的呼救
	if (mp_card_list_down_adhoc.size() == 0)
	{
		CardMap::iterator it = mp_card_list_down_adhoc.begin();
		for(it;it!=mp_card_list_down_adhoc.end();++it){
			if(it->second->status_help == STATUS_ERROR){
				nRet++;
			}
		}
	}

	//统计人员的呼救
	if (mp_card_list_down_person.size() == 0)
	{
		CardMap::iterator it = mp_card_list_down_person.begin();
		for(it;it!=mp_card_list_down_person.end();++it){
			if(it->second->status_help == STATUS_ERROR){
				nRet++;
			}
		}
	}

	return nRet;
}

int CYAServerDlg::get_map_path_nums(const int& start_reader_id,const int& end_reader_id)
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_57);
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	//无可用数据库连接
	if(pConn == NULL){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_58);
		return 1;
	}

	int nRet = 0;

	char sql[LENGTH_SQL] = {0};
	sprintf_s(sql,"select count(idx) from dat_reader_path_tdoa where start_reader_id = %d and end_reader_id = %d;",start_reader_id,end_reader_id);

	MYSQL_RES* pRes = NULL;
	MYSQL_ROW pRow;
	int err = 0;
	int nRow = 0;

	//查询数据库
	pRes = pConn->Execute(sql,err);

	if (err)
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_59);
		return 0;
	}

	while(pRow = mysql_fetch_row(pRes)){
		nRet = atoi(pRow[0]);
	}
	mysql_free_result(pRes);

	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_60);

	return nRet;
}

int CYAServerDlg::parse_json_data_reader_pos_change(message::ptr const& data)
{
	init_reader();
	debug_print_syslog(0, "Init reader postion success.");
	init_drivingface_render();
	debug_print_syslog(0, "Init drivingface render success.");
	return 0;
}


std::string CYAServerDlg::get_json_help()
{
	Json::Value root;
	Json::Value alarms;
	Json::Value adhoc;
	char _time[STR_LEN_TIME];
	struct tm local_time;

	CardMap::iterator it_adhoc = mp_card_list_down_adhoc.begin();

	for(;it_adhoc!=mp_card_list_down_adhoc.end();++it_adhoc){
		if(it_adhoc->second->status_help == STATUS_NORMAL){
			continue;
		}
		Json::Value alarm;
		if(it_adhoc->second->status_help == STATUS_ERROR){		
			alarm[JSON_KEY_CARD_ID] = it_adhoc->second->card_id;
			alarm[JSON_KEY_CARD_TYPE_ID] = it_adhoc->second->card_type;
			localtime_s(&local_time, &it_adhoc->second->enter_reader_time);
			strftime(_time, STR_LEN_TIME, "%Y-%m-%d %H:%M:%S", &local_time);
			alarm["start_time"] = _time;
		}
		if(!alarm.isNull()){
			alarms.append(alarm);
		}
	}

	for(CardMap::iterator it_person = mp_card_list_down_person.begin();it_person!=mp_card_list_down_person.end();++it_person){
		if(it_person->second->status_help == STATUS_NORMAL){
			continue;
		}
		Json::Value alarm;
		if(it_person->second->status_help == STATUS_ERROR){		
			alarm[JSON_KEY_CARD_ID] = it_person->second->card_id;
			alarm[JSON_KEY_CARD_TYPE_ID] = it_person->second->card_type;
			localtime_s(&local_time, &it_person->second->enter_reader_time);
			strftime(_time, STR_LEN_TIME, "%Y-%m-%d %H:%M:%S", &local_time);
			alarm["start_time"] = _time;
		}
		if(!alarm.isNull()){
			alarms.append(alarm);
		}
	}

	if(!alarms.isNull()){
		root[JSON_ROOT_KEY_CMD] = "helpme_req";
		root[JSON_ROOT_KEY_DATA] = alarms; 
	}
	return root.toFastString();
}

Json::Value CYAServerDlg::get_section_json_alarm()
{	
	int nTotals = 0;

	Json::Value sections;
	Json::Value data;

	sections[JSON_ROOT_KEY_CMD]   = JSON_KEY_ALARM_SECTION;

	SectionMap::iterator it = mp_section_list.begin();
	for (;it != mp_section_list.end(); ++it)
	{
		//正常路段不报警
		if (it->second->get_section_state() == SECTION_STATE_NORMAL)
		{
			continue;
		}

		Json::Value tmp;
		Json::Value section;

		//路段id
		tmp[JSON_KEY_ALARM_SECTION_ID] = it->second->m_nID;
		section.append(tmp[JSON_KEY_ALARM_SECTION_ID]);
		//地图id
		tmp[JSON_KEY_MAP_ID] = it->second->m_nMapId;
		section.append(tmp[JSON_KEY_MAP_ID]);
		//路段内车辆总数
		tmp[JSON_KEY_ALARM_SECTION_VEHICLE_COUNTS] = it->second->get_section_vehicle_counts();
		section.append(tmp[JSON_KEY_ALARM_SECTION_VEHICLE_COUNTS]);
		//路段内人员总数
		tmp[JSON_KEY_ALARM_SECTION_STAFFER_COUNTS] = it->second->get_section_staffer_counts();
		section.append(tmp[JSON_KEY_ALARM_SECTION_STAFFER_COUNTS]);
		//路段状态
		tmp[JSON_KEY_ALARM_SECTION_STATE] = it->second->get_section_state();
		section.append(tmp[JSON_KEY_ALARM_SECTION_STATE]);
		//路段开始报警时间
		int ms = 1000; //转为ms
		double t = *((int64_t*)&it->second->alarm_start_time)*ms;
		tmp[JSON_KEY_ALARM_START_TIME] = t;
		section.append(tmp[JSON_KEY_ALARM_START_TIME]);

		if (!section.isNull())
		{
			data.append(section);
		}

		nTotals++;
	}
	sections[JSON_ROOT_KEY_TOTAL] = nTotals;

	if (data != NULL)
	{
		sections[JSON_ROOT_KEY_DATA] = data;
	}
	return sections;
}

Json::Value CYAServerDlg::get_light_json_alarm()
{
	Json::Value lights;
	Json::Value data;

	//cmd
	lights[JSON_ROOT_KEY_CMD] = JSON_KEY_ALARM_LIGHT;

	//data
	LightMap::iterator it = mp_light_list.begin();
	for (;it != mp_light_list.end();++it)
	{
		if (it->second->m_nState == STATUS_NORMAL && it->second->m_nStateBiz == STATUS_NORMAL)
		{
			//continue;
		}

		Json::Value tmp;
		Json::Value light;

		//light_id
		tmp[JSON_KEY_ALARM_LIGHT_ID] = it->second->m_nID;
		light.append(tmp[JSON_KEY_ALARM_LIGHT_ID]);

		//light_group_id,light_group_name,vehicle_id(控制此灯组id)
		LightGroupMap::iterator lgm = mp_light_group_list.find(it->second->m_nLightsGroupID);
		if (lgm != mp_light_group_list.end())
		{
			tmp[JSON_KEY_ALARM_LIGHT_GROUP_ID] = lgm->second->m_nID;
			light.append(tmp[JSON_KEY_ALARM_LIGHT_GROUP_ID]);

			tmp[JSON_KEY_ALARM_LIGHT_GROUP_NAME] = lgm->second->m_strName;
			light.append(tmp[JSON_KEY_ALARM_LIGHT_GROUP_NAME]);

			tmp[JSON_KEY_ALARM_VEHICLE_ID] = lgm->second->m_strVechileId;
			light.append(tmp[JSON_KEY_ALARM_VEHICLE_ID]);

		}else{
			tmp[JSON_KEY_ALARM_LIGHT_GROUP_ID] = 0;
			light.append(tmp[JSON_KEY_ALARM_LIGHT_GROUP_ID]);

			tmp[JSON_KEY_ALARM_LIGHT_GROUP_NAME] = "";
			light.append(tmp[JSON_KEY_ALARM_LIGHT_GROUP_NAME]);

			tmp[JSON_KEY_ALARM_VEHICLE_ID] = "";
			light.append(tmp[JSON_KEY_ALARM_VEHICLE_ID]);
		}

		if (it->second->m_nState == STATUS_NORMAL)
		{
			tmp[JSON_KEY_STATE] = STATUS_NORMAL;
			tmp[JSON_KEY_STATE_BIZ] = STATUS_NORMAL;
		}else{
			tmp[JSON_KEY_STATE] = it->second->m_nState;
			tmp[JSON_KEY_STATE_BIZ] = it->second->m_nStateBiz;
		}
		light.append(tmp[JSON_KEY_STATE]);
		light.append(tmp[JSON_KEY_STATE_BIZ]);

		//路段开始报警时间
		int ms = 1000; //转为ms
		double t = *((int64_t*)&it->second->alarm_start_time)*ms;
		tmp[JSON_KEY_ALARM_START_TIME] = t;
		light.append(tmp[JSON_KEY_ALARM_START_TIME]);

		if (!light.isNull())
		{
			data.append(light);
		}
	}
	if (!data.isNull())
	{
		lights[JSON_ROOT_KEY_DATA] = data;
	}

	return lights;
}

/*
* 闯红灯告警json
*
* param
*		无
*
* return
*		json对象
*
*/
Json::Value CYAServerDlg::get_red_light_json_alarm()
{
	Json::Value redLightEvent;
	Json::Value data;

	redLightEvent[JSON_ROOT_KEY_CMD] = JSON_KEY_ALARM_TRAFFIC_RED_LIGHT;

	CardMap::iterator it = mp_card_list_all.begin();
	for (;it != mp_card_list_all.end();++it)
	{
		//如果此卡闯红灯了
		if (!it->second->is_red_light)
		{
			Json::Value redLight;
			Json::Value record;

			//闯红灯车辆id，被闯灯id，闯红灯时间，司机id
			redLight[JSON_KEY_ALARM_VEHICLE_ID] = it->second->card_id;
			record.append(redLight[JSON_KEY_ALARM_VEHICLE_ID]);

			redLight[JSON_KEY_ALARM_LIGHT_ID] = it->second->light_id;
			record.append(redLight[JSON_KEY_ALARM_LIGHT_ID]);

			int ms = 1000; //转为ms
			double t = *((int64_t*)&it->second->time_red_light)*ms;
			redLight[JSON_KEY_ALARM_START_TIME] = t;
			record.append(redLight[JSON_KEY_ALARM_START_TIME]);

			redLight[JSON_KEY_ALARM_STAFFER_ID] = it->second->driver_id;
			record.append(redLight[JSON_KEY_ALARM_STAFFER_ID]);

			if (!record.isNull())
			{
				data.append(record);
			}
		}
	}

	if (!data.isNull())
	{
		redLightEvent[JSON_ROOT_KEY_DATA] = data;
	}

	return redLightEvent;
}

Json::Value CYAServerDlg::get_json_count_list(int req_type,int area_id)
{
	std::string ret = "";

	Json::Value data;
	CardMap::iterator it_card;

	switch(req_type){
	case REQUEST_ALL:
		break;
	case REQUEST_ALL_OVER_TIME_PERSON:
		//人员井下超时
		for (EventMap::iterator it = mp_event_list->begin();it!=mp_event_list->end();++it)
		{
			if (it->second->ev_type == ET_CARD_OVER_TIME_PERSON && it->second->obj_type == OT_CARD)
			{
				it_card = mp_card_list_all.find(it->second->obj_id);
				if (it_card != mp_card_list_all.end() &&it_card->second->card_type == CT_PERSON)
				{
					////找到满足此异常条件卡对象
					Json::Value card_value;

					card_value = get_card_info(it_card->second);
					data.append(card_value);
				}
			}
		}
		break;
	case REQUEST_AREA_OVER_TIME_PERSON:
		//人员区域超时
		for (EventMap::iterator it = mp_event_list->begin();it!=mp_event_list->end();++it)
		{
			if (it->second->ev_type == ET_CARD_AREA_OVER_TIME_PERSON && it->second->obj_type == OT_CARD)
			{
				it_card = mp_card_list_all.find(it->second->obj_id);
				if (it_card != mp_card_list_all.end())
				{
					if (it_card->second->card_type == CT_PERSON)
					{
						if (area_id != 0 && area_id == it_card->second->area_id)
						{
							Json::Value card_value;
							card_value = get_card_info(it_card->second);
							data.append(card_value);
						}
						else{
							//等于0 即全区域的,全区域的即为井下所有超时人员
							//std::string all_area = "";
							//for (AreaMap::iterator it_area = mp_area_list.begin();it_area != mp_area_list.end();++it_area)
							//{
							//	all_area += get_json_count_list(ET_CARD_AREA_OVER_TIME_PERSON,it_area->second->area_id);
							//}
							//data.append(all_area);
						}	
					}
				}
			}
		}
	case REQUEST_SPECIAL_ERROR_PERSON:
		//特种作业人员异常报警详细列表
		for (EventMap::iterator it = mp_event_list->begin();it!=mp_event_list->end();++it)
		{
			//电量低
			//电量极低
			//人员进入限制区域
			//人员巡检异常
			if ((it->second->ev_type == ET_CARD_LOW_POWER 
				||it->second->ev_type == ET_CARD_LOW_POWER_SERIOUS
				||it->second->ev_type == ET_CARD_AREA_FORBIDDEN_PERSON
				|| it->second->ev_type == ET_CARD_PATROL_ERROR) && it->second->obj_type == OT_CARD)
			{
				it_card = mp_card_list_all.find(it->second->obj_id);
				if (it_card != mp_card_list_all.end())
				{
					if (it_card->second->card_type == CT_PERSON && it_card->second->occupation == "安检员")
					{
						//找到满足此异常条件卡对象
						Json::Value card_value;

						card_value = get_card_info(it_card->second);
						data.append(card_value);
					}	
				}
			}
		}
		break;
	case REQUEST_ALL_OVER_TIME_VEHICLE: 
		// 车辆井下超时
		for (EventMap::iterator it = mp_event_list->begin();it!=mp_event_list->end();++it)
		{
			if (it->second->ev_type == ET_CARD_OVER_TIME_VEHICLE && it->second->obj_type == OT_CARD)
			{
				it_card = mp_card_list_all.find(it->second->obj_id);
				if (it_card != mp_card_list_all.end())
				{
					if (it_card->second->card_type == CT_VEHICLE)
					{
						//找到满足此异常条件卡对象
						Json::Value card_value;

						card_value = get_card_info(it_card->second);
						data.append(card_value);
					}	
				}
			}
		}
		break;
	case REQUEST_AREA_OVER_TIME_VEHICLE:
		// 车辆区域超时
		for (EventMap::iterator it = mp_event_list->begin();it!=mp_event_list->end();++it)
		{
			if (it->second->ev_type == ET_CARD_AREA_OVER_TIME_VEHICLE && it->second->obj_type == OT_CARD)
			{
				it_card = mp_card_list_all.find(it->second->obj_id);
				if (it_card != mp_card_list_all.end())
				{
					if (it_card->second->card_type == CT_VEHICLE)
					{
						if (area_id != 0 && area_id == it_card->second->area_id)
						{
							Json::Value card_value;
							card_value = get_card_info(it_card->second);
							data.append(card_value);
						}
						else{
							//等于0 即全区域的,全区域的即为井下所有超时车辆
							//std::string all_area = "";
							//for (AreaMap::iterator it_area = mp_area_list.begin();it_area != mp_area_list.end();++it_area)
							//{
							//	all_area += get_json_count_list(ET_CARD_AREA_OVER_TIME_PERSON,it_area->second->area_id);
							//}
							//data.append(all_area);
						}	
					}
				}
			}
		}
		break;
	case REQUEST_ALL_OVER_PERSON:
		//井下人员超员，返回全部人员信息
		for (CardMap::iterator it_card = mp_card_list_down_person.begin();it_card != mp_card_list_down_person.end();++it_card)
		{
			Json::Value card_value;
			card_value = get_card_info(it_card->second);
			data.append(card_value);
		}
		break;
	case REQUEST_ALL_OVER_VEHICLE:
		//井下车辆超员，返回全部车辆信息
		for (CardMap::iterator it_card = mp_card_list_down_vehicle.begin();it_card != mp_card_list_down_vehicle.end();++it_card)
		{
			Json::Value card_value;
			card_value = get_card_info(it_card->second);
			data.append(card_value);
		}
		break;
	case REQUEST_AREA_OVER_PERSON:
		//区域人员超员，返回区域所有人员
		for (AreaMap::iterator it_area = mp_area_list.begin();it_area != mp_area_list.end();++it_area)
		{
			for (CardMap::iterator it_person = it_area->second->area_card_list_person->begin();it_person != it_area->second->area_card_list_person->end();++it_person)
			{
				Json::Value card_value;
				card_value = get_card_info(it_person->second);
				data.append(card_value);
			}	
		}
		break;
	case REQUEST_AREA_OVER_VEHICLE:
		//区域车辆超员，返回区域所有车辆
		for (AreaMap::iterator it_area = mp_area_list.begin();it_area != mp_area_list.end();++it_area)
		{
			for (CardMap::iterator it_vehicle = it_area->second->area_card_list_vehicle->begin();it_vehicle != it_area->second->area_card_list_vehicle->end();++it_vehicle)
			{
				Json::Value card_value;
				card_value = get_card_info(it_vehicle->second);
				data.append(card_value);
			}	
		}
		break;
	}

	if (data.size() > 0)
	{
		ret = data.toFastString();
	}

	return data;
}

Json::Value CYAServerDlg::get_card_info(std::shared_ptr<Card> pCard)
{
	//找到满足此异常条件卡对象
	Json::Value data;
	//名字
	data.append(pCard->name);
	//身份证号
	data.append(pCard->number);
	//下井时间
	int ms = 1000; //转为ms
	//入井时间戳
	double t = *((int64_t*)&pCard->down_time)*ms;
	data.append(t);
	//接收时间
	t = *((int64_t*)&pCard->rec_time)*ms;
	data.append(t);
	//工作时长"",
	t = (int)(difftime(time(NULL), pCard->down_time))*ms;
	data.append(t);
	//地图
	data.append(pCard->map_id);
	//区域
	data.append(pCard->area_id);
	//部门
	data.append(pCard->department);
	//设备状态，现在显示暂改为显示电量
	data.append(pCard->state);

	return data;
}

std::string CYAServerDlg::get_json_special_area_process(std::shared_ptr<Card> card /*Card* card*/ )
{
	//新json格式
	Json::Value root;
	Json::Value val_card;
	Json::Value val_cards;

	//卡号
	val_card[JSON_KEY_CARD_ID] = card->card_id;
	val_cards.append(val_card[JSON_KEY_CARD_ID]);

	//if(card->pos_state == PDT_DOWN){
	//x,y坐标
	val_card[JSON_KEY_CORDINATE_X] = CFunctions::round(card->x,2);
	val_cards.append(val_card[JSON_KEY_CORDINATE_X]);
	val_card[JSON_KEY_CORDINATE_Y] = CFunctions::round(card->y,2);
	val_cards.append(val_card[JSON_KEY_CORDINATE_Y]);
	//}else{
	//	val_card[JSON_KEY_CORDINATE_X] = 0;
	//	val_cards.append(val_card[JSON_KEY_CORDINATE_X]);
	//	val_card[JSON_KEY_CORDINATE_Y] = 0;
	//	val_cards.append(val_card[JSON_KEY_CORDINATE_Y]);
	//}

	int ms = 1000;
	//入井时间戳
	double t = *((int64_t*)&card->down_time)*ms;	//转为ms
	val_card[JSON_KEY_DOWN_TIME] = t;
	val_cards.append(val_card[JSON_KEY_DOWN_TIME]);

	//进入区域时间戳
	time_t eat = CFunctions::systime_to_timet(card->enter_area_time);
	t = *((int64_t*)&eat)*ms;
	val_card[JSON_KEY_ENTER_AREA_TIME] = t;
	val_cards.append(val_card[JSON_KEY_ENTER_AREA_TIME]);

	if(card->PosState() == PDT_DOWN){
		//接收时间戳
		t = *((int64_t*)&card->rec_time)*ms;
		val_card[JSON_KEY_REC_TIME] = t;
		val_cards.append(val_card[JSON_KEY_REC_TIME]);
		//工作时长
		t = (int)(difftime(time(NULL), card->down_time))*ms;
		val_card[JSON_KEY_WORK_TIME] = t;
		val_cards.append(val_card[JSON_KEY_WORK_TIME]);
	}else{
		//接收时间戳
		val_card[JSON_KEY_REC_TIME] = 0;
		val_cards.append(val_card[JSON_KEY_REC_TIME]);
		//工作时长
		//t = (int)(difftime(time(NULL), card->down_time));
		val_card[JSON_KEY_WORK_TIME] = 0;
		val_cards.append(val_card[JSON_KEY_WORK_TIME]);
	}

	//地图编号
	val_card[JSON_KEY_MAP_ID] = card->map_id;
	val_cards.append(val_card[JSON_KEY_MAP_ID]);
	//区域编号
	val_card[JSON_KEY_AREA_ID] = card->area_id;
	val_cards.append(val_card[JSON_KEY_AREA_ID]);

	//是否特殊区域
	AreaMap::iterator it_area_cur = mp_area_list.find(card->area_id);
	if(it_area_cur != mp_area_list.end())
	{
		val_card[JSON_KEY_AREA_IS_SPECIAL] = it_area_cur->second->is_special();
		val_cards.append(val_card[JSON_KEY_AREA_IS_SPECIAL]);
	}
	else
	{
		return NULL;
	}

	//部门编号
	val_card[JSON_KEY_DEPT_ID] = card->dept_id;
	val_cards.append(val_card[JSON_KEY_DEPT_ID]);

	if(card->PosState() == PDT_DOWN){
		card->get_state_text();
		//状态
		val_card[JSON_KEY_STATE] = card->state;
		val_cards.append(val_card[JSON_KEY_STATE]);

		//运行状态
		card->get_acc_text();
		val_card[JSON_KEY_STATE_MOVING] = card->state_moving;
		val_cards.append(val_card[JSON_KEY_STATE_MOVING]);

		//业务状态
		val_card[JSON_KEY_STATE_BIZ] = card->StateBiz();
		val_cards.append(val_card[JSON_KEY_STATE_BIZ]);

		//速度
		val_card[JSON_KEY_SPEED] =  CFunctions::round(card->get_speed(),0);
		val_cards.append(val_card[JSON_KEY_SPEED]);
	}else{
		//状态
		val_card[JSON_KEY_STATE] = 0;
		val_cards.append(val_card[JSON_KEY_STATE]);

		//运行状态
		val_card[JSON_KEY_STATE_MOVING] = 0;
		val_cards.append(val_card[JSON_KEY_STATE_MOVING]);

		//业务状态
		val_card[JSON_KEY_STATE_BIZ] = 0;
		val_cards.append(val_card[JSON_KEY_STATE_BIZ]);

		//速度
		val_card[JSON_KEY_SPEED] = 0;
		val_cards.append(val_card[JSON_KEY_SPEED]);

	}

	root[JSON_ROOT_KEY_CMD] = (PDT_DOWN == card->PosState())? JSON_CMD_VALUE_DOWN_MINE : JSON_CMD_VALUE_SPECIAL_AREA_UP_MINE;
	root[JSON_ROOT_KEY_DATA].append(val_cards);

	return root.toFastString();
}


std::string CYAServerDlg::get_json_all_special_area_data()
{
	//新json格式
	Json::Value root;
	Json::Value data;

	for (CardMap::iterator it_card = mp_card_list_all.begin();it_card != mp_card_list_all.end();++it_card)
	{
		Json::Value val_card;
		Json::Value val_cards;

		//卡号
		val_cards.append(it_card->second->card_id);

		//x,y坐标
		val_cards.append(CFunctions::round(it_card->second->x,2));
		val_cards.append(CFunctions::round(it_card->second->y,2));

		int ms = 1000;
		//入井时间戳
		double t = *((int64_t*)&it_card->second->down_time)*ms;	//转为ms
		val_cards.append(t);

		//进入区域时间戳
		time_t eat = CFunctions::systime_to_timet(it_card->second->enter_area_time);
		t = *((int64_t*)&eat)*ms;
		val_cards.append(t);

		//接收时间戳
		t = *((int64_t*)&it_card->second->rec_time)*ms;
		val_cards.append(t);

		//工作时长
		t = (int)difftime(it_card->second->rec_time, it_card->second->down_time)*ms;
		val_cards.append(t);

		//地图编号
		val_cards.append(it_card->second->map_id);
		//区域编号s
		val_cards.append(it_card->second->area_id);

		//是否特殊区域
		AreaMap::iterator it_area_cur = mp_area_list.find(it_card->second->area_id);
		if(it_area_cur != mp_area_list.end())
		{
			if (it_area_cur->second->is_special())
			{
				val_cards.append(it_area_cur->second->is_special());
			}
			else
			{
				continue;
			}		
		}
		else
		{
			continue;
		}

		//部门编号
		val_cards.append(it_card->second->dept_id);

		//状态
		val_cards.append(0);

		//运行状态
		val_cards.append(0);

		//业务状态
		val_cards.append(0);

		//速度s
		val_cards.append(0);

		std::string sc="";
		sc = val_cards.toFastString();

		if (val_cards.size() > 0)
		{
			data.append(val_cards);
		}
	}

	std::string ret = "";
	if (data.size() > 0)
	{
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_SPECIAL_AREA_UP_MINE;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		root[JSON_ROOT_KEY_DATA] = data;

		ret = root.toFastString();
	}

	return ret;
}
std::string CYAServerDlg::get_json_down_and_up(std::shared_ptr<Card> card /*Card* card*/ )
{
	//新json格式
	Json::Value root;
	Json::Value val_card;
	Json::Value val_cards;

	//卡号
	val_card[JSON_KEY_CARD_ID] = card->card_id;
	val_cards.append(val_card[JSON_KEY_CARD_ID]);

	//if(card->pos_state == PDT_DOWN){
	//x,y坐标
	val_card[JSON_KEY_CORDINATE_X] = CFunctions::round(card->x,2);
	val_cards.append(val_card[JSON_KEY_CORDINATE_X]);
	val_card[JSON_KEY_CORDINATE_Y] = CFunctions::round(card->y,2);
	val_cards.append(val_card[JSON_KEY_CORDINATE_Y]);
	//}else{
	//	val_card[JSON_KEY_CORDINATE_X] = 0;
	//	val_cards.append(val_card[JSON_KEY_CORDINATE_X]);
	//	val_card[JSON_KEY_CORDINATE_Y] = 0;
	//	val_cards.append(val_card[JSON_KEY_CORDINATE_Y]);
	//}

	int ms = 1000;
	//入井时间戳
	double t = *((int64_t*)&card->down_time)*ms;	//转为ms
	val_card[JSON_KEY_DOWN_TIME] = t;
	val_cards.append(val_card[JSON_KEY_DOWN_TIME]);

	//进入区域时间戳
	time_t eat = CFunctions::systime_to_timet(card->enter_area_time);
	t = *((int64_t*)&eat)*ms;
	val_card[JSON_KEY_ENTER_AREA_TIME] = t;
	val_cards.append(val_card[JSON_KEY_ENTER_AREA_TIME]);

	if(card->PosState() == PDT_DOWN){
		//接收时间戳
		t = *((int64_t*)&card->rec_time)*ms;
		val_card[JSON_KEY_REC_TIME] = t;
		val_cards.append(val_card[JSON_KEY_REC_TIME]);
		//工作时长
		t = (int)(difftime(time(NULL), card->down_time))*ms;
		val_card[JSON_KEY_WORK_TIME] = t;
		val_cards.append(val_card[JSON_KEY_WORK_TIME]);
	}else{
		val_card[JSON_KEY_REC_TIME] = 0;
		val_cards.append(val_card[JSON_KEY_REC_TIME]);
		//工作时长
		//t = (int)(difftime(time(NULL), card->down_time));
		val_card[JSON_KEY_WORK_TIME] = 0;
		val_cards.append(val_card[JSON_KEY_WORK_TIME]);
	}

	//地图编号
	val_card[JSON_KEY_MAP_ID] = card->map_id;
	val_cards.append(val_card[JSON_KEY_MAP_ID]);
	//区域编号
	val_card[JSON_KEY_AREA_ID] = card->area_id;
	val_cards.append(val_card[JSON_KEY_AREA_ID]);
	//部门编号
	val_card[JSON_KEY_DEPT_ID] = card->dept_id;
	val_cards.append(val_card[JSON_KEY_DEPT_ID]);

	if(card->PosState() == PDT_DOWN){
		card->get_state_text();
		//状态
		val_card[JSON_KEY_STATE] = card->state;
		val_cards.append(val_card[JSON_KEY_STATE]);

		//运行状态
		card->get_acc_text();
		val_card[JSON_KEY_STATE_MOVING] = card->state_moving;
		val_cards.append(val_card[JSON_KEY_STATE_MOVING]);

		//业务状态
		val_card[JSON_KEY_STATE_BIZ] = card->StateBiz();
		val_cards.append(val_card[JSON_KEY_STATE_BIZ]);

		//速度
		val_card[JSON_KEY_SPEED] = CFunctions::round(card->get_speed(), 0);
		val_cards.append(val_card[JSON_KEY_SPEED]);
	}else{
		//状态
		val_card[JSON_KEY_STATE] = 0;
		val_cards.append(val_card[JSON_KEY_STATE]);

		//运行状态
		val_card[JSON_KEY_STATE_MOVING] = 0;
		val_cards.append(val_card[JSON_KEY_STATE_MOVING]);

		//业务状态
		val_card[JSON_KEY_STATE_BIZ] = 0;
		val_cards.append(val_card[JSON_KEY_STATE_BIZ]);

		//速度
		val_card[JSON_KEY_SPEED] = 0;
		val_cards.append(val_card[JSON_KEY_SPEED]);
	}

	root[JSON_ROOT_KEY_CMD] = (PDT_DOWN == card->PosState())? JSON_CMD_VALUE_DOWN_MINE : JSON_CMD_VALUE_UP_MINE;
	root[JSON_ROOT_KEY_DATA].append(val_cards);

	return root.toFastString();
}

std::string CYAServerDlg::get_json_position()
{
	return get_json_card_statistic();

	Json::Value root;

	int cnt = 0;
	MapInfoMap::iterator it_map = mp_map_list.begin();
	for(; it_map != mp_map_list.end(); ++it_map){
		CardMap::iterator it = mp_card_list_all.begin();
		for(; it != mp_card_list_all.end(); ++it){
			/*if(it->second->pos_state != DT_DOWN){
			continue;
			}*/
			//if(it->second->pos_state != PDT_DOWN){
			//	continue;
			//}
			if(it->second->issent) {
				continue;
			}
			if(it->second->map_id != it_map->second->map_id){
				continue;
			}
			if(!it->second->isdealed){
				continue;
			}
			if (!it->second->isoutput)
			{
				continue;
			}

			if(_isnan(it->second->x) || _isnan(it->second->y) || _isnan(it->second->get_speed())){
				continue;
			}
			if (it->second->x == INVALID_COORDINATE || it->second->y == INVALID_COORDINATE)
			{
				continue;
			}

			Json::Value pos_cards;
			Json::Value pos_card;

			it->second->isdealed = false;
			it->second->issent = true;
			it->second->isoutput = false;

			//卡号
			pos_cards.append(it->second->card_id);

			if (fabs(it->second->x) < 1E-4 && fabs(it->second->y) < 1E-4)
			{
				continue;
			}

			//x,y坐标
			pos_card[JSON_KEY_CORDINATE_X] = CFunctions::round(it->second->x, 2);
			pos_cards.append(pos_card[JSON_KEY_CORDINATE_X]);
			pos_card[JSON_KEY_CORDINATE_Y] = CFunctions::round(it->second->y, 2);
			pos_cards.append(pos_card[JSON_KEY_CORDINATE_Y]);

			/*switch(it->second->m_nOutputPosState){
			case 0:
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_225);
			pos_card[JSON_KEY_CORDINATE_X] = CFunctions::round(it->second->x, 2);
			pos_cards.append(pos_card[JSON_KEY_CORDINATE_X]);
			pos_card[JSON_KEY_CORDINATE_Y] = CFunctions::round(it->second->y, 2);
			pos_cards.append(pos_card[JSON_KEY_CORDINATE_Y]);
			break;
			case 1:
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_226);
			pos_card[JSON_KEY_CORDINATE_X] = CFunctions::round(it->second->left_x, 2);
			pos_cards.append(pos_card[JSON_KEY_CORDINATE_X]);
			pos_card[JSON_KEY_CORDINATE_Y] = CFunctions::round(it->second->left_y, 2);
			pos_cards.append(pos_card[JSON_KEY_CORDINATE_Y]);
			break;
			case 2:
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_227);
			pos_card[JSON_KEY_CORDINATE_X] = CFunctions::round(it->second->right_x, 2);
			pos_cards.append(pos_card[JSON_KEY_CORDINATE_X]);
			pos_card[JSON_KEY_CORDINATE_Y] = CFunctions::round(it->second->right_y, 2);
			pos_cards.append(pos_card[JSON_KEY_CORDINATE_Y]);
			break;
			default:
			break;
			}*/

			int ms = 1000; //转为ms
			//入井时间戳
			double t = *((int64_t*)&it->second->down_time)*ms;
			pos_card[JSON_KEY_DOWN_TIME] = t;
			pos_cards.append(pos_card[JSON_KEY_DOWN_TIME]);

			//进入区域时间戳
			time_t tt = CFunctions::systime_to_timet(it->second->enter_area_time);
			t = *((int64_t*)&tt)*ms;
			pos_card[JSON_KEY_ENTER_AREA_TIME] = t;
			pos_cards.append(pos_card[JSON_KEY_ENTER_AREA_TIME]);

			//最后接收时间戳
			t = *((int64_t*)&it->second->rec_time)*ms;
			pos_card[JSON_KEY_REC_TIME] = t;
			pos_cards.append(pos_card[JSON_KEY_REC_TIME]);

			//工作时长
			t = (int)difftime(time(NULL), it->second->down_time)*ms;
			pos_card[JSON_KEY_WORK_TIME] = t;
			pos_cards.append(pos_card[JSON_KEY_WORK_TIME]);

			//地图编号
			pos_card[JSON_KEY_MAP_ID] = it->second->map_id;
			pos_cards.append(pos_card[JSON_KEY_MAP_ID]);

			//区域编号
			pos_card[JSON_KEY_AREA_ID] = it->second->area_id;
			pos_cards.append(pos_card[JSON_KEY_AREA_ID]);

			//部门编号
			pos_card[JSON_KEY_DEPT_ID] = it->second->dept_id;
			pos_cards.append(pos_card[JSON_KEY_DEPT_ID]);

			//状态
			it->second->get_state_text();
			pos_card[JSON_KEY_STATE] = (it->second->state == 0) ? 0 : 1; 
			pos_cards.append(pos_card[JSON_KEY_STATE]);

			//运行状态
			it->second->get_acc_text();
			pos_card[JSON_KEY_STATE_MOVING] = it->second->state_moving;
			pos_cards.append(pos_card[JSON_KEY_STATE_MOVING]);

			//业务状态
			pos_card[JSON_KEY_STATE_BIZ] = it->second->StateBiz();
			pos_cards.append(pos_card[JSON_KEY_STATE_BIZ]);

			//速度
			pos_card[JSON_KEY_SPEED] =  CFunctions::round(it->second->get_speed(),0);
			pos_cards.append(pos_card[JSON_KEY_SPEED]);

			pos_card[JSON_KEY_LANDMARK_ID] = it->second->landmark_id;
			pos_cards.append(pos_card[JSON_KEY_LANDMARK_ID]);

			//directory ID
			pos_card[JSON_KEY_DIRECTORY_ID] = it->second->landmark_direction;
			pos_cards.append(pos_card[JSON_KEY_DIRECTORY_ID]);

			pos_card[JSON_KEY_LANDMARK_DIS] = it->second->landmark_dis;
			pos_cards.append(pos_card[JSON_KEY_LANDMARK_DIS]);

			if(!pos_cards.isNull()){
				root[JSON_ROOT_KEY_DATA].append(pos_cards);
				cnt++;
			}
		}
	}

	std::string ret = "";
	if(cnt > 0){
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_POS_MAP;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION_1_3;
		ret = root.toFastString().c_str();
	}

	return ret;
}

std::string CYAServerDlg::get_json_position(std::shared_ptr<Card> pCard)
{
	if (pCard == nullptr)
	{
		return "";
	}

	Json::Value root;		//root
	Json::Value data;		//data
	Json::Value vehicle;	//车卡的detail
	Json::Value detail;

	//detail部分
	//detail.append(pCard->card_id.c_str());
	//double x = 0.0,y = 0.0;
	//x = pCard->last_cell->getX();
	//y = pCard->last_cell->getY();

	//detail.append(x);
	//detail.append(y);

	//int ms = 1000;

	////入井时间戳
	//double t = *((int64_t*)&pCard->down_time)*ms;
	//detail.append(t);

	////进入区域时间戳
	//time_t tt = CFunctions::systime_to_timet(card->enter_area_time);
	//t = *((int64_t*)&tt)*ms;
	//detail.append(t);

	////最后接收时间戳
	//t = *((int64_t*)&card->rec_time)*ms;
	//detail.append(t);

	////工作时长
	//t = (int)difftime(time(NULL), card->down_time)*ms;
	//detail.append(t);

	////地图编号
	//detail.append(card->map_id);

	////区域编号
	//detail.append(card->area_id);

	////部门编号
	//detail.append(card->dept_id);

	////状态
	//card->get_state_text();
	//int state = (card->state == 0) ? 0 : 1; 
	//detail.append(state);

	////运行状态
	//card->get_acc_text();
	//detail.append(card->state_moving);

	////业务状态
	//detail.append(card->state_biz);

	////速度
	//detail.append(CFunctions::round(card->get_speed(),2));

	////landmark ID
	//detail.append(card->landmark_id);

	////directory ID
	//detail.append(card->landmark_direction);

	////distance
	//detail.append(card->landmark_dis);

	get_json_node_position(pCard, detail);

	if(detail.size() > 0){
		vehicle.append(detail);
		data[JSON_ROOT_KEY_STATISTIC_DETAIL]= vehicle;
	}

	std::string strRet = "";
	if (data.size() > 0)
	{
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_POS_MAP;
		root[JSON_ROOT_KEY_DATA] = data;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION_1_4; 

		strRet = root.toFastString();
	}

	return strRet;
}

std::string CYAServerDlg::get_json_card_position(std::shared_ptr<Card> card)
{
	Json::Value root;

	int cnt = 0;

	Json::Value pos_cards;
	Json::Value pos_card;

	card->isdealed = false;
	card->issent = true;
	card->isoutput = false;

	//卡号
	pos_cards.append(card->card_id);

	if (fabs(card->x) < 1E-4 && fabs(card->y) < 1E-4)
	{
		pos_card[JSON_KEY_CORDINATE_X] = CFunctions::round(card->last_locate.x, 2);
		pos_cards.append(pos_card[JSON_KEY_CORDINATE_X]);
		pos_card[JSON_KEY_CORDINATE_Y] = CFunctions::round(card->last_locate.y, 2);
		pos_cards.append(pos_card[JSON_KEY_CORDINATE_Y]);
	}else{
		pos_card[JSON_KEY_CORDINATE_X] = CFunctions::round(card->x, 2);
		pos_cards.append(pos_card[JSON_KEY_CORDINATE_X]);
		pos_card[JSON_KEY_CORDINATE_Y] = CFunctions::round(card->y, 2);
		pos_cards.append(pos_card[JSON_KEY_CORDINATE_Y]);
	}

	int ms = 1000; //转为ms
	//入井时间戳
	double t = *((int64_t*)&card->down_time)*ms;
	pos_card[JSON_KEY_DOWN_TIME] = t;
	pos_cards.append(pos_card[JSON_KEY_DOWN_TIME]);

	//进入区域时间戳
	time_t tt = CFunctions::systime_to_timet(card->enter_area_time);
	t = *((int64_t*)&tt)*ms;
	pos_card[JSON_KEY_ENTER_AREA_TIME] = t;
	pos_cards.append(pos_card[JSON_KEY_ENTER_AREA_TIME]);

	//最后接收时间戳
	t = *((int64_t*)&card->rec_time)*ms;
	pos_card[JSON_KEY_REC_TIME] = t;
	pos_cards.append(pos_card[JSON_KEY_REC_TIME]);

	//工作时长
	t = (int)difftime(time(NULL), card->down_time)*ms;
	pos_card[JSON_KEY_WORK_TIME] = t;
	pos_cards.append(pos_card[JSON_KEY_WORK_TIME]);

	//地图编号
	pos_card[JSON_KEY_MAP_ID] = card->map_id;
	pos_cards.append(pos_card[JSON_KEY_MAP_ID]);

	//区域编号
	pos_card[JSON_KEY_AREA_ID] = card->area_id;
	pos_cards.append(pos_card[JSON_KEY_AREA_ID]);

	//部门编号
	pos_card[JSON_KEY_DEPT_ID] = card->dept_id;
	pos_cards.append(pos_card[JSON_KEY_DEPT_ID]);

	//状态
	card->get_state_text();
	pos_card[JSON_KEY_STATE] = (card->state == 0) ? 0 : 1; 
	pos_cards.append(pos_card[JSON_KEY_STATE]);

	//运行状态
	card->get_acc_text();
	pos_card[JSON_KEY_STATE_MOVING] = card->state_moving;
	pos_cards.append(pos_card[JSON_KEY_STATE_MOVING]);

	//业务状态
	pos_card[JSON_KEY_STATE_BIZ] = card->StateBiz();
	pos_cards.append(pos_card[JSON_KEY_STATE_BIZ]);

	//速度
	pos_card[JSON_KEY_SPEED] = CFunctions::round(card->get_speed(),0);
	pos_cards.append(pos_card[JSON_KEY_SPEED]);

	//landmark ID
	pos_card[JSON_KEY_LANDMARK_ID] = card->landmark_id;
	pos_cards.append(pos_card[JSON_KEY_LANDMARK_ID]);

	//directory ID
	pos_card[JSON_KEY_DIRECTORY_ID] = card->landmark_direction;
	pos_cards.append(pos_card[JSON_KEY_DIRECTORY_ID]);
	//distance
	pos_card[JSON_KEY_LANDMARK_DIS] = card->landmark_dis;
	pos_cards.append(pos_card[JSON_KEY_LANDMARK_DIS]);

	if(!pos_cards.isNull()){
		root[JSON_ROOT_KEY_DATA].append(pos_cards);
		cnt++;
	}

	std::string ret = "";
	if(cnt > 0){
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_POS_MAP;	//问题1
		ret = root.toFastString().c_str();
	}

	return ret;
}

time_t CYAServerDlg::GetCurShiftStartTime(int& shift_id)
{
	time_t t = time(NULL);
	struct tm* current_time = localtime(&t);

	char ch[64];
	strftime(ch, sizeof(ch), "%H-%M-00", current_time);
	std::string curtime = ch;

	BanShiftMap::iterator it_shift = mp_banshift_list.begin();
	for(; it_shift != mp_banshift_list.end(); ++it_shift)
	{
		if(it_shift->second->end_time < it_shift->second->start_time)
		{
			if(curtime >= it_shift->second->start_time || curtime < it_shift->second->end_time)
			{
				shift_id = it_shift->first;
				break;
			}
		}
		else
		{
			if(curtime >= it_shift->second->start_time && curtime < it_shift->second->end_time)
			{
				shift_id = it_shift->first;
				break;
			}
		}
	}

	switch (shift_id)
	{
	case 1:
		current_time->tm_hour = 0;
		break;
	case 2:
		current_time->tm_hour = 8;
		break;
	case 3:
		current_time->tm_hour = 16;
	default:
		break;
	}

	current_time->tm_min = 0;
	current_time->tm_sec = 0;
	t = mktime(current_time);
	current_time = localtime(&t);

	return t;
}

time_t CYAServerDlg::GetLastShiftStartTime(int& shift_id)
{
	time_t t = time(NULL);
	struct tm* current_time = localtime(&t);
	if((current_time->tm_hour >= 0) && (current_time->tm_hour < 8))
	{
		current_time->tm_hour = 16;
		current_time->tm_mday  = current_time->tm_mday - 1;
		shift_id = 3;
	}
	else if((current_time->tm_hour >= 8) && (current_time->tm_hour < 16))
	{
		current_time->tm_hour = 0;
		shift_id = 1;
	}
	else
	{
		current_time->tm_hour = 8;
		shift_id = 2;
	}
	current_time->tm_min = 0;
	current_time->tm_sec = 0;
	t = mktime(current_time);
	current_time = localtime(&t);
	return t;
}


time_t CYAServerDlg::GetCurShiftEndTime()
{
	time_t t = time(NULL);
	struct tm* current_time = localtime(&t);
	if((current_time->tm_hour >= 0) && (current_time->tm_hour < 8))
	{
		current_time->tm_hour = 8;
	}
	else if((current_time->tm_hour >= 8) && (current_time->tm_hour < 16))
	{
		current_time->tm_hour = 16;
	}
	else
	{
		current_time->tm_hour = 0;
		current_time->tm_mday = current_time->tm_mday + 1;
	}
	current_time->tm_min = 0;
	current_time->tm_sec = 0;
	t = mktime(current_time);
	current_time = localtime(&t);
	return t;
}

std::string CYAServerDlg::get_json_drivingface_card_position(std::shared_ptr<Card> card)
{
	Json::Value root;

	int cnt = 0;
	double cur_shift_work_time_length = 0.0;

	Json::Value pos_cards;
	Json::Value pos_card;

	card->isdealed = false;
	card->issent = true;
	card->isoutput = false;

    float last_total_finsh_length = 0;
	float cur_total_finish_length = 0;
	float diff_length_flag = 0;
	float cur_shift_finish_length = 0;
	std::shared_ptr<DrivingfaceRender> pDrivingfaceRender = nullptr;
	//DrivingfaceRenderMap::iterator it = mp_driving_face_render_list.find(card->reader_id);
	DrivingfaceRenderMap::iterator it = mp_driving_face_render_list.find(501);
	if(it == mp_driving_face_render_list.end()){
		return "";
	}
	else
	{
		pDrivingfaceRender = it->second;
		
        last_total_finsh_length = sqrt(pow(card->driving_face_cur_shift_x - pDrivingfaceRender->x, 2)
			+ pow(card->driving_face_cur_shift_y - pDrivingfaceRender->y, 2)
			+ pow(card->driving_face_cur_shift_z - pDrivingfaceRender->z, 2)) * card->map_scale;
		
		cur_total_finish_length = sqrt(pow(card->x - pDrivingfaceRender->x, 2)
			+ pow(card->y - pDrivingfaceRender->y, 2)
			+ pow(card->z - pDrivingfaceRender->z, 2)) * card->map_scale;

		cur_shift_finish_length = sqrt(pow(card->x - card->driving_face_cur_shift_start_x, 2)
			+ pow(card->y - card->driving_face_cur_shift_start_y, 2)
			+ pow(card->z - card->driving_face_cur_shift_start_z, 2)) * card->map_scale;
		debug_print_syslog(0, "current_shift_start_x: %3f, current_shift_start_y: %3f, current_shift_start_z: %3f.", 
			card->driving_face_cur_shift_start_x, 
			card->driving_face_cur_shift_start_y,
			card->driving_face_cur_shift_start_z);
		debug_print_syslog(0, "current_shift_x: %3f, current_shift_y: %3f, current_shift_z: %3f.", 
			card->driving_face_cur_shift_x, 
			card->driving_face_cur_shift_y,
			card->driving_face_cur_shift_z);
		debug_print_syslog(0, "card_x: %3f, card_y: %3f, card_z: %3f.", 
			card->x, 
			card->y,
			card->z);
		diff_length_flag = (cur_total_finish_length - last_total_finsh_length) * card->map_scale;
		if(diff_length_flag >= 0)
		{
			card->driving_face_cur_shift_x = card->x;
			card->driving_face_cur_shift_y = card->y;
			card->driving_face_cur_shift_z = card->z;
		}
		else
		{
		    cur_total_finish_length = last_total_finsh_length;
		    cur_shift_finish_length = sqrt(pow(card->driving_face_cur_shift_x - card->driving_face_cur_shift_start_x, 2)
			+ pow(card->driving_face_cur_shift_y - card->driving_face_cur_shift_start_y, 2)
			+ pow(card->driving_face_cur_shift_z - card->driving_face_cur_shift_start_z, 2)) * card->map_scale;
		}
	}

	//卡号
	pos_cards.append(card->card_id);

	//x,y坐标
	pos_card[JSON_KEY_CORDINATE_X] = CFunctions::round(card->driving_face_cur_shift_start_x, 2);
	pos_cards.append(pos_card[JSON_KEY_CORDINATE_X]);
	pos_card[JSON_KEY_CORDINATE_Y] = CFunctions::round(card->driving_face_cur_shift_start_y, 2);
	pos_cards.append(pos_card[JSON_KEY_CORDINATE_Y]);

	int ms = 1000; //转为ms
	//入井时间戳
	int shift_id = 0;
	time_t start_time_t = GetCurShiftStartTime(shift_id);
	double t = *((int64_t*)&start_time_t)*ms;
	pos_card[JSON_KEY_DOWN_TIME] = t;
	pos_cards.append(pos_card[JSON_KEY_DOWN_TIME]);

	//最后接收时间戳
	t = *((int64_t*)&card->rec_time)*ms;
	pos_card[JSON_KEY_REC_TIME] = t;
	pos_cards.append(pos_card[JSON_KEY_REC_TIME]);

	//工作时长
	t = (int)(difftime(time(NULL), start_time_t))*ms;
	cur_shift_work_time_length = CFunctions::round(t / 1000 / 3600.0, 1);
	pos_card[JSON_KEY_WORK_TIME] = cur_shift_work_time_length;
	pos_cards.append(pos_card[JSON_KEY_WORK_TIME]);

	//地图编号
	pos_card[JSON_KEY_MAP_ID] = card->map_id;
	pos_cards.append(pos_card[JSON_KEY_MAP_ID]);

	//区域编号
	pos_card[JSON_KEY_AREA_ID] = card->area_id;
	pos_cards.append(pos_card[JSON_KEY_AREA_ID]);

	//部门编号
	pos_card[JSON_KEY_DEPT_ID] = card->dept_id;
	pos_cards.append(pos_card[JSON_KEY_DEPT_ID]);

	//状态
	card->get_state_text();
	pos_card[JSON_KEY_STATE] = (card->is_driving_face_start == 0) ? 0 : 3; 
	pos_cards.append(pos_card[JSON_KEY_STATE]);


	//工作时长
	t = (int)difftime(time(NULL), card->down_time)*ms;
	pos_card[JSON_KEY_WORK_TIME] = t;
	pos_cards.append(pos_card[JSON_KEY_WORK_TIME]);

	//运行状态
	card->get_acc_text();
	pos_card[JSON_KEY_STATE_MOVING] = (card->is_driving_face_start == 0) ? 0 : 3;
	pos_cards.append(pos_card[JSON_KEY_STATE_MOVING]);

	//业务状态
	pos_card[JSON_KEY_STATE_BIZ] = card->StateBiz();
	pos_cards.append(pos_card[JSON_KEY_STATE_BIZ]);
	
	//速度
	double average_speed = 0;
	if(cur_shift_work_time_length != 0)
	{
	    average_speed = cur_shift_finish_length / cur_shift_work_time_length;
	}
	if(average_speed > card->drving_face_cur_shift_max_speed)
	{
	    card->drving_face_cur_shift_max_speed = average_speed;
	}

	//平均速度
	pos_card[JSON_KEY_SPEED] = CFunctions::round(average_speed, 2);
	pos_cards.append(pos_card[JSON_KEY_SPEED]);

    //最大速度
	debug_print_syslog(0, "average time: %3f, cur_finish_length: %3f, ", cur_shift_work_time_length, cur_shift_finish_length);
	pos_card[JSON_KEY_SPEED] = CFunctions::round(card->drving_face_cur_shift_max_speed, 2);
	pos_cards.append(pos_card[JSON_KEY_SPEED]);

	//掘进距离
	pos_card[JSON_KEY_DRIVINGFACE_DIS] = CFunctions::round(cur_shift_finish_length, 2);
	pos_cards.append(pos_card[JSON_KEY_DRIVINGFACE_DIS]);

	//掘进面警戒点ID
	pos_card[JSON_KEY_DRIVINGFACE_WARNING_POINT_ID] = 1;
	pos_cards.append(pos_card[JSON_KEY_DRIVINGFACE_WARNING_POINT_ID]);

	//掘进面警戒点距离
	pos_card[JSON_KEY_DRIVINGFACE_WARNING_POINT_DIS] = CFunctions::round(get_drivingface_warning_point_dis(card), 2);
	pos_cards.append(pos_card[JSON_KEY_DRIVINGFACE_WARNING_POINT_DIS]);

	if(!pos_cards.isNull()){
		root[JSON_ROOT_KEY_DATA].append(pos_cards);
		cnt++;
	}

	std::string ret = "";
	if(cnt > 0){
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_DRIVING_FACE_STATE;	
		ret = root.toFastString().c_str();
	}
    debug_print_syslog(0, "send drivingface stat: %s", ret.c_str());
	return ret;
}

std::string CYAServerDlg::get_json_position_all()
{
	return get_json_card_statistic();

	Json::Value root;
	int cnt = 0;
	MapInfoMap::iterator it_map = mp_map_list.begin();
	for(; it_map != mp_map_list.end(); ++it_map){		
		CardMap::iterator it = mp_card_list_all.begin();
		for(; it != mp_card_list_all.end(); ++it){
			if(it->second->map_id != it_map->second->map_id){
				continue;
			}
			if(_isnan(it->second->x) || _isnan(it->second->y) || _isnan(it->second->get_speed())){
				continue;
			}
			it->second->issent = true;

			Json::Value pos_cards;
			Json::Value pos_card;

			//卡号
			pos_card[JSON_KEY_CARD_ID] = it->second->card_id;
			pos_cards.append(pos_card[JSON_KEY_CARD_ID]);

			//坐标为零的数据不推送
			if (fabs(it->second->x) < 1E-4 && fabs(it->second->y) < 1E-4)
			{
				continue;
			}
			pos_card[JSON_KEY_CORDINATE_X] = CFunctions::round(it->second->x, 2);
			pos_cards.append(pos_card[JSON_KEY_CORDINATE_X]);
			pos_card[JSON_KEY_CORDINATE_Y] = CFunctions::round(it->second->y, 2);
			pos_cards.append(pos_card[JSON_KEY_CORDINATE_Y]);

			//x,y坐标
			/*switch(it->second->m_nOutputPosState){
			case 0:
			pos_card[JSON_KEY_CORDINATE_X] = CFunctions::round(it->second->x, 2);
			pos_cards.append(pos_card[JSON_KEY_CORDINATE_X]);
			pos_card[JSON_KEY_CORDINATE_Y] = CFunctions::round(it->second->y, 2);
			pos_cards.append(pos_card[JSON_KEY_CORDINATE_Y]);
			break;
			case 1:
			pos_card[JSON_KEY_CORDINATE_X] = CFunctions::round(it->second->left_x, 2);
			pos_cards.append(pos_card[JSON_KEY_CORDINATE_X]);
			pos_card[JSON_KEY_CORDINATE_Y] = CFunctions::round(it->second->left_y, 2);
			pos_cards.append(pos_card[JSON_KEY_CORDINATE_Y]);
			break;
			case 2:
			pos_card[JSON_KEY_CORDINATE_X] = CFunctions::round(it->second->right_x, 2);
			pos_cards.append(pos_card[JSON_KEY_CORDINATE_X]);
			pos_card[JSON_KEY_CORDINATE_Y] = CFunctions::round(it->second->right_y, 2);
			pos_cards.append(pos_card[JSON_KEY_CORDINATE_Y]);
			break;
			default:
			break;
			}*/

			int ms = 1000;  //转为ms
			//入井时间戳
			double t = *((int64_t*)&it->second->down_time)*ms;
			pos_card[JSON_KEY_DOWN_TIME] = t;
			pos_cards.append(pos_card[JSON_KEY_DOWN_TIME]);

			//进入区域时间戳
			time_t eat = CFunctions::systime_to_timet(it->second->enter_area_time);
			t = *((int64_t*)&eat)*ms;
			pos_card[JSON_KEY_ENTER_AREA_TIME] = t;
			pos_cards.append(pos_card[JSON_KEY_ENTER_AREA_TIME]);

			//最后接收时间戳
			t = *((int64_t*)&it->second->rec_time)*ms;
			pos_card[JSON_KEY_REC_TIME] = t;
			pos_cards.append(pos_card[JSON_KEY_REC_TIME]);

			//工作时长
			t = (int)difftime(time(NULL), it->second->down_time)*ms;
			pos_card[JSON_KEY_WORK_TIME] = t;
			pos_cards.append(pos_card[JSON_KEY_WORK_TIME]);

			//地图编号
			pos_card[JSON_KEY_MAP_ID] = it->second->map_id;
			pos_cards.append(pos_card[JSON_KEY_MAP_ID]);

			//区域编号
			pos_card[JSON_KEY_AREA_ID] = it->second->area_id;
			pos_cards.append(pos_card[JSON_KEY_AREA_ID]);

			//是否特殊区域,把非特殊区域的卡信息全组装好
			AreaMap::iterator it_area_cur = mp_area_list.find(it->second->area_id);
			if(it_area_cur != mp_area_list.end())
			{
				if (it_area_cur->second->is_special())
				{
					pos_cards.append(it->second->area_id);
				}else{
					continue;
				}		
			}
			else
			{
				continue;
			}

			//部门编号
			pos_card[JSON_KEY_DEPT_ID] = it->second->dept_id;
			pos_cards.append(pos_card[JSON_KEY_DEPT_ID]);

			it->second->get_state_text();

			//状态
			pos_card[JSON_KEY_STATE] = it->second->state; 
			pos_cards.append(pos_card[JSON_KEY_STATE]);

			//运行状态
			it->second->get_acc_text();
			pos_card[JSON_KEY_STATE_MOVING] = it->second->state_moving;
			pos_cards.append(pos_card[JSON_KEY_STATE_MOVING]);

			//业务状态
			pos_card[JSON_KEY_STATE_BIZ] = it->second->StateBiz();
			pos_cards.append(pos_card[JSON_KEY_STATE_BIZ]);

			//速度
			pos_card[JSON_KEY_SPEED] = CFunctions::round(it->second->get_speed(),0);
			pos_cards.append(pos_card[JSON_KEY_SPEED]);

			//landmark ID
			pos_card[JSON_KEY_LANDMARK_ID] = it->second->landmark_id;
			pos_cards.append(pos_card[JSON_KEY_LANDMARK_ID]);

			//directory ID
			pos_card[JSON_KEY_DIRECTORY_ID] = it->second->landmark_direction;
			pos_cards.append(pos_card[JSON_KEY_DIRECTORY_ID]);
			//distance
			pos_card[JSON_KEY_LANDMARK_DIS] = it->second->landmark_dis;
			pos_cards.append(pos_card[JSON_KEY_LANDMARK_DIS]);

			if(!pos_cards.isNull()){
				root[JSON_ROOT_KEY_DATA].append(pos_cards);
				cnt++;
			}
		}
	}

	std::string ret = "";
	if(cnt > 0){
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_POS_MAP;	//问题2
		//ret = root.toFastString().c_str();
		ret = root.toFastString();
	}
	return ret;
}

int CYAServerDlg::insert_data(int index, int key, StatisticDataStr** header)
{
	StatisticDataStr* tmpPtr = *header;
	StatisticDataStr* second = *header;
	if(NULL == tmpPtr)
	{
		KeyValuePair* keyValuePtr = new KeyValuePair;
		keyValuePtr->key = key;
		keyValuePtr->value = 1;
		keyValuePtr->next = NULL;
		StatisticDataStr* deptStatisticData = new StatisticDataStr;
		deptStatisticData->index = index;
		deptStatisticData->data_info = keyValuePtr;
		deptStatisticData->next = NULL;
		tmpPtr = deptStatisticData;
		*header = tmpPtr;
		return 0;
	}
	while(tmpPtr != NULL)
	{
		if(tmpPtr->index == index)
		{
			break;
		}
		second = tmpPtr;
		tmpPtr = tmpPtr->next;
	}
	if(NULL == tmpPtr)
	{
		KeyValuePair* keyValuePtr = new KeyValuePair;
		keyValuePtr->key = key;
		keyValuePtr->value = 1;
		keyValuePtr->next = NULL;
		StatisticDataStr* deptStatisticData = new StatisticDataStr;
		deptStatisticData->index = index;
		deptStatisticData->data_info = keyValuePtr;
		deptStatisticData->next = NULL;
		if(NULL != second)
		{
			second->next = deptStatisticData;
		}
		else
		{
			tmpPtr = deptStatisticData;
		}
	}
	else
	{
		KeyValuePair* keyValuePtr = tmpPtr->data_info;
		KeyValuePair* keyValuePtrSecond = tmpPtr->data_info;
		while(keyValuePtr != NULL )
		{
			if(keyValuePtr->key == key)
			{
				break;
			}
			keyValuePtrSecond = keyValuePtr;
			keyValuePtr = keyValuePtr->next;
		}
		if(NULL == keyValuePtr)
		{
			KeyValuePair* keyValueData = new KeyValuePair;
			keyValueData->key = key;
			keyValueData->value = 1;
			keyValueData->next = NULL;
			keyValuePtrSecond->next = keyValueData;
		}
		else
		{
			keyValuePtr->value = keyValuePtr->value + 1;
		}
	}
	return 0;
}

void CYAServerDlg::delete_memory(StatisticDataStr *header)
{
	if(NULL == header)
	{
		return;
	}

	while(NULL != header)
	{
		KeyValuePair* tmpKeyValuePtr = header->data_info;
		while(NULL != tmpKeyValuePtr)
		{
			KeyValuePair* tmpKPtr = tmpKeyValuePtr;
			tmpKeyValuePtr = tmpKeyValuePtr->next;
			delete tmpKPtr;
		}
		StatisticDataStr* tmpStatisticDataStrPtr = header;
		header=header->next;
		delete tmpStatisticDataStrPtr;
	}
	return;
}

Json::Value CYAServerDlg::get_json_statistic_data( StatisticDataStr* header )
{
	Json::Value data;
	while(NULL != header)
	{
		KeyValuePair* tmpKeyValuePtr = header->data_info;
		while(NULL != tmpKeyValuePtr)
		{
			KeyValuePair* tmpKPtr = tmpKeyValuePtr;
			tmpKeyValuePtr = tmpKeyValuePtr->next;
			Json::Value ttemp;

			ttemp.append(tmpKPtr->key);
			ttemp.append(tmpKPtr->value);
			data.append(ttemp);
		}
		header=header->next;
	}
	return data; 
}


int CYAServerDlg::get_json_node_position( std::shared_ptr<Card> card, Json::Value &detailNode )
{
	// 卡号
	detailNode.append(card->card_id); // 0
	//需要考虑 坐标为零的数据
	detailNode.append( CFunctions::round(card->x, 2)); // 1
	detailNode.append( CFunctions::round(card->y, 2)); // 2
	int ms = 1000;  //转为ms
	//入井时间戳
	double t = *((int64_t*)&card->down_time)*ms;
	detailNode.append(t); // 3
	//进入区域时间戳
	time_t eat = CFunctions::systime_to_timet(card->enter_area_time);
	t = *((int64_t*)&eat)*ms;
	detailNode.append(t); // 4
	//最后接收时间戳
	t = *((int64_t*)&card->rec_time)*ms;
	detailNode.append(t); // 5
	//工作时长
	t = (int)difftime(time(NULL), card->down_time)*ms;
	detailNode.append(t); // 6
	//地图编号
	detailNode.append(card->map_id); // 7
	//区域编号,含特殊区域
	detailNode.append(card->area_id); // 8
	//部门编号
	detailNode.append(card->dept_id); // 9
	//状态
	card->get_state_text();
	detailNode.append(card->state); // 10
	//运行状态
	card->get_acc_text();
	detailNode.append(card->state_moving); // 11
	//业务状态
	detailNode.append(card->StateBiz()); // 12
	//速度
	detailNode.append(CFunctions::round(card->get_speed(), 0)); // 13
	//地标编号
	detailNode.append(card->landmark_id); // 14
	//地标方向
	detailNode.append(card->landmark_direction); // 15
	//距离地标的距离
	detailNode.append(CFunctions::round(card->landmark_dis, 0)); // 16
	// 级别编号
	detailNode.append(card->occlevel_id); //17
	// 升入井状态，测试用
	//detailNode.append(card->pos_state); // 18

	return 0;
}

Json::Value CYAServerDlg::get_json_statistic_vehicle_data(Json::Value& vehicle_data)
{
	Json::Value stat;
	Json::Value detail;

	Json::Value glbl;
	Json::Value depts;

	Json::Value global_area;
	Json::Value global_dept;

	Json::Value testArea;
	Json::Value testAll;

	int dept_sum = 0;
	int all_verhicle_num = 0;

	StatisticDataStr* areaStatisticHeader = NULL;

	for(DeptMap::iterator it_dept = mp_dept_list.begin(); it_dept != mp_dept_list.end(); ++it_dept)
	{
		dept_sum = it_dept->second->dept_card_list_vehicle.size();
		if(dept_sum > 0)
		{
			Json::Value per_dept;
			Json::Value dept_areas;

			StatisticDataStr* deptStatisticHeader = NULL;
						
			CardMap dept_card_map = it_dept->second->dept_card_list_vehicle;
			for(CardMap::iterator it_card = dept_card_map.begin(); it_card != dept_card_map.end(); ++it_card)
			{
				// 非法坐标不推
				if (_isnan(it_card->second->x) || _isnan(it_card->second->y) || _isnan(it_card->second->get_speed()))
				{
					dept_sum--;
					continue;
				}
				if (fabs(it_card->second->x) < 1E-4 && fabs(it_card->second->y) < 1E-4)
				{
					dept_sum--;
					continue;
				}
				if(INVALID_COORDINATE == it_card->second->x || INVALID_COORDINATE == it_card->second->y)
				{
					dept_sum--;
					continue;
				}
				// 组装每个部门的区域统计
				insert_data(it_card->second->dept_id, it_card->second->area_id, &deptStatisticHeader);
				insert_data(0, it_card->second->area_id, &areaStatisticHeader);

				all_verhicle_num++;
				// 获取明细
				Json::Value vehicle;
				get_json_node_position(it_card->second, vehicle);
				if(!vehicle.isNull()){
					detail.append(vehicle);
				}
				
			}
			
			if(dept_sum > 0)
			{
				Json::Value single_dept;
				single_dept.append(it_dept->first);
				single_dept.append(dept_sum);
				global_dept.append(single_dept);

				dept_areas = get_json_statistic_data(deptStatisticHeader);
				if(!dept_areas.isNull()){
					per_dept[JSON_ROOT_KEY_STATISTIC_SUM] = dept_sum;
					per_dept[JSON_ROOT_KEY_STATISTIC_AREA] = dept_areas;
					per_dept[JSON_ROOT_KEY_STATISTIC_DEPT].append(single_dept);
					char dept_id[20];
					sprintf_s(dept_id, "%d", it_dept->first);
					depts[dept_id] = per_dept;
				}
			}
		}
	}

	global_area = get_json_statistic_data(areaStatisticHeader);

	glbl[JSON_ROOT_KEY_STATISTIC_SUM] = all_verhicle_num;
	if(!global_area.isNull()){
		glbl[JSON_ROOT_KEY_STATISTIC_AREA] = global_area;
	}
	if(!global_dept.isNull()){
		glbl[JSON_ROOT_KEY_STATISTIC_DEPT] = global_dept;
	}
	if(!glbl.isNull()){
		stat[JSON_ROOT_KEY_STATISTIC_GLOBAL] = glbl;
	}
	if(!depts.isNull()){
		stat[JSON_ROOT_KEY_STATISTIC_DEPT] = depts;
	}
	if(!stat.isNull()){
		vehicle_data[JSON_ROOT_KEY_STATISTIC_STAT] = stat;
	}
	if(!detail.isNull()){
		vehicle_data[JSON_ROOT_KEY_STATISTIC_DETAIL] = detail;
	}

	return vehicle_data;
}

Json::Value CYAServerDlg::get_json_statistic_staff_data(Json::Value& staff_data)
{
	Json::Value stat;
	Json::Value detail;

	Json::Value glbl;
	Json::Value depts;

	Json::Value global_area;
	Json::Value global_dept;
	Json::Value global_level;

	int all_staff_num = 0;
	int dept_sum = 0;

	StatisticDataStr* areaStatisticHeader = NULL;
	StatisticDataStr* lvlStatisticHeader = NULL;
		
	for(DeptMap::iterator it_dept = mp_dept_list.begin(); it_dept != mp_dept_list.end(); ++it_dept)
	{
		dept_sum = it_dept->second->dept_card_list_person.size();
		if(dept_sum > 0)
		{
			Json::Value per_dept;
			Json::Value dept_areas;
			Json::Value dept_levels;

			StatisticDataStr* deptStatisticHeader = NULL;
			StatisticDataStr* occLevelStatisticHeader = NULL;

			CardMap dept_card_map = it_dept->second->dept_card_list_person;
			for(CardMap::iterator it_card = dept_card_map.begin(); it_card != dept_card_map.end(); ++it_card)
			{
				if (_isnan(it_card->second->x) || _isnan(it_card->second->y) || _isnan(it_card->second->get_speed()))
				{
					dept_sum--;
					continue;
				}
				if (fabs(it_card->second->x) < 1E-4 && fabs(it_card->second->y) < 1E-4)
				{
					dept_sum--;
					continue;
				}
				if(INVALID_COORDINATE == it_card->second->x || INVALID_COORDINATE == it_card->second->y)
				{
					dept_sum--;
					continue;
				}
				// 组装每个部门的区域统计
				insert_data(it_card->second->dept_id, it_card->second->area_id, &deptStatisticHeader);
				insert_data(it_card->second->dept_id, it_card->second->occlevel_id, &occLevelStatisticHeader);
				insert_data(0, it_card->second->area_id, &areaStatisticHeader);
				insert_data(0, it_card->second->occlevel_id, &lvlStatisticHeader);

				all_staff_num++;
				// 获取明细
				Json::Value detailNode;
				get_json_node_position(it_card->second, detailNode);
				if(!detailNode.isNull()){
					detail.append(detailNode);
				}
			}
			if(dept_sum>0){
				dept_areas = get_json_statistic_data(deptStatisticHeader);
				dept_levels = get_json_statistic_data(occLevelStatisticHeader);
			
				Json::Value single_dept;
				single_dept.append(it_dept->first);
				single_dept.append(dept_sum);
				global_dept.append(single_dept);

				per_dept[JSON_ROOT_KEY_STATISTIC_SUM] = dept_sum;
				if(!dept_areas.isNull()){
					per_dept[JSON_ROOT_KEY_STATISTIC_AREA] = dept_areas;
				}
				if(!dept_levels.isNull()){
					per_dept[JSON_ROOT_KEY_STATISTIC_LEVEL] = dept_levels;
				}
				if(!single_dept.isNull()){
					per_dept[JSON_ROOT_KEY_STATISTIC_DEPT].append(single_dept);
					char dept_id[20];
					sprintf_s(dept_id, "%d", it_dept->first);
					depts[dept_id] = per_dept;
				}
			}
		}
	}

	global_area = get_json_statistic_data(areaStatisticHeader);
	global_level = get_json_statistic_data(lvlStatisticHeader);

	glbl[JSON_ROOT_KEY_STATISTIC_SUM] = all_staff_num;
	if(!global_area.isNull()){
		glbl[JSON_ROOT_KEY_STATISTIC_AREA] = global_area;
	}
	if(!global_dept.isNull()){
		glbl[JSON_ROOT_KEY_STATISTIC_DEPT] = global_dept;
	}
	if(!global_level.isNull()){
		glbl[JSON_ROOT_KEY_STATISTIC_LEVEL] = global_level;
	}
	if(!glbl.isNull()){
		stat[JSON_ROOT_KEY_STATISTIC_GLOBAL] = glbl;
	}
	if(!depts.isNull()){
		stat[JSON_ROOT_KEY_STATISTIC_DEPT] = depts;
	}
	if(!stat.isNull()){
		staff_data[JSON_ROOT_KEY_STATISTIC_STAT] = stat;
	}
	if(!detail.isNull()){
		staff_data[JSON_ROOT_KEY_STATISTIC_DETAIL] = detail;
	}
	return staff_data;
}

std::string CYAServerDlg::get_json_card_statistic()
{
	Json::Value root;
	Json::Value data;
	Json::Value v;
	Json::Value s;

	get_json_statistic_vehicle_data(v);
	get_json_statistic_staff_data(s);
	if(!v.isNull()){
		data[JSON_ROOT_KEY_STATISTIC_VEHICLE_DATA] = v;
	}
	if(!s.isNull()){
		data[JSON_ROOT_KEY_STATISTIC_STAFF_DATA] = s;
	}

	std::string ret = "";
	if(!data.isNull()){
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_POS_MAP; // JSON_CMD_VALUE_STATISTIC;
		root[JSON_ROOT_KEY_DATA] = data;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION_1_4;
		ret = root.toFastString();
	}
	return ret;
}

void CYAServerDlg::ReportCardStatistic()
{
	return;
}


/*
* 此函数生成所有数据的json，含坐标位置，事件，呼叫，特殊区域升井等
* 
* param
*		无
*
* return 
*		生成的json字符串
*
*/
std::string CYAServerDlg::get_json_all_data()
{
	Json::Value root;
	Json::Value data;

	Json::Value pos_data;

	//用于测试生成数据
	//GenerateAllDataJsonTest();

	std::string meta_data = "";
	for (int i = 0;i < 4;i++)
	{
		meta_data = "";
		switch(i){
		case 0:
			meta_data = get_json_position_all();
			break;
		case 1:
			meta_data = get_json_event();
			break;
		case 2:
			meta_data = get_json_call_list();
			/*meta_data = "{\"cmd\":\"callcardlist\",\"data\":[ \
			[\"fjb\",\"0010000000001\",103,23431,0,0], \
			[\"fjb\",\"0010000000001\",105,23432,0,2], \
			[\"fjb\",\"0\",105,23433,0,2]]}";*/
			break;
		case 3:
			meta_data = get_json_all_special_area_data();
			break;
		}

		if (meta_data != "")
		{
			Json::Reader reader;
			Json::Value tmp;
			reader.parse(meta_data,tmp);
			data.append(tmp);
		}
	}

	std::string ret = "";
	if (data.size() > 0)
	{
		root[JSON_ROOT_KEY_CMD]		= JSON_CMD_VALUE_RESPONSE_ALL_DATA;
		root[JSON_ROOT_KEY_DATA]	= data;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		ret = root.toFastString();
	}

<<<<<<< HEAD
	if (m_log_send_package)
	{
		CString cstr_output = _T("");
		cstr_output = ret.c_str();
		if (cstr_output != _T(""))
		{
#ifdef ENABLE_MY_LOG
			Log::write_log(FILE_TYPE::JSON_S,ret,true);
#else
			writeErrorLog(_T("JSON_S"),cstr_output,false);
#endif
		}
	}

=======
>>>>>>> newprotocal
	return ret; 
}

std::string CYAServerDlg::get_json_login()
{
	Json::Value root;
	Json::Value data;
	data[JSON_KEY_USERNAME] = JSON_VALUE_USERNAME;
	data[JSON_KEY_PASSWORD] = JSON_VALUE_PASSWORD;
	root[JSON_ROOT_KEY_CMD] =  JSON_CMD_VALUE_LOGIN;
	root[JSON_ROOT_KEY_DATA] = data;
	return root.toFastString();
}

std::string CYAServerDlg::get_json_logout()
{
	Json::Value root;
	Json::Value data;
	//data[JSON_KEY_USERNAME] = JSON_VALUE_USERNAME;
	data["name"] = JSON_VALUE_USERNAME;
	root[JSON_ROOT_KEY_CMD] =  JSON_CMD_VALUE_LOGOUT;
	//root[JSON_ROOT_KEY_DATA] = data;
	root["user"] = data;
	return root.toFastString();
}

void CYAServerDlg::send_json_data(string cmd, string data, bool is_login /* = false*/)
{
	if(data.length() == 0) return;

	USES_CONVERSION;
	CC2UTF8 conv = (char*)data.c_str();
	string utf8_data = conv.c_str();
	CString strlog;
	if(is_login){
		if(is_websocket_ok){
			_io->socket()->emit(cmd, utf8_data);
			is_websocket_login = true;
			strlog.Format(_T("%s: %s"), _T(LOG_SEND_JSON_DATA), _T("登录数据"));
			show_log(strlog);
		}
	}else if(is_websocket_login){
		strlog.Format(_T("%s: %s"), _T(LOG_SEND_JSON_DATA), _T("常规数据"));
		_io->socket()->emit(cmd, utf8_data);
		if(m_log_send_package){
<<<<<<< HEAD
			//wchar_t* p_data = CFunctions::c2wc(data.c_str());
#ifdef ENABLE_MY_LOG
			//Log::write_log(FILE_TYPE::JSON_S,data,true);
#else
			wchar_t* p_data = CFunctions::c2wc(data.c_str());
			writeErrorLog(L"JSON_S", p_data,false);
			if(p_data){
				free(p_data);
				p_data = NULL;
			}
#endif		
			/*if(p_data){
				free(p_data);
				p_data = NULL;
			}*/
=======
			Log::write_log(FILE_TYPE::JSON_S, data, true);
>>>>>>> newprotocal
		}
	}
	debug_print_syslog(0, "Send json %s.", data.c_str());
}

// 处理分站状态
void CYAServerDlg::deal_readers()
{
	ReaderMap::iterator it = mp_reader_list.begin();
	for(; it != mp_reader_list.end(); ++ it){
		int ndiff = (int)difftime(time(NULL), it->second->rec_time);
		if(STATUS_DEVICE_ERROR == it->second->reader_state){ // 异常 
			if(ndiff < READER_TIMEOUT){ // 恢复正常
				INT64 ev_id = it->second->m_event_list[ET_READER_ERROR];
				if(ev_id > 0){
					EventMap::iterator it_ev = mp_event_list->find(ev_id);
					if(it_ev != mp_event_list->end()){
						it_ev->second->status = ES_END;
						it_ev->second->cur_time = time(NULL);
						it_ev->second->cur_value = ndiff;
						it_ev->second->is_sent = false;
						store_data_event(it_ev->second);
						add_event(it_ev->second);
					}					
				}
				it->second->m_event_list[ET_READER_ERROR] = 0;
				it->second->reader_state = STATUS_DEVICE_NORMAL;				
			}
		}else{
			if(ndiff >= READER_TIMEOUT){ //异常
				it->second->reader_state = STATUS_DEVICE_ERROR;
				it->second->lost_time = time(NULL);

				INT64 ev_id = CFunctions::GetMicroSecond();
				std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
				ev->status = ES_START;
				ev->ev_type = ET_READER_ERROR;
				ev->obj_type = OT_DEVICE_READER;
				ev->obj_id = CFunctions::int2string(it->second->reader_id);
				ev->cur_time = time(NULL);

				ev->map_id = it->second->map_id;
				ev->area_id = it->second->area_id;
				ev->x = it->second->reader_x;
				ev->y = it->second->reader_y;

				ev->limit_value = READER_TIMEOUT;
				ev->cur_value = ndiff;
				ev->is_sent = false;

				it->second->m_event_list[ET_READER_ERROR] = ev_id;
				store_data_event(ev);
				add_event(ev);
				Sleep(1);
			}
		}
	}
}

/*
* 处理区域内业务逻辑：包含区域人员超员，人员超时，车辆超员，车辆超时，车辆超速等
*
* param
*		无
*
* return
*		无
*
*/
void CYAServerDlg::deal_areas()
{
	// 区域人数，区域超员数，区域超时数
	int count_person, count_vehicle, count_total, count_over_time_person, count_over_time_vehicle;
	int over_time_vehicle, over_time_person, over_time;
	bool is_true = false;
	time_t current_time(time(NULL));

	AreaMap::iterator it_Area = mp_area_list.begin();

	for(; it_Area != mp_area_list.end(); ++it_Area){
		count_person = count_vehicle = count_total = count_over_time_vehicle = count_over_time_person = 0;
		over_time_person = it_Area->second->over_time_person;
		over_time_vehicle = it_Area->second->over_time_vehicle;

		over_time = over_time_person;
		// 遍历卡，计数
		CardMap::iterator it_card_person = it_Area->second->area_card_list_person->begin();
		for(; it_card_person != it_Area->second->area_card_list_person->end(); ++it_card_person){
			// 计数
			count_total++;
			count_person++;
			// 超时
			is_true = difftime(current_time, CFunctions::systime_to_timet(it_card_person->second->enter_area_time)) > over_time;
			if(is_true){
				if(!it_card_person->second->is_area_over_time){
					it_card_person->second->is_area_over_time = true;
					it_card_person->second->time_area_over_time = current_time;

					deal_alarm_card(it_card_person->second, mp_card_list_area_over_time_person, is_true, AF_CARD_AREA_OVER_TIME);
				}
				over_time_person++;
			}else if(it_card_person->second->is_area_over_time){ // 理论上不会走这条分支，应该走cards_leave_area()
				it_card_person->second->is_area_over_time = false;
				deal_alarm_card(it_card_person->second, mp_card_list_area_over_time_person, is_true, AF_CARD_AREA_OVER_TIME);
			}				
		}

		over_time = over_time_vehicle;
		CardMap::iterator it_card_vehicle = it_Area->second->area_card_list_vehicle->begin();
		for(;it_card_vehicle != it_Area->second->area_card_list_vehicle->end(); ++it_card_vehicle){
			// 计数
			count_total++;

			count_vehicle++;
			// 超时
			if(difftime(current_time, CFunctions::systime_to_timet(it_card_vehicle->second->enter_area_time)) > over_time){
				is_true = true;
				if(!it_card_vehicle->second->is_area_over_time){
					it_card_vehicle->second->is_area_over_time = true;
					it_card_vehicle->second->time_area_over_time = current_time;

					deal_alarm_card(it_card_vehicle->second, mp_card_list_area_over_time_vehicle, is_true, AF_CARD_AREA_OVER_TIME);
				}
				over_time_vehicle++;
			}else if(it_card_vehicle->second->is_area_over_time){ // 理论上不会走这条分支，应该走cards_leave_area()
				is_true = false;
				it_card_vehicle->second->is_area_over_time = false;
				deal_alarm_card(it_card_vehicle->second, mp_card_list_area_over_time_vehicle, is_true, AF_CARD_AREA_OVER_TIME);
			}				
		}
		it_Area->second->count_person = count_person;
		it_Area->second->count_vehicle = count_vehicle;
		it_Area->second->count_area_over_time_person = count_over_time_person;
		it_Area->second->count_area_over_time_vehicle = count_over_time_vehicle;
		// 区域禁入 人员
		//if(it_Area->second->over_count_person == 0){
		if(AREA_TYPE_FORBIDDEN == it_Area->second->area_type_id ){
			if(count_person > 0){
				if(!it_Area->second->is_area_forbidden_person){
					it_Area->second->is_area_forbidden_person = true;
					it_Area->second->count_area_forbidden_person = count_person;
					it_Area->second->time_forbidden_person = current_time;

					deal_alarm_area(it_Area->second, mp_area_forbidden_person, true, AF_AREA_FORBIDDEN);
				}
			}else{
				if(it_Area->second->is_area_forbidden_person){
					it_Area->second->is_area_forbidden_person = false; // 结束报警

					deal_alarm_area(it_Area->second, mp_area_forbidden_person, false, AF_AREA_FORBIDDEN);
				}
			}
		} else {
			if(count_person > it_Area->second->over_count_person ){ // 区域人员超员
				if(!it_Area->second->is_area_over_count_person){
					it_Area->second->is_area_over_count_person = true;
					it_Area->second->count_area_over_count_person = count_person - it_Area->second->over_count_person;
					it_Area->second->time_over_count_person = current_time;

					INT64 ev_id = CFunctions::GetMicroSecond();
					std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
					ev->status = ES_START;
					ev->ev_type = ET_AREA_OVER_COUNT_PERSON;
					ev->obj_type = OT_AREA;
					ev->obj_id = CFunctions::int2string(it_Area->second->area_id);

					ev->map_id = it_Area->second->map_id;
					ev->area_id = it_Area->second->area_id;

					ev->limit_value = it_Area->second->over_count_person;
					ev->cur_value = count_person;
					ev->is_sent = false;

					it_Area->second->m_event_list[ET_AREA_OVER_COUNT_PERSON] = ev_id;
					store_data_event(ev);
					add_event(ev);

					deal_alarm_area(it_Area->second, mp_area_over_count_person, true, AF_AREA_OVER_COUNT);
				}else{
					//如果继续超员
					for (EventMap::iterator it_event = mp_event_list->begin();it_event!=mp_event_list->end();++it_event)
					{
						if (it_event->second->ev_type == ET_AREA_OVER_COUNT_PERSON && atoi(it_event->second->obj_id.c_str()) == it_Area->second->area_id)
						{
							//如果区域持续超员，且区域相等，
							//判断值是不是有变化，有变化，结束上一个，并生成新事件，无变化继续
							if (it_event->second->cur_value != count_person && it_event->second->status == ES_START)
							{
								it_event->second->status = ES_END;
								it_event->second->cur_time = time(NULL);
								it_event->second->is_sent = false;
								store_data_event(it_event->second);
								add_event(it_event->second);

								//生成新事件
								it_Area->second->count_area_over_count_person = count_person - it_Area->second->over_count_person;

								INT64 ev_id = CFunctions::GetMicroSecond();
								std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
								ev->status = ES_START;
								ev->ev_type = ET_AREA_OVER_COUNT_PERSON;
								ev->obj_type = OT_AREA;
								ev->obj_id = CFunctions::int2string(it_Area->second->area_id);

								ev->map_id = it_Area->second->map_id;
								ev->area_id = it_Area->second->area_id;

								ev->limit_value = it_Area->second->over_count_person;
								ev->cur_value = count_person;
								ev->is_sent = false;

								it_Area->second->m_event_list[ET_AREA_OVER_COUNT_PERSON] = ev_id;
								store_data_event(ev);
								add_event(ev);
							}
						}
					}

					it_Area->second->count_area_over_count_person = count_person - it_Area->second->over_count_person;
					it_Area->second->time_over_count_person = current_time;

					INT64 ev_id = CFunctions::GetMicroSecond();
					std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
					ev->status = ES_START;
					ev->ev_type = ET_AREA_OVER_COUNT_PERSON;
					ev->obj_type = OT_AREA;
					ev->obj_id = CFunctions::int2string(it_Area->second->area_id);

					ev->map_id = it_Area->second->map_id;
					ev->area_id = it_Area->second->area_id;

					ev->limit_value = it_Area->second->over_count_person;
					ev->cur_value = count_person;
					ev->is_sent = false;

					it_Area->second->m_event_list[ET_AREA_OVER_COUNT_PERSON] = ev_id;
					store_data_event(ev);
					add_event(ev);

					deal_alarm_area(it_Area->second, mp_area_over_count_person, true, AF_AREA_OVER_COUNT);
					Sleep(1);
				}
			}else{
				if(it_Area->second->is_area_over_count_person){ // 结束超员
					it_Area->second->is_area_over_count_person = false;

					INT64 ev_id = it_Area->second->m_event_list[ET_AREA_OVER_COUNT_PERSON];
					if(ev_id > 0){
						EventMap::iterator it_ev = mp_event_list->find(ev_id);
						if(it_ev != mp_event_list->end()){
							it_ev->second->status = ES_END;
							it_ev->second->cur_time = time(NULL);
							it_ev->second->cur_value = count_person;
							it_ev->second->is_sent = false;
							store_data_event(it_ev->second);
							add_event(it_ev->second);
						}					
					}
					it_Area->second->m_event_list[ET_AREA_OVER_COUNT_PERSON] = 0;

					deal_alarm_area(it_Area->second, mp_area_over_count_person, false, AF_AREA_OVER_COUNT);
				}
			}
			// 区域人员超时
			if(count_over_time_person > 0){
				if(!it_Area->second->is_area_over_time_person){
					it_Area->second->is_area_over_time_person = true;
					it_Area->second->time_over_time_person = current_time;
					deal_alarm_area(it_Area->second, mp_area_over_time_person, true, AF_AREA_OVER_TIME);
				}			
			}else{
				if(it_Area->second->is_area_over_time_person){ // 结束
					it_Area->second->is_area_over_time_person = false;
					deal_alarm_area(it_Area->second, mp_area_over_time_person, false, AF_AREA_OVER_TIME);
				}
			}
		}
		// 区域禁入 车辆
		if(AREA_TYPE_FORBIDDEN == it_Area->second->area_type_id){
			if(count_vehicle > 0){
				if(!it_Area->second->is_area_forbidden_vehicle){
					it_Area->second->is_area_forbidden_vehicle = true;
					it_Area->second->count_area_forbidden_vehicle = count_vehicle;
					it_Area->second->time_forbidden_vehicle = current_time;
					deal_alarm_area(it_Area->second, mp_area_forbidden_vehicle, true, AF_AREA_FORBIDDEN);
				}
			}else{
				if(it_Area->second->is_area_forbidden_vehicle){
					it_Area->second->is_area_forbidden_vehicle = false; // 结束报警
					deal_alarm_area(it_Area->second, mp_area_forbidden_vehicle, false, AF_AREA_FORBIDDEN);
				}
			}
		}else {
			if(count_vehicle > it_Area->second->over_count_vehicle){  // 区域车辆超员
				if(!it_Area->second->is_area_over_count_vehicle){
					it_Area->second->is_area_over_count_vehicle = true;
					it_Area->second->count_area_over_count_vehicle = count_vehicle - it_Area->second->over_count_vehicle;
					it_Area->second->time_over_count_vehicle = current_time;

					INT64 ev_id = CFunctions::GetMicroSecond();
					std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
					ev->status = ES_START;
					ev->ev_type = ET_AREA_OVER_COUNT_VEHICLE;
					ev->obj_type = OT_AREA;
					ev->obj_id = it_Area->second->area_id;
					ev->cur_time = time(NULL);

					ev->map_id = it_Area->second->map_id;
					ev->area_id = it_Area->second->area_id;
					ev->x = 0;
					ev->y = 0;

					ev->limit_value = it_Area->second->over_count_person;
					ev->cur_value = count_vehicle;
					ev->is_sent = false;

					it_Area->second->m_event_list[ET_AREA_OVER_COUNT_VEHICLE] = ev_id;
					store_data_event(ev);
					add_event(ev);

					deal_alarm_area(it_Area->second, mp_area_over_count_vehicle, true, AF_AREA_OVER_COUNT);
					Sleep(1);
				}
			}else{
				it_Area->second->is_area_over_count_vehicle = false; // 结束

				INT64 ev_id = it_Area->second->m_event_list[ET_AREA_OVER_COUNT_VEHICLE];
				if(ev_id > 0){
					EventMap::iterator it_ev = mp_event_list->find(ev_id);
					if(it_ev != mp_event_list->end()){
						it_ev->second->status = ES_END;
						it_ev->second->cur_time = time(NULL);
						it_ev->second->cur_value = count_vehicle;
						it_ev->second->is_sent = false;
						store_data_event(it_ev->second);
						add_event(it_ev->second);
					}					
				}
				it_Area->second->m_event_list[ET_AREA_OVER_COUNT_VEHICLE] = 0;

				deal_alarm_area(it_Area->second, mp_area_over_count_vehicle, false, AF_AREA_OVER_COUNT);
			}		
			// 区域车辆超时
			if(count_over_time_vehicle > 0){
				if(!it_Area->second->is_area_over_time_vehicle){
					it_Area->second->is_area_over_time_vehicle = true;
					it_Area->second->time_over_time_vehicle = current_time;
					deal_alarm_area(it_Area->second, mp_area_over_time_vehicle, true, AF_AREA_OVER_TIME);
				}
			}else{
				if(it_Area->second->is_area_over_time_vehicle){ // 结束
					it_Area->second->is_area_over_time_vehicle = false;
					deal_alarm_area(it_Area->second, mp_area_over_time_vehicle, false, AF_AREA_OVER_TIME);
					// 写入数据库
				}
			}
		}
	}
}

void CYAServerDlg::card_enter_mine(std::shared_ptr<Card> card /*Card* card*/)
{
	if(!card->is_pos_state_changed()){ // 位置没有变化
		if(PDT_DOWN == card->PosState()){
			if(CT_PERSON == card->card_type){
				if(!card->is_mine_over_time && difftime(time(NULL), card->get_working_time()) > sls_setting.over_time_person){
					deal_alarm_card(card, mp_card_list_over_time_person, true,  AF_CARD_OVER_TIME);
				}
				//井下超员
				if (mp_card_list_down_person.size() > sls_setting.over_count_person)
				{
					deal_alarm_card(card,mp_card_list_over_count_person,true,AF_CARD_OVER_COUNT);
				}
			}else if(CT_VEHICLE == card->card_type){
				if(!card->is_mine_over_time && difftime(time(NULL), card->get_working_time()) > sls_setting.over_time_vehicle){
					deal_alarm_card(card, mp_card_list_over_time_vehicle, true, AF_CARD_OVER_TIME);
				}
				if(card->get_speed() > sls_setting.over_speed){
					if(!card->is_mine_over_speed)
					{
						deal_alarm_card(card, mp_card_list_over_speed_vehicle, true, AF_CARD_OVER_SPEED);
					}
				}
				else
				{
					if(card->is_mine_over_speed)
					{
						deal_alarm_card(card, mp_card_list_over_speed_vehicle, false, AF_CARD_OVER_SPEED);
					}
				}
			}
		}
	}else{
		card_enter_mine(card, (POS_DEVICE_TYPE)card->PosState());
	}
}

void CYAServerDlg::card_enter_mine( std::shared_ptr<Card> card, POS_DEVICE_TYPE pdt )
{
	card->PosStateOld(pdt);
	card->PosState(pdt);	
	if(CT_PERSON) // 车辆不推送升入井消息
	{
		send_json_data(JSON_CMD_VALUE_PUSH, get_json_down_and_up(card));
	}
	if(PDT_DOWN == pdt)
	{ // 入井
		process_driving_face_start_service(card);
		card_down_mine(card);
		if(card->occupation == "安检员"){
			init_patrol_info(card->card_id);
		}
	}
	else if(PDT_UP ==pdt)
	{
		// 升井，补全离开区域时间
		store_data_card(card, HIS_AREA_LOCATION_LEAVE);
		if(card->occupation == "安检员"){
			delete_patrol_info(card->card_id);
		}
		process_driving_face_end_service(card);
		card_up_mine(card);
	}
}

void CYAServerDlg::card_enter_map(std::shared_ptr<Card> card /*Card* card*/ )
{
	if(card->map_id == card->map_id_old) return ;
	// 离开原地图，进入新地图
	MapInfoMap::iterator it_map_old = mp_map_list.find(card->map_id_old);
	if(it_map_old != mp_map_list.end()){
		if(CT_PERSON == card->card_type){
			CardMap::iterator it_card = it_map_old->second->map_card_list_person.find(card->card_id);
			if(it_card != it_map_old->second->map_card_list_person.end()){
				it_map_old->second->map_card_list_person.erase(it_card);
			}
		}else if(CT_VEHICLE == card->card_type){
			CardMap::iterator it_card = it_map_old->second->map_card_list_vehicle.find(card->card_id);
			if(it_card != it_map_old->second->map_card_list_vehicle.end()){
				it_map_old->second->map_card_list_vehicle.erase(it_card);
			}
		}
	}
	card->map_id_old = card->map_id;
	MapInfoMap::iterator it_map = mp_map_list.find(card->map_id);
	if(it_map != mp_map_list.end()){
		card->map_scale = it_map->second->map_scale;
		if(CT_PERSON == card->card_type){
			it_map->second->map_card_list_person.insert(make_pair(card->card_id, card));
		}else  if(CT_VEHICLE == card->card_type){
			it_map->second->map_card_list_vehicle.insert(make_pair(card->card_id, card));
		}
	}
}

//卡card进入区域
void CYAServerDlg::card_enter_area(std::shared_ptr<Card> card /* Card* card*/)
{
	if (card.use_count() == 0)
	{
		return;
	}
	if(!card->b_pos_change){
		//如果坐标无变化，不需要进区域判断逻辑
		return;
	}
	_point p1, p2;
	double r, scale;
	bool b_in_area = false;
	p1.x = card->x, p1.y = card->y, p1.z = card->z;

	AreaMap::iterator it_area_cur = mp_area_list.find(card->area_id);
	if(it_area_cur != mp_area_list.end()){ 
		// 在区域列表中存在此区域 
		if(it_area_cur->second->is_in_polygon(p1)) { 
			// 卡所在区域没有变化
			return;
		}
	}
	int old_area_id = card->area_id;
	AreaMap::iterator it_area = mp_area_list.begin();
	for(; it_area != mp_area_list.end(); ++it_area){
		if(card->map_id == it_area->second->map_id){ // 必须在同一地图内
			if(it_area->second->is_in_polygon(p1)){ // 在区域内
				/*if(it_area->second->area_id == old_area_id){
				return;
				}*/
				if(it_area_cur != mp_area_list.end()){ // 离开区域
					store_data_card(card, HIS_AREA_LOCATION_LEAVE);
					card_leave_area(card, it_area_cur->second);
				}
				card->area_id = it_area->second->area_id;
				card->enter_area_time = card->deal_time;
				card->PosState((0 == it_area->second->area_type_id) ? PDT_UP :PDT_DOWN);

				if(CT_PERSON == card->card_type){
					it_area->second->area_card_list_person->insert(make_pair(card->card_id, card));
					if(AREA_TYPE_FORBIDDEN == it_area->second->area_type_id){
						deal_alarm_card(card, mp_card_list_forbidden_person, true, AF_CARD_AREA_FORBIDDEN);
					}
				}else if(CT_VEHICLE == card->card_type){
					it_area->second->area_card_list_vehicle->insert(make_pair(card->card_id, card));
					if(AREA_TYPE_FORBIDDEN == it_area->second->area_type_id){
						deal_alarm_card(card, mp_card_list_forbidden_vehicle, true, AF_CARD_AREA_FORBIDDEN);
					}
				}
				b_in_area = true;
				break;
			}
		}
	}

	if(!b_in_area){	
		// 找不到区域，使用分站所属区域
		//从区域列表中查找卡所属分站的区域ID
		if(card->x == 0 || card->y == 0 || card->z == 0)
		{
			return;
		}
		AreaMap::iterator it_area_reader = mp_area_list.find(card->p_reader->area_id);
		if(it_area_reader == mp_area_list.end()){
			return;
		}
		if(card->area_id == it_area_reader->second->area_id){
			return;
		}
		if(it_area_cur != mp_area_list.end()){
			store_data_card(card, HIS_AREA_LOCATION_LEAVE);
			card_leave_area(card, it_area_cur->second);
		}
		card->area_id = it_area_reader->second->area_id;
		card->enter_area_time = card->deal_time;
		card->PosState((0 == it_area_reader->second->area_type_id) ? PDT_UP :PDT_DOWN);
		if(CT_PERSON == card->card_type){
			it_area_reader->second->area_card_list_person->insert(make_pair(card->card_id, card));
			if(AREA_TYPE_FORBIDDEN == it_area_reader->second->area_type_id){
				deal_alarm_card(card, mp_card_list_forbidden_person, true, AF_CARD_AREA_FORBIDDEN);
			}
		}else if(CT_VEHICLE == card->card_type){
			it_area_reader->second->area_card_list_vehicle->insert(make_pair(card->card_id, card));
			if(AREA_TYPE_FORBIDDEN == it_area_reader->second->area_type_id){
				deal_alarm_card(card, mp_card_list_forbidden_vehicle, true, AF_CARD_AREA_FORBIDDEN);
			}
		}
	}
	//TRACE(_T("x: %f, y: %f, lx: %f,ly: %f,area_id: %d \r\n"),card->x,card->y,card->last_x,card->last_y,card->area_id);
	//deal_areas();
	if(CT_VEHICLE == card->card_type){
		deal_area_over_speed(card);
	}
	// 保存区域信息
	store_data_card(card, HIS_AREA_LOCATION_ENTER);
}

void CYAServerDlg::card_enter_special_area(std::shared_ptr<Card> card, int special_area_id)
{
	if (card.use_count() == 0)
	{
		return;
	}

	if(card->area_id == special_area_id){
		return ;
	}
	card->area_id = special_area_id;
	card->enter_area_time = card->deal_time;
	card->PosState(PDT_UP);
	card->PosStateOld(PDT_UP);

	AreaMap::iterator it_area = mp_area_list.find(special_area_id);
	if(it_area != mp_area_list.end())
	{
		if(CT_PERSON == card->card_type)
		{
			it_area->second->area_card_list_person->insert(make_pair(card->card_id, card));
			if(AREA_TYPE_FORBIDDEN == it_area->second->area_type_id)
			{
				deal_alarm_card(card, mp_card_list_forbidden_person, true, AF_CARD_AREA_FORBIDDEN);
			}
		}
		else if(CT_VEHICLE == card->card_type)
		{
			it_area->second->area_card_list_vehicle->insert(make_pair(card->card_id, card));
			if(AREA_TYPE_FORBIDDEN == it_area->second->area_type_id)
			{
				deal_alarm_card(card, mp_card_list_forbidden_vehicle, true, AF_CARD_AREA_FORBIDDEN);
			}
		}
	}
	debug_print_syslog(0, "x: %f, y: %f, lx: %f,ly: %f,area_id: %d", 
		card->x, card->y, card->last_x, card->last_y, card->area_id);

	//deal_areas();
	if(CT_VEHICLE == card->card_type){
		deal_area_over_speed(card);
	}
	// 保存区域信息
	store_data_card(card, HIS_AREA_LOCATION_ENTER);
}


void CYAServerDlg::card_leave_area(std::shared_ptr<Card> card, std::shared_ptr<Area> area /*Card* card, Area* area*/)
{
	// 从列表中删除
	std::shared_ptr<CardMap> card_map = nullptr;
	std::shared_ptr<CardMap> alarm_card_map = nullptr;
	std::shared_ptr<CardMap> alarm_forbidden_map = nullptr;
	if(CT_PERSON == card->card_type){
		card_map = area->area_card_list_person;
		alarm_card_map = mp_card_list_area_over_time_person;
		alarm_forbidden_map = mp_card_list_forbidden_person;
	}else if(CT_VEHICLE == card->card_type){
		card_map = area->area_card_list_vehicle;
		alarm_card_map = mp_card_list_area_over_time_vehicle;
		alarm_forbidden_map = mp_card_list_forbidden_vehicle;
	}
	CardMap::iterator it_card = card_map->find(card->card_id);
	if(it_card != card_map->end()){
		// 如果区域超时
		if(it_card->second->is_area_over_time){
			it_card->second->is_area_over_time = false;
			deal_alarm_card(card, alarm_card_map, false, AF_CARD_AREA_OVER_TIME);
		}
		// 先处理，后删除
		deal_alarm_card(card, alarm_forbidden_map, false, AF_CARD_AREA_FORBIDDEN);

		card_map->erase(it_card);
	}
}

void CYAServerDlg::reset_map_card()
{
	MapInfoMap::iterator it_map = mp_map_list.begin();
	for(; it_map != mp_map_list.end(); ++ it_map){
		it_map->second->map_card_list_person.erase(it_map->second->map_card_list_person.begin(), it_map->second->map_card_list_person.end());
		it_map->second->map_card_list_vehicle.erase(it_map->second->map_card_list_vehicle.begin(), it_map->second->map_card_list_vehicle.end());
	}
}

bool CYAServerDlg::is_in_rectangle( _point p, double dblleft, double dbltop, double dblright, double dblbottom )
{
	return (p.x >= dblleft && p.x <= dblright && p.y >= dbltop && p.y <= dblbottom);
}

bool CYAServerDlg::is_in_circle( _point p1, _point p2, double r, double scale )
{
	return sqrt((p2.x - p1.x) * (p2.x - p1.x) +  (p2.y - p1.y) * (p2.y - p1.y)) <= r * scale;
}

void CYAServerDlg::package_data()
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_223);
	string strJson = get_json_position();
	// 定位数据
	if(strJson == ""){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_224);
		return ;
	}
	send_json_data(JSON_CMD_VALUE_PUSH, strJson);
	g_last_send_time = ::GetTickCount();
}

void CYAServerDlg::package_data_test()
{
	Json::Value root;
	Json::Value valStaffer;
	Json::Value valStaffers;
	Json::Value valDistance;
	Json::Value valDist;
	Json::Value valReaders;
	Json::Value valReader;
	int nCnt = 0;
	std::string strJson;
	for(int i = 1; i < 4; i++){
		valStaffer["id"] = i;
		valStaffer["x"] = 50 * (m_nCountClick + i);
		valStaffer["y"] = 50 * sin(20.0) * (m_nCountClick + i);
		valStaffers.append(valStaffer);
		nCnt++;
	}
	root["staffer"] = valStaffers;
	root["reader"] = valReaders;
	if(nCnt == 0){
		return;
	}
	strJson = root.toFastString();
	send_json_data(JSON_CMD_VALUE_PUSH, strJson.c_str());
}

void CYAServerDlg::formatByteArray( std::string &strBuf, BYTE * buf, int nLen )
{
	//CString strBuf1 = _T("");
	//for(int i = 0; i < nLen; i++){
	//	strBuf1.Format(_T("%.2X "),buf[i]);
	//	strBuf += strBuf1;
	//	if((i + 1) % 16 == 0){
	//		strBuf += _T("\n");
	//	}
	//}
	char ch[5];
	for(int i = 0; i < nLen; i++)
	{
		sprintf_s(ch, "%.2X ", buf[i]);
		strBuf += ch;
		if((i + 1)%16 == 0)
		{
			strBuf += "\n";
		}
	}
}

void CYAServerDlg::writeErrorLog( const CString strFile, const CString strErr, bool bTime /*= true*/  )
{
	LogInfo* err = new LogInfo;
	err->handle = NULL;
	err->useTime = false;
	err->path = NULL;
	err->strLog = NULL;

	err->handle = this;
	err->useTime = bTime;

	err->path = CFunctions::wc2c(strFile);
	err->strLog  = CFunctions::wc2c(strErr);

	send_err_log_message((char *)err);
}

BOOL CYAServerDlg::openLogFile(CString strFile)
{
	TCHAR lpstrCurDir[MAX_PATH] = _T("");
	CString ctemp;
	GetModuleFileName(NULL,lpstrCurDir,MAX_PATH);
	ctemp = lpstrCurDir;
	int index = ctemp.ReverseFind('\\');
	CString strFilePath = ctemp.Left(index+1);
	CString strFileName;
	strFileName.Format(_T("%s_%s.log"), strFile, COleDateTime::GetCurrentTime().Format(_T("%Y%m%d")));
	strFilePath += _T("error\\");
	strFilePath += strFileName;
	if (cfErrorLog == NULL){
		return FALSE;
	}
	BOOL bOpenFile=FALSE;//是否需要重新打开文件
	if(cfErrorLog.m_pStream==NULL){
		bOpenFile=TRUE;
	}else{
		if(cfErrorLog.GetFilePath()!=strFilePath){
			bOpenFile=TRUE;
			cfErrorLog.Close();
		}
	}
	if(bOpenFile){
		return cfErrorLog.Open(strFilePath, CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite|CFile::shareDenyNone);
	}else{
		return TRUE;
	}
}

BOOL CYAServerDlg::openLogFile(const char* strFile)
{
	TCHAR lpstrCurDir[MAX_PATH] = _T("");
	CString ctemp;
	GetModuleFileName(NULL,lpstrCurDir,MAX_PATH);
	ctemp = lpstrCurDir;
	int index = ctemp.ReverseFind('\\');
	CString strFilePath = ctemp.Left(index+1);
	CString strFileName;
	//CString strTemp;
	//strTemp.Format(_T("%S"),strFile);
	strFileName.Format(_T("%s_%s.log"), CFunctions::c2wc(strFile), COleDateTime::GetCurrentTime().Format(_T("%Y%m%d")));
	strFilePath += _T("error\\");
	strFilePath += strFileName;
	if (cfErrorLog == NULL){
		return FALSE;
	}
	BOOL bOpenFile=FALSE;//是否需要重新打开文件
	if(cfErrorLog.m_pStream==NULL){
		bOpenFile=TRUE;
	}else{
		if(cfErrorLog.GetFilePath()!=strFilePath){
			bOpenFile=TRUE;
			cfErrorLog.Close();
		}
	}
	if(bOpenFile){
		return cfErrorLog.Open(strFilePath, CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite|CFile::shareDenyNone);
	}else{
		return TRUE;
	}
}

void CYAServerDlg::OnBnExit()
{
	stop_and_exit();
}

void CYAServerDlg::OnBnSyncTime()
{
	//同步分站时间
	//send_sync_reader();

	//模拟单步控制双面灯
	/*send_call_light(CC_SET_LIGHTS_STATE, 1, 1, 2,LIGHT_SHAPE::GREEN_UP);
	Sleep(2000);
	send_call_light(CC_SET_LIGHTS_STATE, 2, 1, 2,LIGHT_SHAPE::GREEN_UP);

	Sleep(2000);
	send_call_light(CC_SET_LIGHTS_STATE, 1, 1, 2,LIGHT_SHAPE::RED_CIRCLE);
	Sleep(2000);
	send_call_light(CC_SET_LIGHTS_STATE, 2, 1, 2,LIGHT_SHAPE::RED_CIRCLE);*/
	//int i = 0;
	//while (1)
	//{
	//	int shape = i%7 + 1;
	//	i++;
	//	TRACE(_T("shape: %d \r\n"),shape);
	//	send_call_light(CC_SET_LIGHTS_STATE, 1, 1, 2,shape);
	//	Sleep(LIGHT_CTRL_DELAY);
	//	send_call_light(CC_SET_LIGHTS_STATE, 2, 1, 2,shape);
	//	Sleep(LIGHT_CTRL_DELAY);
	//}
	//模拟循环控制红绿灯
	/*int i = 0;
	while (1)
	{
	int shape = i%7 + 1;
	i++;
	TRACE(_T("shape: %d \r\n"),shape);
	send_call_light(CC_SET_LIGHTS_STATE, 1, 1, 2,shape);
	Sleep(LIGHT_CTRL_DELAY);
	send_call_light(CC_SET_LIGHTS_STATE, 2, 1, 2,shape);
	Sleep(LIGHT_CTRL_DELAY);
	}*/
}

CYAServerDlg::~CYAServerDlg()
{
	ws_close();
}

void CYAServerDlg::OnConnected()
{
	is_websocket_ok = true;
	time_ws_connect = ::GetTickCount();
}

void CYAServerDlg::OnClosed( client::close_reason const& reason )
{
	int i = -1;
	if(reason == client::close_reason_drop){
		i = (int) reason;
	}else{
		i = (int) reason;
	}
	is_websocket_login = false;
	is_websocket_ok = false;
#ifdef DEBUG
	TRACE(_T("The Connection is closed!\r\n"));
#endif // DEBUG	
}

void CYAServerDlg::OnFailed()
{
	is_websocket_login = false;
	is_websocket_ok = false;
	_io->close();
#ifdef DEBUG
	TRACE(_T("The Connection is dropped because of failed!\r\n"));
#endif // DEBUG	
}

void CYAServerDlg::ws_open()
{
	//m_ws_url="ws://localhost:8086/";
	_io->connect(m_ws_url);

	CString strlog = _T("");

	wchar_t* p = CFunctions::c2wc(m_ws_url.c_str());
	strlog.Format(_T("%s: %s"), _T(LOG_CONNECT_WEB_SERVER), p);
	if(p){
		free(p);
		p = NULL;
	}

	show_log(strlog);
}

void CYAServerDlg::OnPushMessage()
{
	string aa = "";
}

void CYAServerDlg::store_data_card(std::shared_ptr<Card> card /*Card* card*/, int tag )
{
	char sql[LENGTH_SQL] = {0};
	char _time[STR_LEN_TIME], _time_ex[STR_LEN_TIME];
	struct tm local_time, local_time_ex; 
	time_t t = time(NULL);

	bool b_exec = false;

	switch(tag){
	case HIS_RAW_DATA:
	case RPT_ATTEND_DOWN:
	case RPT_ATTEND_UP:
		t = CFunctions::systime_to_timet(card->deal_time);
		localtime_s(&local_time, &t);
		strftime(_time, 30, "%Y-%m-%d %H:%M:%S", &local_time);
		break;

	case HIS_AREA_LOCATION_ENTER:
	case HIS_AREA_LOCATION_LEAVE:
	case HIS_LOCATION:
		sprintf_s(_time,
			STR_LEN_TIME,
			"%u-%u-%u %u:%u:%u.%u",
			card->deal_time.wYear,card->deal_time.wMonth,card->deal_time.wDay,
			card->deal_time.wHour,card->deal_time.wMinute,card->deal_time.wSecond,card->deal_time.wMilliseconds);
		break;
	}

	switch(tag){
	case HIS_LOCATION:
		{
			//数据正常，推送数据库
			if(card->map_id != 0 && card->area_id != 0){
				b_exec = true;
				/*sprintf_s(sql, LENGTH_SQL, 
					"INSERT IGNORE INTO his_location(card_id, cur_time, x, y, z, map_id, area_id, state,speed,mileage, landmark_id, direction_mapper_id, landmark_dist) VALUES(%s, '%s', %.3f, %.3f, %.3f, %d, %d, %d,%.3f,%.4f, %d, %d, %.4f);",  
					card->card_id.c_str(), _time, card->x, card->y, card->z, card->map_id, card->area_id, card->state,card->get_speed(),card->mileage, card->landmark_id, card->landmark_direction, card->landmark_dis);*/
				
				//memset(_time,0,STR_LEN_TIME);

				if (card->curCellReaderName == "" && card->originCellReaderName == "")
				{
					return;
				}

				if (CFunctions::CheckSystemTimeValid(card->last_cell->interval_time))
				{
					sprintf_s(_time_ex,
						STR_LEN_TIME,
						"%u-%u-%u %u:%u:%u.%u",
						card->last_cell->interval_time.wYear,card->last_cell->interval_time.wMonth,card->last_cell->interval_time.wDay,
						card->last_cell->interval_time.wHour,card->last_cell->interval_time.wMinute,card->last_cell->interval_time.wSecond,card->last_cell->interval_time.wMilliseconds);
				}		

				std::string strTime = "";
				strTime = _time_ex;
#ifdef DEBUG
				//TRACE(_T("store_data_card: interval_time = %s\r\n"),CFunctions::c2wc(strTime.c_str()));
#else
				//char log[200] = {0};
				//sprintf_s(log,"store_data_card: interval_time = %s",strTime.c_str());
				//std::string strLog = log;
				//Log::write_log(FILE_TYPE::SYS_S,strLog,true);
#endif // DEBUG
				
				sprintf_s(sql,
					LENGTH_SQL,
					"insert ignore into his_cell_location(card_id,cur_time,interval_time,origin_reader_name,origin_cell_id,real_reader_name,real_cell_id,card_stamp_time,isFit,speed,mileage,map_id,area_id) values('%s','%s','%s','%s',%d,'%s',%d,%d,%d,%.4f,%.4f,%d,%d);",
					card->card_id.c_str(),
					_time,
					strTime.c_str(),
					card->originCellReaderName.c_str(),
					card->originCellId,
					card->curCellReaderName.c_str(),
					card->curCellId,
					card->time_stamp_last,
					card->is_fit_pos,
					card->get_speed(),
					card->mileage,
					card->map_id,
					card->area_id);
			}
			break;
		}
	case HIS_RAW_DATA:
		{
			b_exec = true;
			sprintf_s(sql, LENGTH_SQL,
				"INSERT IGNORE INTO his_raw_data(card_id, reader_id, antenna_id, reader_stamp, card_stamp, \
				fly_time, distance, ranging_type, power_state, accelerate, his_time, rec_time ) \
				VALUES(%s, %d, %d, %d, %d, %lld, %4.f, %d, %d, %d, '%s', '%s');",
				card->card_id.c_str(), card->reader_id, card->antenna_id, card->reader_tickcount, card->time_stamp,
				card->flying_time, card->distance, card->ranging_type, card->power_state, card->accelerate_state,
				card->str_his_time.c_str(), card->str_rec_time.c_str());
			break;
		}
	case HIS_AREA_LOCATION_ENTER:
		{
			if(card->map_id != 0 && card->area_id != 0){
				b_exec = true;
				sprintf_s(sql, LENGTH_SQL,
					"call add_area(%s, %d, %d, '%s','%s');",
					card->card_id.c_str() , card->area_id, card->map_id, _time,_time);
			}
			break;
		}
	case HIS_AREA_LOCATION_LEAVE:
		{
			if(card->map_id != 0 && card->area_id != 0){
				b_exec = true;
				sprintf_s(_time_ex,
					STR_LEN_TIME,
					"%u-%u-%u %u:%u:%u.%u",
					card->enter_area_time.wYear,card->enter_area_time.wMonth,card->enter_area_time.wDay,
					card->enter_area_time.wHour,card->enter_area_time.wMinute,card->enter_area_time.wSecond,card->enter_area_time.wMilliseconds);

				sprintf_s(sql, LENGTH_SQL,
					"call add_area(%s, %d, %d, '%s','%s');",
					card->card_id.c_str() , card->area_id, card->map_id, _time_ex,_time);
			}
			break;
		}
	case RPT_ATTEND_DOWN:
		{
			if(card->map_id != 0 && card->area_id != 0){
				b_exec = true;	
				switch (card->card_type)
				{
				case CT_PERSON:
					sprintf_s(sql, LENGTH_SQL,
						"CALL add_att_staff(%s, '%s', '%s', %d, %d, %.3f);",
						card->card_id.c_str(), _time, _time, card->landmark_id, card->landmark_direction, card->landmark_dis );
					break;
				case CT_VEHICLE:
					sprintf_s(sql, LENGTH_SQL,
						"CALL add_att_vehicle(%s, '%s', '%s', %d, %d, %.3f);",
						card->card_id.c_str(), _time, _time, card->landmark_id, card->landmark_direction, card->landmark_dis);
					break;
				}
			}
			break;
		}
	case RPT_ATTEND_UP:
		{
			if(card->map_id != 0 && card->area_id != 0){
				b_exec = true;
				string str_down_time = CFunctions::time_t2string(card->down_time);

				switch (card->card_type)
				{
				case CT_PERSON:
					sprintf_s(sql, LENGTH_SQL,
						"CALL add_att_staff(%s, '%s', '%s', %d, %d, %.3f);",
						card->card_id.c_str(), str_down_time.c_str(), _time,card->landmark_id, card->landmark_direction, card->landmark_dis);
					break;
				case CT_VEHICLE:
					sprintf_s(sql, LENGTH_SQL,
						"CALL add_att_vehicle(%s, '%s', '%s', %d, %d, %.3f);",
						card->card_id.c_str(), str_down_time.c_str(), _time, card->landmark_id, card->landmark_direction, card->landmark_dis);
					break;
				}
			}
			break;
		}
	default:
		return;
	}
	try
	{
		if(b_exec){
			execute_sql(sql);
<<<<<<< HEAD
			//CString sql_log = _T("");
			//sql_log = sql;
			//writeErrorLog(_T("SQL_S"),sql_log,true);
#ifdef ENABLE_MY_LOG
			std::string strlog = sql;
			Log::write_log(FILE_TYPE::SQL_S,strlog,true);//写入日志 20170705
#else
			CString sql_log = _T("");
			sql_log.Format(_T("%s"),sql);
			writeErrorLog(_T("SQL_S"),sql_log,true);
#endif // ENABLE_MY_LOG	
=======
			std::string strSqlLog = sql;
			Log::write_log(FILE_TYPE::SQL_S,strSqlLog,true);
>>>>>>> newprotocal
		}
	}
	catch (...)
	{

	}
}

std::string CYAServerDlg::get_json_counting()
{
	Json::Value root;
	Json::Value data;

	//超时总数，区域超时总数，特种异常工作异常总数，登陆时推送一次，增量推送，点集总数才推送详细列表
	int over_time_person_totals = 0;
	int area_over_time_person_totals = 0;
	int special_person_error_totals = 0;
	int over_time_vehicle_totals = 0;
	int area_over_time_vehicle_totals = 0;
	std::map<int,int> mp_area_over_time_person_counts;		//第一个int为area_id,第二个为区域人员超时统计的总数
	std::map<int,int> mp_area_over_time_vehicle_counts;		//第一个int为area_id,第二个为区域车辆超时统计的总数

	Json::Value counts;

	for (EventMap::iterator it = mp_event_list->begin();it != mp_event_list->end();++it)
	{
		if (it->second->obj_type == OT_CARD)//&&!it->second->is_count
		{
			CardMap::iterator it_card = mp_card_list_all.end();
			AreaMap::iterator it_area = mp_area_list.end();
			std::map<int,int>::iterator it_area_time_count;
			switch (it->second->ev_type)
			{
			case ET_CARD_OVER_TIME_PERSON:
				//井下人员超时总数
				over_time_person_totals++;
				it->second->is_count = true;
				break;
			case ET_CARD_AREA_OVER_TIME_PERSON:
				//人员区域超时
				//找到此卡，确定它的区域
				area_over_time_person_totals = 1;
				//找到此卡所在的区域
				it_area = mp_area_list.find(it->second->area_id);
				if (it_area == mp_area_list.end())
				{
					break;
				}
				//找到此区域，区域统计map中是否存在此区域
				it_area_time_count = mp_area_over_time_person_counts.find(it->second->area_id);
				if (it_area_time_count != mp_area_over_time_person_counts.end())
				{
					//存在此区域,则此区域内人数自增1
					//area_over_time_person_totals = area_over_time_person_totals;
					(it_area_time_count->second)++;
				}else{
					//不存在此区域，创建区域，并保存人数为1
					mp_area_over_time_person_counts.insert(std::make_pair(it_area->second->area_id,area_over_time_person_totals));
				}

				it->second->is_count = true;
				break;
			case ET_CARD_LOW_POWER:				//电量低
			case ET_CARD_LOW_POWER_SERIOUS:		//电量极低
			case ET_CARD_AREA_FORBIDDEN_PERSON:		//人员进入限制区域
			case ET_CARD_PATROL_ERROR:			//人员巡检异常
				//特种作业人员异常总数
				it_card = mp_card_list_down_person.find(it->second->obj_id);
				if (it_card != mp_card_list_down_person.end())
				{
					if (it_card->second->occupation == "安检员")
					{
						special_person_error_totals++;
						it->second->is_count = true;
					}
				}
				break;
			case ET_CARD_OVER_TIME_VEHICLE:
				// 车辆井下超时
				over_time_vehicle_totals++;
				it->second->is_count = true;
				break;
			case ET_CARD_AREA_OVER_TIME_VEHICLE:
				// 车辆区域超时
				//找到此卡，确定它的区域
				area_over_time_vehicle_totals = 1;
				//找到此卡所在的区域
				it_area = mp_area_list.find(it->second->area_id);
				if (it_area == mp_area_list.end())
				{
					break;
				}
				//存在此区域，则查看保存车辆区域超员map中是否有此区域总数统计
				it_area_time_count = mp_area_over_time_person_counts.find(it->second->area_id);
				if (it_area_time_count != mp_area_over_time_person_counts.end())
				{
					//存在，则统计数自增1
					//area_over_time_person_totals = area_over_time_person_totals;
					(it_area_time_count->second)++;
				}else{
					//不存在，则创建此统计总数
					mp_area_over_time_person_counts.insert(std::make_pair(it_area->second->area_id,area_over_time_person_totals));
				}

				/*it_card = mp_card_list_all.find(it->second->obj_id);
				it_area_time_count = mp_area_over_time_vehicle_counts.find(it_card->area_id);
				if (it_area_time_count != mp_area_over_time_vehicle_counts.end())
				{
				area_over_time_vehicle_totals = it_area_time_count->second;
				area_over_time_vehicle_totals++;
				it_area_time_count->second = area_over_time_vehicle_totals;
				}else{
				mp_area_over_time_vehicle_counts.insert(std::make_pair(it_card->area_id,area_over_time_vehicle_totals));
				}*/

				it->second->is_count = true;
				break;
			}
		}
	}

	//井下人员超员、区域人员超员
	int over_person_totals = 0;
	int over_vehicle_totals = 0;

	std::map<int,int> mp_area_over_person_counts;
	std::map<int,int> mp_area_over_vehicle_counts;

	//井下人员超员
	if (mp_card_list_down_person.size() > sls_setting.over_count_person)
	{
		over_person_totals = mp_card_list_down_person.size();
	}
	//井下车辆超员
	if (mp_card_list_down_vehicle.size() > sls_setting.over_count_vehicle)
	{
		over_vehicle_totals = mp_card_list_down_vehicle.size();
	}

	//区域超员
	for(AreaMap::iterator it_area = mp_area_list.begin();it_area != mp_area_list.end();++it_area)
	{
		//区域人员超员
		if (it_area->second->area_card_list_person->size() > it_area->second->over_count_person)
		{
			area_over_time_person_totals = it_area->second->area_card_list_person->size();
			mp_area_over_person_counts.insert(make_pair(it_area->second->area_id,area_over_time_person_totals));
		}
		//区域车辆超员
		if (it_area->second->area_card_list_vehicle->size() > it_area->second->over_count_vehicle)
		{
			area_over_time_vehicle_totals = it_area->second->area_card_list_vehicle->size();
			mp_area_over_vehicle_counts.insert(make_pair(it_area->second->area_id,area_over_time_vehicle_totals));
		}
	}

	if (over_person_totals > 0)
	{
		//井下人员超员总数
		data[JSON_KEY_ALARM_OVER_COUNT_PERSON] = over_person_totals;
	}

	if (over_vehicle_totals > 0)
	{
		//井下车辆超员总数
		data[JSON_KEY_ALARM_OVER_COUNT_VEHICLE] = over_vehicle_totals;
	}

	if (over_time_person_totals > 0)
	{
		//井下人员超时总数
		data[JSON_KEY_ALARM_OVER_TIME_PERSON] = over_time_person_totals;
	}

	if (over_time_vehicle_totals > 0)
	{
		//井下车辆超时总数
		data[JSON_KEY_ALARM_OVER_TIME_VEHICLE] = over_time_vehicle_totals;
	}

	if (special_person_error_totals > 0)
	{
		//特种作业人员异常总数
		data[JSON_KEY_COUNTING_SPECIAL_ERROR_TOTAL] = special_person_error_totals;
	}

	if (mp_area_over_time_person_counts.size() > 0)
	{
		//区域超时人员总数 区域 + 总数
		Json::Value area_counts;
		for (std::map<int,int>::iterator iter = mp_area_over_time_person_counts.begin();iter != mp_area_over_time_person_counts.end();++iter)
		{
			Json::Value area_over_time;
			area_over_time.append(iter->first);
			area_over_time.append(iter->second);
			area_counts.append(area_over_time);
		}
		if (area_counts.size() > 0)
		{
			data[JSON_KEY_ALARM_AREA_OVER_TIME_PERSON] = area_counts;
		}
	}

	if (mp_area_over_time_vehicle_counts.size() > 0)
	{
		//区域超时车辆总数 区域 + 总数
		Json::Value area_counts;
		for (std::map<int,int>::iterator iter = mp_area_over_time_vehicle_counts.begin();iter != mp_area_over_time_vehicle_counts.end();++iter)
		{
			Json::Value area_over_time;
			area_over_time.append(iter->first);
			area_over_time.append(iter->second);
			area_counts.append(area_over_time);
		}
		if (area_counts.size() > 0)
		{
			data[JSON_KEY_ALARM_AREA_OVER_TIME_VEHICLE] = area_counts;
		}
	}

	if (mp_area_over_person_counts.size() > 0)
	{
		//区域人员超员总数 区域 + 总数
		Json::Value area_counts;
		for (std::map<int,int>::iterator iter = mp_area_over_person_counts.begin();iter != mp_area_over_person_counts.end();++iter)
		{
			Json::Value area_over_person;
			area_over_person.append(iter->first);
			area_over_person.append(iter->second);
			area_counts.append(area_over_person);
		}
		if (area_counts.size() > 0)
		{
			data[JSON_KEY_ALARM_AREA_OVER_PERSON] = area_counts;
		}
	}
	if (mp_area_over_vehicle_counts.size() > 0)
	{
		//区域车辆超员总数  区域 + 总数
		Json::Value area_counts;
		for (std::map<int,int>::iterator iter = mp_area_over_vehicle_counts.begin();iter != mp_area_over_vehicle_counts.end();++iter)
		{
			Json::Value area_over_vehicle;
			area_over_vehicle.append(iter->first);
			area_over_vehicle.append(iter->second);
			area_counts.append(area_over_vehicle);
		}
		if (area_counts.size() > 0)
		{
			data[JSON_KEY_ALARM_AREA_OVER_VEHICLE] = area_counts;
		}
	}

	std::string ret = "";
	if (data.size() > 0)
	{
		root[JSON_ROOT_KEY_DATA] = data;
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_COUNTING;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		ret = root.toFastString();
	}

	return ret;
}

/*
* 从配置文件中载入数据库配置
*
* param
*		无
*
* return
*		无
*/
void CYAServerDlg::load_param_from_ini()
{
	m_tcp_host = CFunctions::c2wc(theApp.tcp_host.c_str());
	m_ws_url = theApp.ws_url;

	int nBackup = atoi(theApp.dbbackup.c_str());
	switch(nBackup){
	case 0:
		m_db_setting.host = theApp.dbhost;
		m_db_setting.user = theApp.dbuser;
		m_db_setting.password = theApp.dbpwd;
		m_db_setting.dbname = theApp.dbname;
		m_db_setting.encoding = theApp.dbencoding;
		m_db_setting.port = theApp.dbport;
		break;
	case 1:
		m_db_setting.host = theApp.dbhost_bk;
		m_db_setting.user = theApp.dbuser_bk;
		m_db_setting.password = theApp.dbpwd_bk;
		m_db_setting.dbname = theApp.dbname_bk;
		m_db_setting.encoding = theApp.dbencoding_bk;
		m_db_setting.port = theApp.dbport_bk;
		break;
	}
}

int CYAServerDlg::init_dept()
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	if(pConn == NULL){
		return 1;
	}

	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	pRes = pConn->Execute("select dept_id, name from dat_dept order by rank;", err);

	std::shared_ptr<Dept> dept = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))	{
		DeptMap::iterator it = mp_dept_list.find(atoi(pRow[0]));		
		if(it != mp_dept_list.end()){
			dept = it->second;
		}else{
			dept = std::make_shared<Dept>(atoi(pRow[0]), pRow[1]);
			mp_dept_list.insert(make_pair(dept->dept_id, dept));
			nRow++;
		}
	}
	mysql_free_result(pRes);
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_DEPT), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}

int CYAServerDlg::init_level()
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	if(pConn == NULL){
		return 1;
	}

	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	pRes = pConn->Execute("select occupation_level_id from dat_occupation_level;", err);

	std::shared_ptr<OccLevel> level = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))	{
		OccLevelMap::iterator it = mp_occlevel_list.find(atoi(pRow[0]));		
		if(it != mp_occlevel_list.end()){
			level = it->second;
		}else{
			level = std::make_shared<OccLevel>(atoi(pRow[0]));
			mp_occlevel_list.insert(make_pair(level->occlevel_id, level));
			nRow++;
		}
	}
	mysql_free_result(pRes);
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_LEVEL), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}

/*
* 从数据库的dat_setting表初始化系统阈值，
* 包括：井下人员阈值，井下车辆阈值，人员超时阈值，车辆超时阈值，车辆超速阈值
*
* param
*		无
*
* return
*		无
*/
int CYAServerDlg::init_setting()
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	if(pConn == NULL){
		return 1;
	}

	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	pRes = pConn->Execute("select setting_id, name, type, value from dat_setting;", err);
	string name, val, type;
	while(pRow = mysql_fetch_row(pRes))	{
		name = pRow[1], type = pRow[2],	val = pRow[3];
		if("over_count_person" == name){
			sls_setting.over_count_person = atoi(val.c_str());
		}else if("over_count_vehicle" == name){
			sls_setting.over_count_vehicle = atoi(val.c_str());
		}else if("over_time_person" == name){
			sls_setting.over_time_person = atoi(val.c_str()) * 60; // 转为秒
		}else if("over_time_vehicle" == name){
			sls_setting.over_time_vehicle = atoi(val.c_str()) * 60; // 转为秒
		}else if("over_speed" == name){
			sls_setting.over_speed = atof(val.c_str());
		}
	}
	mysql_free_result(pRes);

	show_log(_T(LOG_INIT_SETTING));

	return 0;
}

void CYAServerDlg::deal_alarm_card(std::shared_ptr<Card> card, std::shared_ptr<CardMap> dest_card_list/*Card* card, CardMap* dest_card_list*/, bool is_alarm, ALARM_FLAG tag)
{
	if(dest_card_list->empty())
	{
		return;
	}	
	if(is_alarm)
	{
		dest_card_list->insert(make_pair(card->card_id, card));
	}
	else
	{
		CardMap::iterator it_card = dest_card_list->find(card->card_id);
		if(it_card != dest_card_list->end())
		{
			dest_card_list->erase(it_card);
		}
		else
		{
			return;
		}
	}

	EVENT_TYPE et = ET_UNKNOWN;
	double limit_val = 0, cur_val = 0;

	AreaMap::iterator it_area = mp_area_list.find(card->area_id);
	if(it_area != mp_area_list.end()){
		et = ET_UNKNOWN;
		switch (tag)
		{
		case AF_CARD_OVER_TIME:
			{
				et = (card->card_type == CT_VEHICLE)? ET_CARD_OVER_TIME_VEHICLE:ET_CARD_OVER_TIME_PERSON;
				limit_val = (card->card_type == CT_VEHICLE)? sls_setting.over_time_vehicle : sls_setting.over_time_person;
				cur_val = difftime(time(NULL), card->get_working_time());

				card->is_mine_over_time = is_alarm;
				card->time_over_time = is_alarm ? time(NULL) : 0;
				card->status_over_time = is_alarm ? 1 : 0;
				break;
			}
		case AF_CARD_AREA_FORBIDDEN:
			{				
				et = (card->card_type == CT_VEHICLE)? ET_CARD_AREA_FORBIDDEN_VEHICLE:ET_CARD_AREA_FORBIDDEN_PERSON;
				limit_val = (card->card_type == CT_VEHICLE)? it_area->second->count_area_forbidden_vehicle : it_area->second->count_area_forbidden_person;
				cur_val = (card->card_type == CT_VEHICLE)? it_area->second->count_vehicle:it_area->second->count_person;

				card->time_area_forbidden = is_alarm ? time(NULL) : 0;
				card->status_area_forbidden = is_alarm ? 1 : 0;
				break;
			}
		case AF_CARD_AREA_OVER_TIME:
			{
				et = (card->card_type == CT_VEHICLE)? ET_CARD_AREA_OVER_TIME_VEHICLE:ET_CARD_AREA_OVER_TIME_PERSON;
				limit_val = (card->card_type == CT_VEHICLE)? it_area->second->over_time_vehicle : it_area->second->over_time_person;
				cur_val = difftime(card->time_area_over_time, CFunctions::systime_to_timet(card->enter_area_time));

				card->time_area_over_time = is_alarm ? time(NULL) : 0;
				card->status_area_over_time = is_alarm ? 1 : 0;
				break;
			}
		case AF_CARD_OVER_SPEED:
			{
				et = ET_CARD_OVER_SPEED;
				limit_val = sls_setting.over_speed;
				cur_val = card->get_speed();

				card->is_mine_over_speed = is_alarm;
				card->time_over_speed = is_alarm ? time(NULL) : 0;
				card->status_over_speed = is_alarm ? 1 : 0;
				break;
			}
		case AF_CARD_AREA_OVER_SPEED:
			{
				et = ET_CARD_AREA_OVER_SPEED;
				limit_val = it_area->second->over_speed_vehicle;
				cur_val = card->get_speed();

				card->is_area_over_speed = is_alarm;
				card->time_area_over_speed = is_alarm ? time(NULL) : 0;
				card->status_area_over_speed = is_alarm ? 1 : 0;
				break;
			}
		case AF_CARD_OVER_COUNT:
			{
				//井下人员超员
				et = (card->card_type == CT_VEHICLE)? ET_OVER_COUNT_VEHICLE:ET_OVER_COUNT_PERSON;
				limit_val = (card->card_type == CT_VEHICLE)? sls_setting.over_count_vehicle : sls_setting.over_count_person;
				cur_val = dest_card_list->size();
				break;
			}

		default:
			break;
		}

		if( ET_CARD_OVER_TIME_VEHICLE == et || ET_CARD_AREA_OVER_TIME_VEHICLE == et)
		{
			return ;
		}

		if(ET_UNKNOWN != et)
		{
			INT64 ev_id = card->m_event_list[et];
			if(ev_id > 0 )
			{			
				EventMap::iterator it_ev = mp_event_list->find(ev_id);
				if(it_ev != mp_event_list->end())
				{
					it_ev->second->limit_value = limit_val;
					it_ev->second->cur_value = cur_val;					
					it_ev->second->map_id = card->map_id;
					it_ev->second->area_id = card->area_id;
					it_ev->second->x = card->x;
					it_ev->second->y = card->y;
					it_ev->second->landmarkid = card->landmark_id;
					it_ev->second->landmarkdirect = card->landmark_direction;
					it_ev->second->landmarkdist = card->landmark_dis;
					if(is_alarm)
					{
						it_ev->second->is_sent = false;
					}
					else
					{
						it_ev->second->status = ES_END;
						it_ev->second->cur_time = time(NULL);
						it_ev->second->is_sent = false;
						store_data_event(it_ev->second);
						add_event(it_ev->second);

						card->m_event_list[et] = 0;
					}				
				}
			}
			else
			{
				INT64 ev_id = CFunctions::GetMicroSecond();
				std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
				ev->status = ES_START;	
				ev->ev_type = et;
				ev->obj_type = OT_CARD;
				ev->obj_id = card->card_id;
				ev->cur_time = time(NULL);
				ev->cur_value = cur_val;
				ev->limit_value = limit_val;
				
				ev->map_id = card->map_id;
				ev->area_id = card->area_id;
				ev->x = card->x;
				ev->y = card->y;
				ev->limit_value = limit_val;
				ev->cur_value = cur_val;
				ev->landmarkid = card->landmark_id;
				ev->landmarkdirect = card->landmark_direction;
				ev->landmarkdist = card->landmark_dis;
				ev->is_sent = false;
				card->m_event_list[et] = ev_id;
				store_data_event(ev);
				add_event(ev);
				Sleep(1);
			}
		}
	}
}

void CYAServerDlg::deal_drivingface_alarm(std::shared_ptr<Card> card, bool is_alarm, ALARM_FLAG tag)
{
	EVENT_TYPE et = ET_UNKNOWN;
	double limit_val = 0, cur_val = 0;
    
	INT64 ev_id = CFunctions::GetMicroSecond();
	std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
	if(is_alarm)
	{
		ev->status = ES_START;	
    	ev->cur_time = time(NULL);
		ev->is_sent = false;
		ev->ev_type = et;
    	ev->obj_type = OT_CARD;
    	ev->obj_id = card->card_id;
    	ev->cur_value = cur_val;
    	ev->limit_value = limit_val;
    
    	ev->map_id = card->map_id;
    	ev->area_id = card->area_id;
    	ev->x = card->x;
    	ev->y = card->y;
    	card->m_event_list[et] = ev_id;
	}
	else
	{
		ev->status = ES_END;
		ev->cur_time = time(NULL);
		ev->is_sent = false;
		ev->ev_type = et;
    	ev->obj_type = OT_CARD;
    	ev->obj_id = card->card_id;
    	ev->cur_value = cur_val;
    	ev->limit_value = limit_val;
    
    	ev->map_id = card->map_id;
    	ev->area_id = card->area_id;
    	ev->x = card->x;
    	ev->y = card->y;
		card->m_event_list[et] = 0;
	}
	
	store_data_event(ev);
	add_event(ev);
	Sleep(1);
}


void CYAServerDlg::deal_alarm_area(std::shared_ptr<Area> area, std::shared_ptr<AreaMap> dest_area_list /*Area* area, AreaMap* dest_area_list*/, bool is_alarm, ALARM_FLAG tag )
{
	//AreaMap::iterator it_area = dest_area_list->find(area->area_id);
	//if(it_area != dest_area_list->end()){
	//	if(!is_alarm){
	//		//savetodb
	//		dest_area_list->erase(it_area);
	//	}
	//}else{
	//	if(is_alarm){
	//		// savetodb
	//		dest_area_list->insert(make_pair(area->area_id, area));
	//	}
	//}
}

/*
* 根据车卡位置来实行红绿灯策略
*
* param
*		card		卡信息
*
* return
*		成功返回0，失败返回1
*/
int CYAServerDlg::deal_traffic_lights(std::shared_ptr<Card> card)
{
	if (card->x < 1E-3 && card->y < 1E-3)
	{
		return 1;
	}

	int nMapId  = 0;

	nMapId = card->map_id;

	MapInfoMap::iterator it_map = mp_map_list.find(nMapId);
	if (it_map != mp_map_list.end())
	{
		//车辆位置
		_point p;
		p.x = card->x;
		p.y = card->y;
		p.z = card->z;

		std::shared_ptr<Section> pSection = nullptr;

		//将车辆加入到车辆所在的路段表中
		SectionMap::iterator it_section ;
		it_section = it_map->second->map_section_list.begin();
		for (;it_section != it_map->second->map_section_list.end();++it_section)
		{
			//获得车辆所在的路段
			if (it_section->second->IsInPolygon(p))
			{
				pSection = it_section->second;
				//车辆在此路段内，将其保存到路段数据中
				CardMap::iterator it_card = pSection->mp_vehicle_list.find(card->card_id);
				if (it_card == pSection->mp_vehicle_list.end())
				{
					pSection->mp_vehicle_list.insert(make_pair(card->card_id,card));
				}

				//如果路段内车辆数大于正常数则记录报警时间
				//当路段之前是报警状态，当恢复正常状态，更新报警结束时间
				if (pSection->mp_vehicle_list.size() > 1)
				{
					int nSize = pSection->mp_vehicle_list.size();
					int nState = SECTION_STATE_NORMAL;
					switch (nSize)
					{
						//case 0:
						//	pSection->m_nState = SECTION_STATE_NORMAL;
						//	break;
					case 1:
						nState = SECTION_STATE_BUSY;
						break;
					case 2:
						nState = SECTION_STATE_CONGESTION;
						break;
					default:
						break;
					}
					//记录告警开始时间
					if(nState != pSection->m_nState){
						pSection->m_nState = nState;
						pSection->alarm_start_time = time(NULL);
						store_data_section(pSection,time(NULL),ALARM_SECTION_START);
					}
				}else{
					if (pSection->m_nState != SECTION_STATE_NORMAL)
					{
						pSection->m_nState = SECTION_STATE_NORMAL;
						time_t cur_time(time(NULL));
						store_data_section(pSection,cur_time,ALARM_SECTION_END);
					}
				}

				//此路段内有有轨车
				//退出
				break;
			}
		}

		if (card->m_nStream == 0)
		{
			return 1;
		}

		//车辆离开路口区域，将红绿灯组的所有灯设置为绿灯
		int nGroupId = 0;
		LightGroupMap::iterator it_lg = it_map->second->map_light_group_list.find(card->m_nLightGroupId);
		if (it_lg != it_map->second->map_light_group_list.end())
		{
			//红绿灯组所在区域即为路口区域
			it_section = it_map->second->map_section_list.find(it_lg->second->m_nSectionId);
			if (!it_section->second->IsInPolygon(p))
			{
				if (card->b_enter_intersection)
				{
					//离开路口区域，将此路口所有红绿灯改为绿色
					for (LightMap::iterator it_ll = it_lg->second->mp_lights_list.begin();it_ll != it_lg->second->mp_lights_list.end();++it_ll)
					{
						it_ll->second->m_nColor = COLOR_GREEN;
						if(LIGHT_CTRL_STATE::CTRL_STATE_AUTO == it_ll->second->m_nIsCtrl){
							//TRACE(_T("all show green ,light_id = %d \r\n"),it_ll->second->m_nID);
							send_call_light(CC_SET_LIGHTS_STATE,it_ll->second->m_nID, it_ll->second->m_nIsCtrl, it_ll->second->m_nColor,GREEN_UP);
							Sleep(LIGHT_CTRL_DELAY);
						}
					}
					card->b_enter_intersection = false;

					//发送控制消息给红绿灯组，
					LightGroupMap::iterator it_group = it_map->second->map_light_group_list.find(card->m_nLightGroupId);
					if (it_group != it_map->second->map_light_group_list.end())
					{
						if (it_group->second->isAllLightColor(COLOR_GREEN))
						{
							//释放红绿灯组的控制权
							card->m_nLightGroupId = -1;
							return 0;
						}
					}

					//控制成功，退出；控制失败，报警并退出
					//需要代码实现
				}
			}else{
				card->b_enter_intersection = true;
				//车辆进入路口区域，要判断车辆是否有此红绿灯组控制权，如没有，其即为闯红灯行为
				if (card->m_nLightGroupId != it_lg->second->m_nID)
				{
					LightMap::iterator it_light = it_map->second->map_light_list.find(card->light_id);
					if (it_light != it_map->second->map_light_list.end())
					{
						//记录车辆闯红灯了，将报警发到前端，发完即重置闯红灯状态
						card->is_red_light = true;
						store_data_traffic_red_light(it_light->second,card);
					}
				}
			}
		}	

		//找到路段
		if (pSection != nullptr)
		{
			//从路段中根据车辆上行/下行方向，获得路段中的上行灯/下行灯
			LightMap::iterator it_light = pSection->mp_light_list.begin();
			bool bFind = false;
			for (;it_light!=pSection->mp_light_list.end();++it_light)
			{
				//灯方向和车方向一致
				if (card->m_nStream == it_light->second->m_nStream)
				{
					bFind = true;
					card->light_id = it_light->second->m_nID;
					break;
				}
			}
			//如果没找到此灯，退出
			if (it_light == pSection->mp_light_list.end())
			{
				return 1;
			}
			//判断灯是否正常，不正常，放弃此灯组的控制权
			if (it_light->second->get_light_state() != STATUS_NORMAL)
			{
				it_light->second->m_nState = STATUS_ERROR;
				store_data_light(it_light->second,ALARM_LIGHT_FAULT_START);
				return 1;
			}
			//根据灯ID获取灯组id
			LightGroupMap::iterator it_group = it_map->second->map_light_group_list.end();
			if (it_light != pSection->mp_light_list.end() && bFind)
			{
				bFind = false;
				for (it_group = it_map->second->map_light_group_list.begin();it_group != it_map->second->map_light_group_list.end();++it_group)
				{
					if (it_group->second->isExist(it_light->second))
					{
						bFind = true;
						break;
					}
				}
			}

			if (it_group == it_map->second->map_light_group_list.end())
			{
				return 1;
			}

			if (it_group->second->isAllLightColor(COLOR_GREEN))
			{
				//灯组中的灯全是绿灯，获得此灯组的控制权

				//控制的是否为自己
				if (it_group->second->m_strVechileId == card->card_id)
				{
					//判断车是否长时间不动
					//如果是，则报警，并修改此车不能控制红绿灯功能
				} 
			}else{	
				//是否找到红绿灯所在的灯组
				if (it_group != it_map->second->map_light_group_list.end() && bFind)
				{
					if (it_group->second->m_bIsUsed)
					{
						//如果灯组在使用，
						//判断当前卡的级别是否大于控制灯组卡的级别，如果是，获得控制权
						bool bChangeAuthority = false;
						CardMap::iterator it_card = mp_card_list_all.find(it_group->second->m_strVechileId);
						if (it_card != mp_card_list_all.end())
						{
							//可以更改红绿灯组控制权的条件如下
							//1.存在此卡,车辆级别更高，
							//2.此车在主巷道，被控制的红绿灯组的车在非主巷道
							//3.车辆为上行且原车辆车辆为下行
							bool bRet = false;
							if (card->level > it_card->second->level)
							{
								bRet = true;
							}
							else if (card->level == it_card->second->level 
								&& (isInMainTunel(card)&&!isInMainTunel(it_card->second)))
							{
								bRet = true;
							}else if (card->level == it_card->second->level 
								&& (getTunelProperty(card)==getTunelProperty(it_card->second)&&(getTunelProperty(card)!=0))
								&& (card->direction == UP_STREAM && it_card->second->direction == DOWN_STREAM))
							{
								bRet = true;
							}

							if (bRet)
							{
								bChangeAuthority = true;
								it_group->second->m_strVechileId = card->card_id;
							}
						}

						if (!bChangeAuthority)
						{
							//说明此灯组被控制了，当前车辆无法控制红绿灯组，
							return 1;
							//那么车辆需要进硐室躲避
							card_enter_chamber(card,pSection);
						}
					}
				}else{
					return 1;
				}
			}

			it_group->second->m_bIsUsed = true;
			it_group->second->m_strVechileId = card->card_id;
			card->m_nLightGroupId = it_group->second->m_nID;
			//控制灯的颜色，将当前灯设置为绿色，其他为红色
			for (LightMap::iterator it_glight = it_group->second->mp_lights_list.begin();it_glight != it_group->second->mp_lights_list.end();++it_glight)
			{
				if (it_glight->second->m_nID == it_light->second->m_nID 
					&& it_glight->second->m_nMapID == it_light->second->m_nMapID )
				{
					it_glight->second->m_nColor = COLOR_GREEN;
				}else{
					it_glight->second->m_nColor = COLOR_RED;
				}

				if(LIGHT_CTRL_STATE::CTRL_STATE_AUTO == it_glight->second->m_nIsCtrl){
					switch (it_glight->second->m_nColor)
					{
					case COLOR_GREEN:
						//TRACE(_T("group : show green ;light_id = %d\r\n"),it_glight->second->m_nID);
						send_call_light(CC_SET_LIGHTS_STATE,it_glight->second->m_nID, it_glight->second->m_nIsCtrl, it_glight->second->m_nColor,GREEN_UP);
						break;
					case COLOR_RED:
						//TRACE(_T("group : show red ;light_id = %d\r\n"),it_glight->second->m_nID);
						send_call_light(CC_SET_LIGHTS_STATE,it_glight->second->m_nID, it_glight->second->m_nIsCtrl, it_glight->second->m_nColor,RED_CROSS);
						break;
					}
					//send_call_light(CC_SET_LIGHTS_STATE,it_glight->second->m_nID, it_glight->second->m_nIsCtrl, it_glight->second->m_nColor,GREEN_UP);
				}
				Sleep(LIGHT_CTRL_DELAY);
			}

			//下发控制消息给红绿灯，如果控制失败，则报警
		}
	}

	return 0;
}

/*:deal_area_over_speed
*	处理区域超速
*
*	param
*		card		车卡信息
*
*	return
*		成功返回0，失败返回1
*
*/
int CYAServerDlg::deal_area_over_speed(std::shared_ptr<Card> card)
{
	int nAreaId = 0;

	nAreaId = card->area_id;

	AreaMap::iterator it_area = mp_area_list.find(nAreaId);
	if (it_area != mp_area_list.end())
	{
		if (it_area->second->over_speed_vehicle == 0)
		{
			return 0;
		}

		if (card->get_speed() > it_area->second->over_speed_vehicle)
		{
			if(0 == it_area->second->over_speed_vehicle)
			{
				return 0;
			}
			if(!card->is_area_over_speed){
				deal_alarm_card(card,it_area->second->area_card_list_over_speed,true, AF_CARD_AREA_OVER_SPEED);
			}
		}else if(card->is_area_over_speed)
			deal_alarm_card(card,it_area->second->area_card_list_over_speed,false, AF_CARD_AREA_OVER_SPEED);
	}

	return 0;
}

/*
*	车辆进入硐室
*
*	param
*		card		车卡信息
*
*	return
*		成功返回0，失败返回1
*
*/
int CYAServerDlg::card_enter_chamber(std::shared_ptr<Card> card,std::shared_ptr<Section> section)
{
	return 1;
	ChamberMap::iterator it_chamber = section->mp_champer_list.begin();
	for (;it_chamber != section->mp_champer_list.end();++it_chamber)
	{
		//在路段中查找和车辆位置最近的可用硐室
		double dDistance = 0.0;
		//dDistance = sqrt(card->x);
		if (!it_chamber->second->m_nIsUsed)
		{

		}
	}

	return 0;
}

/*
* 判断坐标输出需不需要选择坐标左边偏移位置
*
* param
*		card	卡信息
* 
* return
*		成功返回0，执行失败返回1		
*
*/
int CYAServerDlg::select_pos_output(std::shared_ptr<Card> card)
{
	return 0;

	int nMapId = 0;

	nMapId = card->map_id;

	MapInfoMap::iterator it_map = mp_map_list.find(nMapId);
	for (;it_map != mp_map_list.end();++it_map)
	{
		CardMap::iterator it_vehicle = it_map->second->map_card_list_vehicle.begin();
		for (;it_vehicle != it_map->second->map_card_list_vehicle.end();++it_vehicle)
		{
			if (it_vehicle->second->card_id != card->card_id)
			{
				double distance = 0.0;
				distance = sqrt(pow(it_vehicle->second->x - card->x,2) + pow(it_vehicle->second->y - card->y,2));
				//会车距离
				if (distance <= VEHICLE_WIDTH )
				{
					//不同方向都靠右
					if (card->m_nMoveDirection != it_vehicle->second->m_nMoveDirection)
					{
						card->m_nOutputPosState = RIGHT_POS;
						it_vehicle->second->m_nOutputPosState = RIGHT_POS;
					}else{
						//相同方向一左一右
						card->m_nOutputPosState = LEFT_POS;
						it_vehicle->second->m_nOutputPosState = RIGHT_POS;
					}
				}else{
					card->m_nOutputPosState = CENTRAL_POS;
					it_vehicle->second->m_nOutputPosState = CENTRAL_POS;
				}
			}
		}


		//SectionMap::iterator it_section = it_map->second->map_section_list.begin();
		//for (;it_section != it_map->second->map_section_list.end();++it_section)
		//{
		//	_point p;
		//	p.x = card->x;
		//	p.y = card->y;
		//	p.z = card->z;

		//	if (it_section->second->IsInPolygon(p));
		//	{
		//		//判断路段内是否有反向运动的车辆，如果有，则最终要输出坐标靠左偏移的坐标
		//		CardMap::iterator it_vehicle = it_section->second->mp_vehicle_list.begin();
		//		for (;it_vehicle != it_section->second->mp_vehicle_list.end();++it_vehicle)
		//		{
		//			if (card->m_nMoveDirection != it_vehicle->second->m_nMoveDirection)
		//			{
		//				card->is_output_left_pos = true;
		//			}else{
		//				card->is_output_left_pos = false;
		//			}
		//		}
		//	}
	}

	return 0;
}

/*
* 从数据库的dat_alarm_type表初始化告警类型和名称
*
* param
*		无
*
* return
*		无
*/
int CYAServerDlg::init_alarm_type()
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	if(pConn == NULL){
		return 1;
	}

	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	pRes = pConn->Execute("select event_type_id, name from dat_event_type;", err);

	if(err>0){
		return 1;
	}

	while(pRow = mysql_fetch_row(pRes))	{
		AlarmTypeMap::iterator it = mp_alarm_type_list.find(atoi(pRow[0]));		
		if(it != mp_alarm_type_list.end()){
			it->second = pRow[1];
		}else{
			mp_alarm_type_list.insert(make_pair(atoi(pRow[0]), pRow[1]));
		}
	}
	mysql_free_result(pRes);

	show_log(_T(LOG_INIT_ALARM_TYPE));

	return 0;
}

void CYAServerDlg::AddItem( CString strvalue, int readerid, BOOL is_closed, DEVICE_TYPE rt )
{
	CString strRow;
	int nRow = 0;
	bool bFind = false;
	for(int i = 0; i < m_listctrl_reader.GetItemCount(); i++){
		if(strvalue == m_listctrl_reader.GetItemText(i, 1)){
			nRow = i;
			bFind = true;
			break;
		}
	}
	if(!bFind){
		nRow = m_listctrl_reader.GetItemCount();
		nRow = m_listctrl_reader.InsertItem(nRow, CFunctions::formatInt(readerid));
	}
	m_listctrl_reader.SetItemText(nRow, 1, strvalue);
	m_listctrl_reader.SetItemText(nRow, 2, is_closed ? _T("中断"): _T("已连接"));
	m_listctrl_reader.SetItemText(nRow, 3, (rt == DEVICE_TYPE::DT_CARD_READER)? _T("读卡分站"): _T("通信分站"));
	//debug_print_syslog(0, "Station connect info: ip:%S, read_id:%d, is_closed:%d, device_type:%d",
	//	strvalue, readerid, is_closed, rt);
}

void CYAServerDlg::show_log( LPCTSTR szlog, BOOL bSave )
{
	CString sMsg, sLog;
	CString sTime=COleDateTime::GetCurrentTime().Format(_T(LOG_TIME_FORMAT));
	sMsg.Format(_T("%s %s\n"), sTime, szlog);
	try{
		::LogMsg(sMsg);
	}
	catch(...){
	}
}

/*
* 初始化数据库连接
*
* param
*		无
*
* return
*		无
*
*/
void CYAServerDlg::database_connect()
{
	show_log(_T(LOG_CONNECT_DB));

	GetConnPool().Init(m_db_setting.encoding.c_str(), m_db_setting.host.c_str(), m_db_setting.user.c_str(), 
		m_db_setting.password.c_str(), m_db_setting.dbname.c_str(), m_db_setting.port, NULL, 0);
	int nConn = GetConnPool().InitAllConn();
	if(nConn > 0){
		show_log(_T(LOG_CONNECT_DB_SUCCESS));
	}else{
		show_log(_T(LOG_CONNECT_DB_FAIL));
	}
}

void CYAServerDlg::OnMenuDb()
{
	CDbSettingDlg dlg;
	dlg.DoModal();
}

void CYAServerDlg::OnCallMessage(string const& name, message::ptr const& data, bool isAck,message::list &ack_resp )
{
	if(data->get_flag() == message::flag_object){
		string cmd = data->get_map()[JSON_ROOT_KEY_CMD]->get_string();
		if(JSON_CMD_VALUE_META_DATA_CHANGED == cmd){
			map<string,message::ptr> data_map = data->get_map()[JSON_ROOT_KEY_DATA]->get_map();
			string name = data_map[JSON_KEY_NAME]->get_string().c_str();
			string op_type = data_map[JSON_KEY_OP_TYPE]->get_string().c_str();
			EDIT_TYPE_ID edit_type_id = (JSON_KEY_OP_TYPE_INSERT == op_type)? ET_INSERT: ((JSON_KEY_OP_TYPE_UPDATE == op_type)? ET_UPDATE: ET_DELETE);
			if(JSON_KEY_NAME_VEHICLE == name){
				string id = data_map[JSON_KEY_ID]->get_string().c_str();
				deal_call_edit_vehicle(id, edit_type_id);
			}else if(JSON_KEY_NAME_STAFF == name){
				string id = data_map[JSON_KEY_ID]->get_string().c_str();
				deal_call_edit_staff(id, edit_type_id);
			}else if(JSON_KEY_NAME_READER == name){
				int id = atoi(data_map[JSON_KEY_ID]->get_string().c_str());
				deal_call_edit_reader(id, edit_type_id);
			}else if(JSON_KEY_NAME_CARD == name){
				string id = data_map[JSON_KEY_ID]->get_string().c_str();
				deal_call_edit_card(id, edit_type_id);
			}else if(JSON_KEY_NAME_AREA == name){
				int id = atoi(data_map[JSON_KEY_ID]->get_string().c_str());
				deal_call_edit_area(id, edit_type_id);
			}else if(JSON_KEY_NAME_MAP == name){
				int id = atoi(data_map[JSON_KEY_ID]->get_string().c_str());
				deal_call_edit_map(id, edit_type_id);
			}else if(JSON_KEY_NAME_PATROL_TASK == name){
				std::string id = data_map[JSON_KEY_ID]->get_string().c_str();
				deal_call_edit_patrol_task(id, edit_type_id);
			}else if(JSON_KEY_NAME_PATH == name){
				//int id = data_map[JSON_KEY_ID]->get_int();
				//deal_call_edit_path(id, edit_type_id);
			}else if (JSON_KEY_NAME_SECTION == name)
			{
				int id = atoi(data_map[JSON_KEY_ID]->get_string().c_str());
				deal_call_edit_section(id,edit_type_id);
			}else if (JSON_KEY_NAME_LIGHT == name)
			{
				int id = atoi(data_map[JSON_KEY_ID]->get_string().c_str());
				deal_call_edit_light(id,edit_type_id);
			}else if (JSON_KEY_NAME_CHAMBER == name)
			{
				int id = atoi(data_map[JSON_KEY_ID]->get_string().c_str());
				deal_call_edit_chamber(id,edit_type_id);
			}else if(JSON_KEY_NAME_SHIFT == name)
			{
				init_shift();
			}
		}else if(JSON_CMD_VALUE_SET_LIMIT_VALUE == cmd){
			//阈值限制接口
			string json_data = data->get_map()[JSON_ROOT_KEY_DATA]->get_string(); 
			parse_json_data_set_limit_value(json_data.c_str());
		} else if(JSON_CMD_VALUE_REQUEST_ALL_POSTION == cmd){
			//请求全部位置信息
			send_json_data(JSON_CMD_VALUE_REQUEST_ALL_POSTION, get_json_position_all());
			// send_json_data(JSON_CMD_VALUE_SPECIAL_AREA_UP_MINE, get_json_all_special_area_data());
			//请求所有呼叫信息
			std::string call_list = "";
			call_list = get_json_call_list();
			if (call_list != "")
			{
				send_json_data(JSON_CMD_VALUE_PUSH,call_list);
			}
		} else if(JSON_CMD_VALUE_DEAL_HELP == cmd){
			// 处理呼救信息
			string json_data = data->get_map()[JSON_ROOT_KEY_DATA]->get_string(); 
			parse_json_data_deal_help(json_data.c_str());
		} else if(JSON_CMD_VALUE_CALL_CARD_REQUEST == cmd){
			//呼叫			
			parse_json_data_call_card(data);
		} else if(JSON_CMD_VALUE_CALL_CARD_CANCEL_REQUEST == cmd){
			//取消呼叫
			parse_json_data_call_card_cancel(data);
		} else if(JSON_CMD_VALUE_CLEAR_CARD == cmd) {
			// 清楚盲区卡
			//map<string,message::ptr> data_map = data->get_map()[JSON_ROOT_KEY_DATA]->get_map();
			//parse_json_data_clear_card(data_map);
		}else if (JSON_CMD_VALUE_LIGHTS_CTRL_REQUEST == cmd)
		{
			parse_json_data_set_light_color(data);
		}else if (JSON_CMD_VALUE_REQUEST_ALL_DATA == cmd)
		{
			debug_print_syslog(0, "receive user cmd:%s\n",cmd.c_str());
			std::string sd = "";
			sd = get_json_all_data();
			send_json_data(JSON_CMD_VALUE_PUSH, sd);
			load_his_driving_face_card_state(); //report driving face data
			debug_print_syslog(0, "send msg to web:%s\n",sd.c_str());
		}else if(JSON_CMD_VALUE_REQUEST_COUNTS_INFO == cmd){
			//前端请求统计总数的详细列表信息
			parse_json_data_request_counts_info(data);
		}
		else if(JSON_KEY_EVENT_READER_POS_CHANGE == cmd)
		{
			parse_json_data_reader_pos_change(data);
		}
	}
}

void CYAServerDlg::parse_json_data_set_limit_value( const char* sz )
{
	Json::Value root;
	Json::Reader reader;
	CString strlog;
	if (!reader.parse(sz,root)){
		strlog.Format(_T("%s%s"), _T(LOG_SET_LIMIT_VALUE), _T(LOG_FAIL));
		show_log(strlog);
		return ;
	}
	sls_setting.over_count_person = root[JSON_KEY_ALARM_OVER_COUNT_PERSON].asInt();
	sls_setting.over_count_vehicle = root[JSON_KEY_ALARM_OVER_COUNT_VEHICLE].asInt();
	sls_setting.over_time_person = root[JSON_KEY_ALARM_OVER_TIME_PERSON].asInt();
	sls_setting.over_time_vehicle = root[JSON_KEY_ALARM_OVER_TIME_VEHICLE].asInt();
	sls_setting.over_speed = root[JSON_KEY_ALARM_OVER_SPEED_VEHICLE].asDouble();

	strlog.Format(_T("%s%s"), _T(LOG_SET_LIMIT_VALUE), _T(LOG_SUCCESS));
	show_log(strlog);

	if(m_log_recv_package){
		std::string strlog = sz;
		Log::write_log(FILE_TYPE::JSON_R, strlog, true);
	}
}

void CYAServerDlg::parse_json_data_call_card(message::ptr const& data)
{
	CString strlog = _T("");
	string call_id = "", user_name = "", call_time = "";
	string cardid = "", readerid = "";
	int call_time_out = 0, reader_count = 0, card_count = 0, call_type_id = 0;

	map<string,message::ptr> data_map = data->get_map()[JSON_ROOT_KEY_DATA]->get_map();

	call_id			= data_map[JSON_KEY_CALL_CARD_CALL_ID]->get_string();
	call_time_out	= data_map[JSON_KEY_CALL_CARD_CALL_TIME_OUT]->get_int();
	call_type_id	= data_map[JSON_KEY_CALL_CARD_CALL_TYPE]->get_int();
	user_name		= data_map[JSON_KEY_CALL_CARD_USER_NAME]->get_string();
	call_time		= data_map[JSON_KEY_CALL_CARD_CALL_TIME]->get_string();

	vector<message::ptr> reader_vec = data_map[JSON_KEY_CALL_CARD_STATIONS]->get_vector();
	vector<message::ptr> card_vec = data_map[JSON_KEY_CALL_CARD_CARDS]->get_vector();

	if(reader_vec.size() == 0 && card_vec.size() == 0)
	{
		return;
	}

	int reader_id = 0, npos = 0;
	shared_ptr<_call_info_user> call_user;
	shared_ptr<_call_info_reader> call_reader;
	std::shared_ptr<_call_info_card> call_card;

	CallInfoUserMap::iterator it_user_call = mp_user_call_info.find(user_name);
	if(it_user_call != mp_user_call_info.end()){
		call_user = it_user_call->second;
	}else{
		call_user = std::make_shared<_call_info_user>();
		call_user->user_name = user_name;
		mp_user_call_info.insert(make_pair(user_name, call_user));
	}

	SocketMap::iterator it_sock;
	BYTE buf[LENGTH_SEND_BUF] = {0};
	//呼叫发起有两种，
	//一种通过分站发起呼叫即为对此分站下的所有自组网卡全员呼叫
	//一种是对单卡发起的呼叫
	vector<message::ptr>::const_iterator it_reader = reader_vec.begin();
	for(; it_reader != reader_vec.end(); ++it_reader){
		std::string s_reader_id = "";
		s_reader_id = (*it_reader)->get_map()[JSON_KEY_CALL_CARD_STATION_ID]->get_string();	
		reader_id = atoi(s_reader_id.c_str());

		CallInfoReaderMap::iterator it_call_reader = call_user->mpReader.find(reader_id);
		if(it_call_reader != call_user->mpReader.end()){
			call_reader = it_call_reader->second;
			if(call_reader->call_type > call_type_id){
				call_reader->call_type = call_type_id;
			}
		}else{
			call_reader = std::make_shared<_call_info_reader>();
			call_reader->call_type = call_type_id;
			call_user->mpReader.insert(make_pair(reader_id, call_reader));
		}

		//当对某一个分站，不输入任何卡号，需要判断card_vec的大小
		if (card_vec.size() > 0)
		{
			vector<message::ptr>::const_iterator it_card = card_vec.begin();
			std::string  str_card_id = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string();

			if("" == str_card_id || str_card_id == "0"){
				call_reader->cards_count = 0;
				call_reader->is_call_all = true;
				call_reader->is_start_call = true;
			}else{
				call_reader->cards_count = card_vec.size();
				call_reader->is_call_all = false;
				call_reader->is_start_call = true;

				BYTE card_type = 0;
				for(; it_card != card_vec.end(); ++it_card){
					string s_card_id = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string();
					//string s_card_type = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID]->get_string();
					int card_type = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID]->get_int();
					CallInfoCardMap::iterator it_call_card = call_reader->mpCard.find(s_card_id);

					int card_id = atoi(s_card_id.c_str());
					//int card_type = atoi(s_card_type.c_str());
					if(it_call_card != call_reader->mpCard.end()){ // 已在呼叫列表
						call_card = it_call_card->second;
						if(call_card->call_type < call_type_id){ // 原呼叫优先级低
							call_card->card_type = card_type;
							call_card->call_type = call_type_id;
							call_card->start_time = time(NULL);
							call_card->time_out = call_time_out;
						}else {
							call_card->start_time = time(NULL);
							call_card->time_out = call_time_out;
						}
					}else{ // 未在呼叫列表
						call_card = std::make_shared<_call_info_card>();
						call_card->card_type = card_type;
						call_card->start_time = time(NULL);
						call_card->time_out = call_time_out;
						call_card->call_type = call_type_id;
						call_reader->mpCard.insert(make_pair(s_card_id, call_card));
					}
				}
			}
		}else{
			//此分站的全员呼叫
			call_reader->cards_count = 0;
			call_reader->is_call_all = true;
			call_reader->is_start_call = true;
		}	
	}

	//单卡发送呼叫
	it_reader = reader_vec.begin();
	if(it_reader == reader_vec.end() && card_vec.size() > 0 ){	
		int nCounts = 0;
		int card_id = 0;
		BYTE card_type = 0;	
		string s_card_id = "";
		string s_card_type = "";

		vector<message::ptr>::const_iterator it_card = card_vec.begin();

		for(; it_card != card_vec.end(); ++it_card){
			card_type = 0;	
			s_card_id = "";
			s_card_type = "";
			call_type_id = 0;

			nCounts++;

			s_card_id = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string();		
			card_type =(*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID]->get_int();

			string new_card_id = s_card_id.substr(3,s_card_id.length());
			card_id = atoi(new_card_id.c_str());

			CardMap::iterator it_card = mp_card_list_all.find(s_card_id);
			if (it_card== mp_card_list_all.end())
			{
				continue;
			}

			reader_id = it_card->second->reader_id;
			CallInfoReaderMap::iterator it_call_reader = call_user->mpReader.find(reader_id);

			if(it_call_reader != call_user->mpReader.end()){
				call_reader = it_call_reader->second;	
				call_reader->is_start_call = true;
				call_reader->is_call_all = false;
				call_reader->cards_count = 1;
				if(call_reader->call_type > call_type_id){
					call_reader->call_type = call_type_id;
				}
			}else{
				call_reader = std::make_shared<_call_info_reader>();
				call_reader->call_type = call_type_id;
				call_reader->is_call_all = false;
				call_reader->cards_count = 1;
				call_reader->is_start_call = true;
				call_user->mpReader.insert(make_pair(reader_id, call_reader));
			}

			CallInfoCardMap::iterator it_call_card = call_reader->mpCard.find(s_card_id);
			if(it_call_card != call_reader->mpCard.end()){ // 已在呼叫列表
				call_card = it_call_card->second;
				if(call_card->call_type < call_type_id){ // 原呼叫优先级低
					call_card->card_type = card_type;
					call_card->card_id = 1;
					call_card->call_type = call_type_id;
					call_card->start_time = time(NULL);
					call_card->time_out = call_time_out;
				}else {
					call_card->start_time = time(NULL);
					call_card->time_out = call_time_out;
				}
			}else{ // 未在呼叫列表
				call_card = std::make_shared<_call_info_card>();
				call_card->card_id = card_id;
				call_card->card_type = card_type;
				call_card->start_time = time(NULL);
				call_card->time_out = call_time_out;
				call_card->call_type = call_type_id;
				call_card->str_card_id = s_card_id;
				call_reader->mpCard.insert(make_pair(s_card_id, call_card));
			}
		}
	}

	Json::Value root;
	Json::Value resp_data;

	//收到呼叫信息，即直接返回
	time_t ct = time(NULL);
	double t = *((int64_t*)&ct)*1000;
	if (atoi(call_id.c_str()) == 0)
	{
		Json::Value callinfo;
		callinfo.append(user_name);
		callinfo.append(0);
		callinfo.append(0);
		callinfo.append(t);
		callinfo.append(call_id);
		//CALL_STATE::CALL_SUCCESSED,CALL_STATE::CALL_ING,CALL_STATE::CALL_FAILED
		callinfo.append(CALL_STATE::CALL_ING);
		resp_data.append(callinfo);
	}else{
		//是否有选择分站
		if (reader_vec.size() > 0)
		{
			//如果有选择分站
			//根据分站数和卡数量构造返回呼叫返回的json
			for (vector<message::ptr>::const_iterator it_reader = reader_vec.begin();it_reader != reader_vec.end();++it_reader)
			{	
				if (card_vec.size() > 0)
				{
					for (vector<message::ptr>::const_iterator it_card = card_vec.begin();it_card != card_vec.end();++it_card)
					{
						Json::Value callinfo;
						callinfo.append(user_name);
						callinfo.append((*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string());
						callinfo.append((*it_reader)->get_map()[JSON_KEY_CALL_CARD_STATION_ID]->get_string());
						callinfo.append(t);
						callinfo.append(call_id);
						//CALL_STATE::CALL_SUCCESSED,CALL_STATE::CALL_ING,CALL_STATE::CALL_FAILED
						callinfo.append(CALL_STATE::CALL_ING);
						resp_data.append(callinfo);
					}
				}else{
					Json::Value callinfo;
					callinfo.append(user_name);
					callinfo.append(0);
					callinfo.append((*it_reader)->get_map()[JSON_KEY_CALL_CARD_STATION_ID]->get_string());
					callinfo.append(t);
					callinfo.append(call_id);
					//CALL_STATE::CALL_SUCCESSED,CALL_STATE::CALL_ING,CALL_STATE::CALL_FAILED
					callinfo.append(CALL_STATE::CALL_ING);
					resp_data.append(callinfo);
				}			
			}
		} 
		else
		{
			//如果无分站信息
			for (vector<message::ptr>::const_iterator it_card = card_vec.begin();it_card != card_vec.end();++it_card)
			{
				Json::Value callinfo;
				callinfo.append(user_name);
				callinfo.append((*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string());
				callinfo.append(0);
				callinfo.append(t);
				callinfo.append(call_type_id);
				//CALL_STATE::CALL_SUCCESSED,CALL_STATE::CALL_ING,CALL_STATE::CALL_FAILED
				callinfo.append(CALL_STATE::CALL_ING);
				resp_data.append(callinfo);
			}
		}		
	}

	std::string ret = "";
	if(resp_data.size() > 0){
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_CALL_CARD_RESPONSE;
		root[JSON_ROOT_KEY_DATA] = resp_data;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		ret = root.toFastString();
		send_json_data(JSON_CMD_VALUE_PUSH,ret);
	}

	strlog.Format(_T("%s%s"), _T(LOG_CALL_CARD), _T(LOG_SUCCESS));
	show_log(strlog);

	//CString strlog;
	//string call_id, user_name, call_time;
	//string cardid, readerid;
	//int call_time_out, reader_count, card_count, call_type_id;

	//map<string,message::ptr> data_map = data->get_map()[JSON_ROOT_KEY_DATA]->get_map();

	//call_id			= data_map[JSON_KEY_CALL_CARD_CALL_ID]->get_string();
	//call_time_out	= data_map[JSON_KEY_CALL_CARD_CALL_TIME_OUT]->get_int();
	//call_type_id	= data_map[JSON_KEY_CALL_CARD_CALL_TYPE]->get_int();
	//user_name		= data_map[JSON_KEY_CALL_CARD_USER_NAME]->get_string();
	//call_time		= data_map[JSON_KEY_CALL_CARD_CALL_TIME]->get_string();

	//vector<message::ptr> reader_vec = data_map[JSON_KEY_CALL_CARD_STATIONS]->get_vector();
	//vector<message::ptr> card_vec = data_map[JSON_KEY_CALL_CARD_CARDS]->get_vector();

	//if(reader_vec.size() == 0 && card_vec.size() == 0)
	//{
	//	return;
	//}

	//int reader_id, npos;
	//SocketMap::iterator it_sock;
	//BYTE buf[LENGTH_SEND_BUF];
	//shared_ptr<_call_info_user> call_user;
	//shared_ptr<_call_info_reader> call_reader;
	//std::shared_ptr<_call_info_card> call_card;

	//CallInfoUserMap::iterator it_user_call = mp_user_call_info.find(user_name);
	//if(it_user_call != mp_user_call_info.end()){
	//	call_user = it_user_call->second;
	//}else{
	//	call_user = std::make_shared<_call_info_user>();
	//	call_user->user_name = user_name;
	//	mp_user_call_info.insert(make_pair(user_name, call_user));
	//}

	////呼叫发起有两种，
	////一种通过分站发起呼叫即为对此分站下的所有自组网卡全员呼叫
	////一种是对单卡发起的呼叫
	//vector<message::ptr>::const_iterator it_reader = reader_vec.begin();
	//if(reader_vec.size() > 0){	
	//	for(; it_reader != reader_vec.end(); ++it_reader){
	//		std::string s_reader_id = "";
	//		s_reader_id = (*it_reader)->get_map()[JSON_KEY_CALL_CARD_STATION_ID]->get_string();	
	//		reader_id = atoi(s_reader_id.c_str());
	//		//reader_id  = (*it_reader)->get_map()[JSON_KEY_CALL_CARD_STATION_ID]->get_int();

	//		CallInfoReaderMap::iterator it_call_reader = call_user->mpReader.find(reader_id);
	//		if(it_call_reader != call_user->mpReader.end()){
	//			call_reader = it_call_reader->second;
	//			if(call_reader->call_type > call_type_id){
	//				call_reader->call_type = call_type_id;
	//			}
	//		}else{
	//			call_reader = std::make_shared<_call_info_reader>();
	//			call_reader->call_type = call_type_id;
	//			call_user->mpReader.insert(make_pair(reader_id, call_reader));
	//		}

	//		vector<message::ptr>::const_iterator it_card = card_vec.begin();	
	//		int card_id = atoi((*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string().c_str());
	//		//if(card_vec.size() == 0 || 0 == (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_int()){
	//		if(card_vec.size() == 0 || 0 == card_id){
	//			call_reader->cards_count = 0;
	//			call_reader->is_call_all = true;
	//			call_reader->is_start_call = true;
	//	
	//		}else{
	//			call_reader->cards_count = card_vec.size();
	//			call_reader->is_call_all = false;
	//			call_reader->is_start_call = true;

	//			BYTE card_type = 0;
	//			for(; it_card != card_vec.end(); ++it_card){
	//				if( "" == (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string()){
	//					call_reader->cards_count = 0;
	//					call_reader->is_call_all = true;
	//				}else{
	//					string s_card_id = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string();
	//					string s_card_type = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID]->get_string();
	//					//string str_card_id = CFunctions::getstrwithzero(card_type, 3) + CFunctions::getstrwithzero(card_id, 10);
	//					CallInfoCardMap::iterator it_call_card = call_reader->mpCard.find(s_card_id);

	//					int card_id = atoi(s_card_id.c_str());
	//					int card_type = atoi(s_card_type.c_str());
	//					if(it_call_card != call_reader->mpCard.end()){ // 已在呼叫列表
	//						call_card = it_call_card;
	//						if(call_card->call_type < call_type_id){ // 原呼叫优先级低
	//							call_card->card_type = card_type;
	//							call_card->call_type = call_type_id;
	//							call_card->start_time = time(NULL);
	//							call_card->time_out = call_time_out;
	//						}else {
	//							call_card->start_time = time(NULL);
	//							call_card->time_out = call_time_out;
	//						}
	//					}else{ // 未在呼叫列表
	//						call_card = std::make_shared<_call_info_card>();
	//						call_card->card_type = card_type;
	//						call_card->start_time = time(NULL);
	//						call_card->time_out = call_time_out;
	//						call_card->call_type = call_type_id;
	//						call_reader->mpCard.insert(make_pair(s_card_id, call_card));
	//					}
	//				}
	//			}
	//		}
	//	}
	//}

	////单卡发送呼叫
	//it_reader = reader_vec.begin();
	//if(it_reader == reader_vec.end() && card_vec.size() > 0 ){	
	//	int nCounts = 0;
	//	int card_id = 0;
	//	BYTE card_type = 0;	
	//	string s_card_id = "";
	//	string s_card_type = "";

	//	vector<message::ptr>::const_iterator it_card = card_vec.begin();

	//	for(; it_card != card_vec.end(); ++it_card){
	//		card_type = 0;	
	//		s_card_id = "";
	//		s_card_type = "";
	//		call_type_id = 0;

	//		nCounts++;

	//		s_card_id = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string();		
	//		card_type =(*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID]->get_int();

	//		string new_card_id = s_card_id.substr(3,s_card_id.length());
	//		card_id = atoi(new_card_id.c_str());
	//		//card_type = atoi(s_card_type.c_str());

	//		CardMap::iterator it_card = mp_card_list_all.find(s_card_id);
	//		if (it_card== mp_card_list_all.end())
	//		{
	//			continue;
	//		}

	//		//reader_id = mp_card_list_down_adhoc.find(s_card_id)->second->reader_id;
	//		reader_id = it_card->reader_id;
	//		CallInfoReaderMap::iterator it_call_reader = call_user->mpReader.find(reader_id);

	//		if(it_call_reader != call_user->mpReader.end()){
	//			call_reader = it_call_reader->second;	
	//			call_reader->is_start_call = true;
	//			call_reader->is_call_all = false;
	//			call_reader->cards_count = 1;
	//			if(call_reader->call_type > call_type_id){
	//				call_reader->call_type = call_type_id;
	//			}
	//		}else{
	//			call_reader = std::make_shared<_call_info_reader>();
	//			call_reader->call_type = call_type_id;
	//			call_reader->is_call_all = false;
	//			call_reader->cards_count = 1;
	//			call_reader->is_start_call = true;
	//			call_user->mpReader.insert(make_pair(reader_id, call_reader));
	//		}


	//		CallInfoCardMap::iterator it_call_card = call_reader->mpCard.find(s_card_id);
	//		if(it_call_card != call_reader->mpCard.end()){ // 已在呼叫列表
	//			call_card = it_call_card;
	//			if(call_card->call_type < call_type_id){ // 原呼叫优先级低
	//				call_card->card_type = card_type;
	//				call_card->card_id = 1;
	//				call_card->call_type = call_type_id;
	//				call_card->start_time = time(NULL);
	//				call_card->time_out = call_time_out;
	//			}else {
	//				call_card->start_time = time(NULL);
	//				call_card->time_out = call_time_out;
	//			}
	//		}else{ // 未在呼叫列表
	//			call_card = std::make_shared<_call_info_card>();
	//			call_card->card_id = card_id;
	//			call_card->card_type = card_type;
	//			call_card->start_time = time(NULL);
	//			call_card->time_out = call_time_out;
	//			call_card->call_type = call_type_id;
	//			call_card->str_card_id = s_card_id;
	//			call_reader->mpCard.insert(make_pair(s_card_id, call_card));
	//		}
	//	}
	//}

	//strlog.Format(_T("%s%s"), _T(LOG_CALL_CARD), _T(LOG_SUCCESS));
	//show_log(strlog);
}

void CYAServerDlg::parse_json_data_clear_card( const char* sz )
{
	Json::Value root;
	Json::Reader reader;
	CString strlog = _T("");
	if (!reader.parse(sz,root)){
		strlog.Format(_T("%s%s"), _T(LOG_CLEAR_CARD), _T(LOG_FAIL));
		show_log(strlog);
		return ; 
	}
	if(root.isNull() || !root.isArray()){
		return; 
	}
	int card_type_id, edit_type_id;
	string cardid = "";
	for(unsigned int i = 0; i < root.size(); i++){
		cardid = root[i][JSON_KEY_EDIT_CARD_ID].asString();
		edit_type_id = root[i][JSON_KEY_EDIT_EDIT_TYPE_ID].asInt();
		CardMap::iterator it_card = mp_card_list_all.find(cardid);
		if(it_card != mp_card_list_all.end()){
			if(STATUS_ERROR == it_card->second->status_lost){
				// 升井
				it_card->second->up_time = time(NULL);
				it_card->second->PosState(PDT_UP);
				card_enter_mine(it_card->second);
				remove_card(cardid);
			}
		}		
	}
	strlog.Format(_T("%s%s"), _T(LOG_CLEAR_CARD), _T(LOG_SUCCESS));
	show_log(strlog);	

	if(m_log_recv_package){
		std::string strlog = sz;
		Log::write_log(FILE_TYPE::JSON_R, strlog, true);
	}
}

void CYAServerDlg::parse_json_data_deal_help( const char* sz )
{
	Json::Value root;
	Json::Reader reader;
	CString strlog;
	if (!reader.parse(sz,root)){
		strlog.Format(_T("%s%s"), _T(LOG_DEAL_HELP), _T(LOG_FAIL));
		show_log(strlog);
		return ; 
	}
	int card_type_id, edit_type_id;
	string cardid = root[JSON_KEY_EDIT_CARD_ID].asString();
	card_type_id = root[JSON_KEY_CARD_TYPE_ID].asInt();
	edit_type_id = root[JSON_KEY_EDIT_EDIT_TYPE_ID].asInt();

	CardMap::iterator it_card = mp_card_list_help->find(cardid);
	if(it_card != mp_card_list_help->end()){
		it_card->second->status_help = STATUS_HELP_DEALED;
	}
	strlog.Format(_T("%s%s"), _T(LOG_DEAL_HELP), _T(LOG_SUCCESS));
	show_log(strlog);

	if(m_log_recv_package){
		std::string strlog = sz;
		Log::write_log(FILE_TYPE::JSON_R, strlog, true);
	}
}

/*
* 处理web端发送的修改红绿灯颜色功能
* 
* param
*		data	---		前端json
*
* return
*		成功执行返回0，失败返回1
*/
int CYAServerDlg::parse_json_data_set_light_color(message::ptr const& data)
{
	//解析字符串后，对红绿灯进行控制
	//如果控制失败，则报警
	std::string strUserId = "";
	int task_id = 0;
	int obj_type = 0, ctrl_type = 0, lights_state = 0;

	map<string,message::ptr> data_map = data->get_map()[JSON_ROOT_KEY_DATA]->get_map();

	task_id		 = data_map[JSON_KEY_CALL_LIGHT_TASK_ID]->get_int();
	strUserId    = data_map[JSON_KEY_CALL_LIGHT_USER_ID]->get_string();
	obj_type	 = data_map[JSON_KEY_CALL_LIGHT_OBJ_TYPE]->get_int();
	ctrl_type	 = data_map[JSON_KEY_CALL_LIGHT_CTRL_TYPE]->get_int();
	lights_state = data_map[JSON_KEY_CALL_LIGHT_LIGHT_STATE]->get_int(); // 红、绿

	if(obj_type == LIGHTS_SELECT_TYPE::LST_SOME_LIGHTS ){
		vector<message::ptr> lights = data_map[JSON_KEY_CALL_LIGHT_LIGHTS]->get_vector();
		//获取每个灯进行控制
		vector<message::ptr>::const_iterator it_light = lights.begin();
		for (;it_light != lights.end();++it_light){
			int nLightId = 0;
			//获得灯id
			nLightId = (*it_light)->get_map()[JSON_KEY_CALL_LIGHT_ID]->get_int();		
			add_light_to_call_list((LIGHTS_SELECT_TYPE)obj_type, (LIGHT_COLOR)lights_state, (LIGHT_CTRL_STATE)ctrl_type, task_id, (LIGHT_SHAPE)lights_state,nLightId);
		}
	}else{
		add_light_to_call_list((LIGHTS_SELECT_TYPE)obj_type, (LIGHT_COLOR)lights_state, (LIGHT_CTRL_STATE)ctrl_type, task_id,(LIGHT_SHAPE)lights_state, 0);
	}

	send_call_light();

	return 0;
}
/*
* web端发起请求统计总数的详细列表
*/
int CYAServerDlg::parse_json_data_request_counts_info(message::ptr const& data)
{
	int req_type = -1;
	int area_id = -1;
	std::string req_user = "";
	std::string req_time = "";
	std::string req_task_id = "";

	map<string,message::ptr> data_map = data->get_map()[JSON_ROOT_KEY_DATA]->get_map();

	req_user = data_map[JSON_KEY_REQ_COUNTS_USER]->get_string();
	req_type = data_map[JSON_KEY_REQ_COUNTS_TYPE]->get_int();
	area_id  = data_map[JSON_KEY_EVENT_AREA_ID]->get_int();
	req_time = data_map[JSON_KEY_REQ_COUNTS_TIME]->get_string();
	req_task_id = data_map[JSON_KEY_CALL_LIGHT_TASK_ID]->get_string();

	Json::Value ret_data;

	if (req_type == REQUEST_ALL_OVER_TIME_PERSON 
		|| req_type == REQUEST_SPECIAL_ERROR_PERSON 
		|| req_type == REQUEST_ALL_OVER_TIME_VEHICLE
		|| req_type == REQUEST_ALL_OVER_PERSON
		|| req_type == REQUEST_ALL_OVER_VEHICLE)
	{
		ret_data = get_json_count_list(req_type,0);
	} 
	else
	{
		if (area_id != 0)
		{
			ret_data = get_json_count_list(req_type,area_id);
		} 
		else
		{
			ret_data = get_json_count_list(req_type,0);
		}
	}

	if (ret_data.size() > 0)
	{
		Json::Value root;
		root[JSON_ROOT_KEY_CMD] = JSON_KEY_RESPONSE_COUNTS_DETAIL;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;

		Json::Value data;
		data[JSON_KEY_REQ_COUNTS_USER] = req_user;
		data[JSON_KEY_REQ_COUNTS_TYPE] = req_type;
		data[JSON_KEY_ALARM_AREA_ID]   = area_id;
		data[JSON_KEY_ALARM_DETAIL] = ret_data;
		data[JSON_KEY_CALL_LIGHT_TASK_ID] = req_task_id;
		root[JSON_ROOT_KEY_DATA] = data;
		if (root.size() > 0)
		{
			std::string ret = "";
			ret = root.toFastString();
			if (ret != "")
			{
				send_json_data(JSON_CMD_VALUE_PUSH,ret);
			}
		}		
	}

	return 0;
}

void CYAServerDlg::deal_call_edit_map(int id, EDIT_TYPE_ID edit_type_id)
{
	CString strlog = _T("");
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			init_map(id);
			break;
		}
	case ET_UPDATE:
		{
			init_map(id);
			break;
		}
	case ET_DELETE:
		{
			MapInfoMap::iterator it_map = mp_map_list.find(id);
			if(it_map != mp_map_list.end()){
				mp_map_list.erase(it_map);
			}
			break;
		}
	default:
		break;
	}
	strlog.Format(_T("%s%s"), _T(LOG_EDIT_MAP), _T(LOG_SUCCESS));
	show_log(strlog);
}

void CYAServerDlg::deal_call_edit_area(int id, EDIT_TYPE_ID edit_type_id)
{
	CString strlog;
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			init_area(id);
			break;
		}
	case ET_UPDATE:
		{
			init_area(id);
			break;
		}
	case ET_DELETE:
		{
			AreaMap::iterator it_area = mp_area_list.find(id);
			MapInfoMap::iterator it_map = mp_map_list.find(it_area->second->map_id);
			if(it_map != mp_map_list.end()){
				AreaMap::iterator it_map_area = it_map->second->map_area_list.find(id);
				it_map->second->map_area_list.erase(it_map_area);
			}
			if(it_area != mp_area_list.end()){
				mp_area_list.erase(it_area);
			}

			it_area = mp_area_over_count_person->find(id);
			if(it_area != mp_area_over_count_person->end()){
				mp_area_over_count_person->erase(it_area);
			}
			it_area = mp_area_over_time_person->find(id);
			if(it_area != mp_area_over_time_person->end()){
				mp_area_over_time_person->erase(it_area);
			}
			it_area = mp_area_forbidden_person->find(id);
			if(it_area != mp_area_forbidden_person->end()){
				mp_area_forbidden_person->erase(it_area);
			}
			it_area = mp_area_over_count_vehicle->find(id);
			if(it_area != mp_area_over_count_vehicle->end()){
				mp_area_over_count_vehicle->erase(it_area);
			}
			it_area = mp_area_over_time_vehicle->find(id);
			if(it_area != mp_area_over_time_vehicle->end()){
				mp_area_over_time_vehicle->erase(it_area);
			}
			it_area = mp_area_forbidden_vehicle->find(id);
			if(it_area != mp_area_forbidden_vehicle->end()){
				mp_area_forbidden_vehicle->erase(it_area);
			}
			break;
		}
	default:
		break;
	}
	strlog.Format(_T("%s%s"), _T(LOG_EDIT_AREA), _T(LOG_SUCCESS));
	show_log(strlog);
}

void CYAServerDlg::deal_call_edit_reader(int id, EDIT_TYPE_ID edit_type_id)
{
	CString strlog;
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			init_reader(id);
#ifdef ALGORITHM_TYPE_TOF
			init_all_readers_coverage();
#elif defined ALGORITHM_TYPE_TDOA
			init_tdoa_all_readers_coverage(id);
#endif
			break;
		}
	case ET_UPDATE:
		{
			init_reader(id);
#ifdef ALGORITHM_TYPE_TOF
			init_all_readers_coverage();
#elif defined ALGORITHM_TYPE_TDOA
			init_tdoa_all_readers_coverage(id);
#endif
			break;
		}
	case ET_DELETE:
		{
			ReaderMap::iterator it_reader = mp_reader_list.find(id);
			MapInfoMap::iterator it_map = mp_map_list.find(it_reader->second->map_id);
			if(it_map != mp_map_list.end()){
				ReaderMap::iterator it_map_reader = it_map->second->map_reader_list.find(id);
				if(it_map_reader != it_map->second->map_reader_list.end()){
					it_map->second->map_reader_list.erase(it_map_reader);
				}
			}
			if(it_reader != mp_reader_list.end()){
				mp_reader_list.erase(it_reader);
			}
			break;
		}
	default:
		break;
	}
	strlog.Format(_T("%s%s"), _T(LOG_EDIT_READER), _T(LOG_SUCCESS));
	show_log(strlog);
}

void CYAServerDlg::deal_call_edit_card(string id, EDIT_TYPE_ID edit_type_id)
{
	CString strlog;
	CardMap::iterator it_card = mp_card_list_all.find(id);
	if(it_card == mp_card_list_all.end()){
		return;
	}
	int card_type_id = it_card->second->card_type;
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			if(CT_VEHICLE == card_type_id){
				init_vehicle(id, true);
			}else if(CT_PERSON == card_type_id) {
				init_staffer(id, true);
			}else if(CT_ADHOC == card_type_id){
				init_adhoc(id, true);
			}
			break;
		}
	case ET_UPDATE:
		{
			if(CT_VEHICLE == card_type_id){
				init_vehicle(id, true);
			}else if(CT_PERSON == card_type_id) {
				init_staffer(id, true);
			}else if(CT_ADHOC == card_type_id){
				init_adhoc(id, true);
			}
			break;
		}
	case ET_DELETE:
		{
			remove_card(id);
			break;
		}
	default:
		break;
	}
	strlog.Format(_T("%s%s"), _T(LOG_EDIT_CARD), _T(LOG_SUCCESS));
	show_log(strlog);
}

void CYAServerDlg::deal_call_edit_staff(string id, EDIT_TYPE_ID edit_type_id)
{
	CString strlog;
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			init_staffer(id);
			break;
		}
	case ET_UPDATE:
		{
			init_staffer(id);
			break;
		}
	case ET_DELETE:
		{
			string cardid = "";
			CardMap::iterator it_card = mp_card_list_down_person.begin();
			for(; it_card != mp_card_list_down_person.end(); ++it_card){
				if(it_card->second->id == id){
					cardid = it_card->second->card_id;
					break;
				}
			}
			remove_card(cardid);
			break;
		}
	default:
		break;
	}
	strlog.Format(_T("%s%s"), _T(LOG_EDIT_STAFFER), _T(LOG_SUCCESS));
	show_log(strlog);
}

void CYAServerDlg::deal_call_edit_vehicle(string id, EDIT_TYPE_ID edit_type_id)
{
	CString strlog;
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			init_vehicle(id);
			break;
		}
	case ET_UPDATE:
		{
			init_vehicle(id);
			break;
		}
	case ET_DELETE:
		{
			string cardid = "";
			CardMap::iterator it_card = mp_card_list_down_vehicle.begin();
			for(; it_card != mp_card_list_down_vehicle.end(); ++it_card){
				if(it_card->second->id == id){
					cardid = it_card->second->card_id;
					break;
				}
			}
			remove_card(cardid);
			break;
		}
	default:
		break;
	}
	strlog.Format(_T("%s%s"), _T(LOG_EDIT_VEHICLE), _T(LOG_SUCCESS));
	show_log(strlog);
}

void CYAServerDlg::deal_call_edit_adhoc(string id, EDIT_TYPE_ID edit_type_id)
{
	CString strlog;
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			init_adhoc(id);
			break;
		}
	case ET_UPDATE:
		{
			init_adhoc(id);
			break;
		}
	case ET_DELETE:
		{
			string cardid = "";
			CardMap::iterator it_card = mp_card_list_down_adhoc.begin();
			for(; it_card != mp_card_list_down_adhoc.end(); ++it_card){
				if(it_card->second->id == id){
					cardid = it_card->second->card_id;
					break;
				}
			}
			remove_card(cardid);
			break;
		}
	default:
		break;
	}
	strlog.Format(_T("%s%s"), _T(LOG_EDIT_ADHOC), _T(LOG_SUCCESS));
	show_log(strlog);
}

int CYAServerDlg::deal_call_edit_section(int id,EDIT_TYPE_ID edit_type_id)
{
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			init_section(id);
			break;
		}
	case ET_UPDATE:
		{
			init_section(id);
			break;
		}
	case ET_DELETE:
		{
			//删除路段后要将硐室表和灯组表中灯的路段信息改写
			ChamberMap::iterator it_chamber = mp_chamber_list.begin();
			for (;it_chamber != mp_chamber_list.end();++it_chamber)
			{
				if (it_chamber->second->m_nSectionID == id)
				{
					it_chamber->second->m_nSectionID = 0;
					break;
				}
			}

			LightGroupMap::iterator it_light_group = mp_light_group_list.begin();
			for (;it_light_group != mp_light_group_list.end();++it_light_group)
			{
				if (it_light_group->second->m_nSectionId == id)
				{
					it_light_group->second->m_nSectionId = 0;
					break;
				}
			}

			//删除路段信息
			SectionMap::iterator it_section = mp_section_list.find(id);
			if (it_section != mp_section_list.end())
			{
				mp_section_list.erase(it_section);
			}


			break;
		}
	default:
		break;
	}

	CString cstrLog = _T("");
	cstrLog.Format(_T("%s%s"), _T(LOG_EDIT_SECTION), _T(LOG_SUCCESS));
	show_log(cstrLog);

	return 0;
}

int CYAServerDlg::deal_call_edit_light(int id,EDIT_TYPE_ID edit_type_id)
{
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			init_traffic_lights(id);
			break;
		}
	case ET_UPDATE:
		{
			init_traffic_lights(id);
			break;
		}
	case ET_DELETE:
		{
			bool bFind = false;
			//灯组中删除
			LightGroupMap::iterator it_light_group = mp_light_group_list.begin();
			for (;it_light_group != mp_light_group_list.end();++it_light_group)
			{
				LightMap::iterator it_light = it_light_group->second->mp_lights_list.find(id);
				if (it_light != it_light_group->second->mp_lights_list.end())
				{
					it_light_group->second->mp_lights_list.erase(it_light);
					break;
				}
			}

			bFind = false;
			//路段中删除
			SectionMap::iterator it_section = mp_section_list.begin();
			for (;it_section != mp_section_list.end();++it_section)
			{
				LightMap::iterator it_light = it_section->second->mp_light_list.begin();
				for (;it_light != it_section->second->mp_light_list.end();++it_light)
				{
					if (it_light->second->m_nID == id)
					{
						bFind = true;
						it_section->second->mp_light_list.erase(it_light);
						break;
					}
				}
				if (bFind)
				{
					break;
				}
			}

			//从灯表中删除
			LightMap::iterator it = mp_light_list.find(id);
			if (it != mp_light_list.end())
			{
				mp_light_list.erase(it);
			}

			break;
		}
	default:
		break;
	}

	CString cstrLog = _T("");
	cstrLog.Format(_T("%s%s"), _T(LOG_EDIT_LIGHT), _T(LOG_SUCCESS));
	show_log(cstrLog);

	return 0;
}

int CYAServerDlg::deal_call_edit_chamber(int id,EDIT_TYPE_ID edit_type_id)
{
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			init_chamber(id);
			break;
		}
	case ET_UPDATE:
		{
			init_chamber(id);
			break;
		}
	case ET_DELETE:
		{
			//路段中删除硐室
			SectionMap::iterator it_section = mp_section_list.begin();
			for (;it_section != mp_section_list.end();++it_section)
			{
				ChamberMap::iterator it_chamber = mp_chamber_list.begin();
				for (;it_chamber != mp_chamber_list.end();++it_chamber)
				{
					if (it_chamber->second->m_nID == id)
					{
						mp_chamber_list.erase(it_chamber);
						break;
					}
				}
			}

			//硐室表中删除
			ChamberMap::iterator it = mp_chamber_list.find(id);
			if (it != mp_chamber_list.end())
			{
				mp_chamber_list.erase(it);
			}
			break;
		}
	default:
		break;
	}

	CString cstrLog = _T("");
	cstrLog.Format(_T("%s%s"), _T(LOG_EDIT_CHAMBER), _T(LOG_SUCCESS));
	show_log(cstrLog);

	return 0;
}

void CYAServerDlg::remove_card( string card_id )
{
	if(card_id.length() == 0)
		return;
	int card_type_id = 0;
	CardMap::iterator it_card = mp_card_list_all.find(card_id);
	if(it_card == mp_card_list_all.end()){
		return;
	}
	card_type_id = it_card->second->card_type;

	int map_id = 0,area_id = 0,dept_id = 0, occlevel_id = 0;
	map_id = it_card->second->map_id;
	area_id = it_card->second->area_id;
	dept_id = it_card->second->dept_id;
	occlevel_id = it_card->second->occlevel_id;

	// 避免状态重置
	// mp_card_list_all.erase(it_card);

	MapInfoMap::iterator it_map = mp_map_list.find(map_id);
	if(it_map != mp_map_list.end()){
		if(CT_VEHICLE == card_type_id){
			CardMap::iterator it_map_card = it_map->second->map_card_list_vehicle.find(card_id);
			if(it_map_card != it_map->second->map_card_list_vehicle.end()){
				it_map->second->map_card_list_vehicle.erase(it_map_card);
			}
		}else if(CT_PERSON == card_type_id){
			CardMap::iterator it_map_card = it_map->second->map_card_list_person.find(card_id);
			if(it_map_card != it_map->second->map_card_list_person.end()){
				it_map->second->map_card_list_person.erase(it_map_card);
			}
		}
	}
	AreaMap::iterator it_area = mp_area_list.find(area_id);
	if(it_area != mp_area_list.end()){
		if(CT_VEHICLE == card_type_id){
			CardMap::iterator it_area_card = it_area->second->area_card_list_vehicle->find(card_id);
			if(it_area_card != it_area->second->area_card_list_vehicle->end()){
				it_area->second->area_card_list_vehicle->erase(it_area_card);
			}
		}else if(CT_PERSON == card_type_id){
			CardMap::iterator it_area_card = it_area->second->area_card_list_person->find(card_id);
			if(it_area_card != it_area->second->area_card_list_person->end()){
				if (it_area_card->second->accelerate_state == 0)
				{
					it_area->second->area_card_list_person->erase(it_area_card);
				}
			}
		}
	}
	DeptMap::iterator it_dept = mp_dept_list.find(dept_id);
	if(it_dept != mp_dept_list.end()){
		if(CT_VEHICLE == card_type_id){
			CardMap::iterator it_dept_card = it_dept->second->dept_card_list_vehicle.find(card_id);
			if(it_dept_card != it_dept->second->dept_card_list_vehicle.end()){
				it_dept->second->dept_card_list_vehicle.erase(it_dept_card);
			}
		}else if(CT_PERSON == card_type_id){
			CardMap::iterator it_dept_card = it_dept->second->dept_card_list_person.find(card_id);
			if(it_dept_card != it_dept->second->dept_card_list_person.end()){
				it_dept->second->dept_card_list_person.erase(it_dept_card);
			}
		}
	}

	if(CT_VEHICLE == card_type_id){
		it_card = mp_card_list_down_vehicle.find(card_id);
		if(it_card != mp_card_list_down_vehicle.end()){			
			mp_card_list_down_vehicle.erase(it_card);			
		}
		it_card = mp_card_list_forbidden_vehicle->find(card_id);
		if(it_card != mp_card_list_forbidden_vehicle->end()){
			mp_card_list_forbidden_vehicle->erase(it_card);
		}
		it_card = mp_card_list_over_time_vehicle->find(card_id);
		if(it_card != mp_card_list_over_time_vehicle->end()){
			mp_card_list_over_time_vehicle->erase(it_card);
		}
		it_card = mp_card_list_area_over_time_vehicle->find(card_id);
		if(it_card != mp_card_list_area_over_time_vehicle->end()){
			mp_card_list_area_over_time_vehicle->erase(it_card);
		}
		it_card = mp_card_list_over_speed_vehicle->find(card_id);
		if(it_card != mp_card_list_over_speed_vehicle->end()){
			mp_card_list_over_speed_vehicle->erase(it_card);
		}
	}else if(CT_PERSON == card_type_id) {
		it_card = mp_card_list_down_person.find(card_id);
		if(it_card != mp_card_list_down_person.end()){
			mp_card_list_down_person.erase(it_card);
		}
		it_card = mp_card_list_over_time_person->find(card_id);
		if(it_card != mp_card_list_over_time_person->end()){
			mp_card_list_over_time_person->erase(it_card);
		}
		it_card = mp_card_list_forbidden_person->find(card_id);
		if(it_card != mp_card_list_forbidden_person->end()){
			mp_card_list_forbidden_person->erase(it_card);
		}
		it_card = mp_card_list_help->find(card_id);
		if(it_card != mp_card_list_help->end()){
			mp_card_list_help->erase(it_card);
		}
		it_card = mp_card_list_area_over_time_person->find(card_id);
		if(it_card != mp_card_list_area_over_time_person->end()){
			mp_card_list_area_over_time_person->erase(it_card);
		}
		it_card = mp_card_list_over_count_person->find(card_id);
		if (it_card != mp_card_list_over_count_person->end())
		{
			mp_card_list_over_count_person->erase(it_card);
		}
		OccLevelMap::iterator it_level = mp_occlevel_list.find(occlevel_id);
		if(it_level != mp_occlevel_list.end())
		{
			CardMap::iterator it_level_card = it_level->second->level_card_list_person.find(card_id);
			if(it_level_card != it_level->second->level_card_list_person.end())
			{
				it_level->second->level_card_list_person.erase(it_level_card);
			}
		}
	}

	//从事件表中删除此事件
	for (EventMap::iterator it_event = mp_event_list->begin();it_event != mp_event_list->end();)
	{
		if (it_event->second->obj_id == card_id)
		{
			//应该先加上事件结束处理逻辑，再删除
			it_event = mp_event_list->erase(it_event);
		}else{
			++it_event;
		}
	}
}

void CYAServerDlg::calculate_card_postion_by_tof(std::shared_ptr<Card> card) // 计算card坐标
{
	int anchorNum = card->reader_id;
	card->x = card->p_reader->ant[card->antenna_id]->antenna_x;
	card->y = card->p_reader->ant[card->antenna_id]->antenna_y;
	card->z = card->p_reader->ant[card->antenna_id]->antenna_z;
	card->a = card->p_reader->ant[card->antenna_id]->antenna_angle;
	//card->area_id = card->p_reader->area_id;
	double sina = sin(card->a);
	double cosa = cos(card->a);
	std::shared_ptr<MapInfo> pMap = nullptr;
	MapInfoMap::iterator it = mp_map_list.find(card->map_id);
	if(it != mp_map_list.end()){
		pMap = it->second;
	}
	else
	{
		return;
	}

	double move_x = card->distance * cos(card->a) / pMap->map_scale;
	double move_y = card->distance * sin(card->a) / pMap->map_scale;
	card->x = card->x + move_x;
	card->y = card->y + move_y;

	return;
}

void CYAServerDlg::process_driving_face_start_service(std::shared_ptr<Card> card)
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_236);
	
	char sql[LENGTH_SQL] = {'\0'};
	std::string cur_shift_start_time = "";
	std::string cur_shift_end_time = "";
	
	int shift_id = 0;
	cur_shift_start_time = CFunctions::time_t2string(GetCurShiftStartTime(shift_id));
	cur_shift_end_time = CFunctions::time_t2string(GetCurShiftEndTime());
	
	std::shared_ptr<DrivingfaceRender> pDrivingfaceRender = nullptr;
	DrivingfaceRenderMap::iterator it = mp_driving_face_render_list.find(501);		
	if(it == mp_driving_face_render_list.end()){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_237);
		return;
	}
	else
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_238);
		pDrivingfaceRender = it->second;
		int drivingface_id = pDrivingfaceRender->drivingface_id;
		std::shared_ptr<MapInfo> pMap = nullptr;
		MapInfoMap::iterator it = mp_map_list.find(card->map_id);
		if(it != mp_map_list.end()){
			pMap = it->second;
		}
		else
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_239);
			return;
		}
		
		float last_total_finsh_length = 0;
		float cur_total_finish_length = 0;
		float cur_shift_finish_length = 0;
		float diff_dis_flag = 0;

        last_total_finsh_length = sqrt(pow(card->driving_face_cur_shift_x - pDrivingfaceRender->x, 2)
			+ pow(card->driving_face_cur_shift_y - pDrivingfaceRender->y, 2)
			+ pow(card->driving_face_cur_shift_z - pDrivingfaceRender->z, 2)) * card->map_scale;
		
		cur_total_finish_length = sqrt(pow(card->x - pDrivingfaceRender->x, 2)
			+ pow(card->y - pDrivingfaceRender->y, 2)
			+ pow(card->z - pDrivingfaceRender->z, 2)) * card->map_scale;

		cur_shift_finish_length = sqrt(pow(card->x - card->driving_face_cur_shift_start_x, 2)
			+ pow(card->y - card->driving_face_cur_shift_start_y, 2)
			+ pow(card->z - card->driving_face_cur_shift_start_z, 2)) * card->map_scale;

		diff_dis_flag = (cur_total_finish_length - last_total_finsh_length) * pMap->map_scale;
		if(diff_dis_flag >= 0)
		{
			card->driving_face_cur_shift_x = card->x;
			card->driving_face_cur_shift_y = card->y;
			card->driving_face_cur_shift_z = card->z;
		}
		else
		{
		    cur_total_finish_length = last_total_finsh_length;
		    cur_shift_finish_length = sqrt(pow(card->driving_face_cur_shift_x - card->driving_face_cur_shift_start_x, 2)
			+ pow(card->driving_face_cur_shift_y - card->driving_face_cur_shift_start_y, 2)
			+ pow(card->driving_face_cur_shift_z - card->driving_face_cur_shift_start_z, 2)) * card->map_scale;
		}
		

		sprintf_s(sql, LENGTH_SQL, 
			"update his_drivingface_his set end_time = '%s', finsh_length=%.3f, cur_finish_length=%.3f, end_x = %.3f, end_y=%.3f, end_z=%.3f  where card_id = %s and start_time = '%s';",
			cur_shift_end_time.c_str(), 
			cur_total_finish_length, 
			cur_shift_finish_length, 
			card->driving_face_cur_shift_x, 
			card->driving_face_cur_shift_y, 
			card->driving_face_cur_shift_z, 
			card->card_id.c_str(), 
			cur_shift_start_time.c_str());
		
		execute_sql(sql);
		debug_print_syslog(0, "driving face update sql: %s", sql);
		card->is_driving_face_start = 1;
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_240);
		update_driving_face_data();
	}
	return;
}

void CYAServerDlg::send_drivingface_card_position_json()
{
    std::shared_ptr<Card> card = nullptr;
	string str_card_id = CFunctions::getstrwithzero(2, 3) + CFunctions::getstrwithzero(1014, 10);
	
	CardMap::iterator it_vehicle = mp_card_list_all.find(str_card_id);
	if(it_vehicle != mp_card_list_all.end())
	{
		send_json_data(JSON_CMD_VALUE_PUSH, get_json_drivingface_card_position(it_vehicle->second));
		debug_print_syslog(0, "find drivingface card: %s.", it_vehicle->second->card_id.c_str());
		update_driving_face_data();
	}
	debug_print_syslog(0, "period send drivingface card stat.");
}

void CYAServerDlg::write_drivingface_shift_start_data(std::shared_ptr<Card> card)
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_249);
	//add his_drivingface_his
	char sql[LENGTH_SQL] = {'\0'};
	
	std::string strCurShiftStartTime = "";
	std::string strCurShiftEndTime = "";
	
	int shift_id = 0;
	strCurShiftStartTime = CFunctions::time_t2string(GetCurShiftStartTime(shift_id));
	time_t end_time = GetCurShiftEndTime();
	strCurShiftEndTime = CFunctions::time_t2string(end_time);
	
	std::shared_ptr<DrivingfaceRender> pDrivingfaceRender = nullptr;
	DrivingfaceRenderMap::iterator it = mp_driving_face_render_list.find(501);		
	if(it == mp_driving_face_render_list.end())
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_250);
		return;
	}
	else
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_251);
		pDrivingfaceRender = it->second;
		int drivingface_id = pDrivingfaceRender->drivingface_id;
		float last_total_finsh_length = 0;
		float cur_total_finish_length = 0;
		float cur_shift_finish_length = 0;
		float diff_dis_flag = 0;

        last_total_finsh_length = sqrt(pow(card->driving_face_cur_shift_start_x - pDrivingfaceRender->x, 2)
			+ pow(card->driving_face_cur_shift_start_y - pDrivingfaceRender->y, 2)
			+ pow(card->driving_face_cur_shift_start_z - pDrivingfaceRender->z, 2)) * card->map_scale;;
		
		cur_total_finish_length = sqrt(pow(card->x - pDrivingfaceRender->x, 2)
			+ pow(card->y - pDrivingfaceRender->y, 2)
			+ pow(card->z - pDrivingfaceRender->z, 2)) * card->map_scale;

		
		cur_shift_finish_length = sqrt(pow(card->x - card->driving_face_cur_shift_start_x, 2)
					+ pow(card->y - card->driving_face_cur_shift_start_y, 2)
					+ pow(card->z - card->driving_face_cur_shift_start_z, 2)) * card->map_scale;
		
		std::shared_ptr<MapInfo> pMap = nullptr;
		MapInfoMap::iterator it = mp_map_list.find(card->map_id);
		if(it != mp_map_list.end()){
			pMap = it->second;
		}
		else
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_252);
			return;
		}

		diff_dis_flag = (cur_total_finish_length - last_total_finsh_length) * pMap->map_scale;
        #if 0
		if(diff_dis_flag >= 0)
		{
			card->driving_face_cur_shift_x = card->x;
			card->driving_face_cur_shift_y = card->y;
			card->driving_face_cur_shift_z = card->z;
			card->driving_face_cur_shift_start_x = card->driving_face_cur_shift_x;
			card->driving_face_cur_shift_start_y = card->driving_face_cur_shift_y; 
			card->driving_face_cur_shift_start_z = card->driving_face_cur_shift_z;
		}
		else
		{
		    card->driving_face_cur_shift_start_x = card->driving_face_cur_shift_x;
			card->driving_face_cur_shift_start_y = card->driving_face_cur_shift_y; 
			card->driving_face_cur_shift_start_z = card->driving_face_cur_shift_z;
		    cur_total_finish_length = last_total_finsh_length;
		    cur_shift_finish_length = 0;
		}
		#endif
		sprintf_s(sql, LENGTH_SQL, 
 			"INSERT IGNORE INTO his_drivingface_his(drivingface_id, card_id, finsh_length, cur_finish_length, start_time, end_time, start_x, start_y, start_z, end_x, end_y, end_z) \
			VALUES(%d, %s, %.3f, %.3f, '%s', '%s', %.3f, %.3f, %.3f, %.3f, %.3f, %.3f);",  
			drivingface_id, 
			card->card_id.c_str(), 
			cur_total_finish_length, 
			0.0,
			strCurShiftStartTime.c_str(), 
			strCurShiftEndTime.c_str(), 
			card->driving_face_cur_shift_start_x, 
			card->driving_face_cur_shift_start_y, 
			card->driving_face_cur_shift_start_z,
			card->driving_face_cur_shift_x, 
			card->driving_face_cur_shift_y, 
			card->driving_face_cur_shift_z);
		execute_sql(sql);
		debug_print_syslog(0, "driving face shift start sql: %s", sql);
	}
	return;
}
void CYAServerDlg::driving_face_shift_start()
{
	string str_card_id = CFunctions::getstrwithzero(2, 3) + CFunctions::getstrwithzero(1014, 10);
	CardMap::iterator it_vehicle = mp_card_list_all.find(str_card_id);

	std::shared_ptr<Card> card = nullptr;
	if(it_vehicle != mp_card_list_all.end())
	{
		card = it_vehicle->second;
		if(card)
		{
		    //update shift start point
		    card->driving_face_cur_shift_start_x = card->driving_face_cur_shift_x;
			card->driving_face_cur_shift_start_y = card->driving_face_cur_shift_y; 
			card->driving_face_cur_shift_start_z = card->driving_face_cur_shift_z;
			
			write_drivingface_shift_start_data(card);
			store_driving_face_data();
		}
	}
	return;
}

void CYAServerDlg::write_drivingface_shift_end_data(std::shared_ptr<Card> card)
{
#if 0
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_253);
	//add his_drivingface_his
	char sql[LENGTH_SQL] = {'\0'};
	
	std::string cur_shift_start_time = "";
	std::string cur_shift_end_time = "";
	
	int shift_id = 0;
	cur_shift_start_time = CFunctions::time_t2string(GetCurShiftStartTime(shift_id));
	cur_shift_end_time = CFunctions::time_t2string(GetCurShiftEndTime());
	
	
	std::shared_ptr<DrivingfaceRender> pDrivingfaceRender = nullptr;
	DrivingfaceRenderMap::iterator it = mp_driving_face_render_list.find(card->reader_id);		
	if(it == mp_driving_face_render_list.end() || (1 != card->is_driving_face_start)){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_254);
		return;
	}
	else
	{
		pDrivingfaceRender = it->second;
		int drivingface_id = pDrivingfaceRender->drivingface_id;
		float  finsh_length = 0;
		float cur_finish_length = 0;
		finsh_length = sqrt(pow(card->x - pDrivingfaceRender->x, 2)
			+ pow(card->y - pDrivingfaceRender->y, 2)
			+ pow(card->z - pDrivingfaceRender->z, 2));
		cur_finish_length = sqrt(pow(card->x - card->driving_face_x, 2)
			+ pow(card->y - card->driving_face_y, 2)
			+ pow(card->z - card->driving_face_z, 2));
		std::shared_ptr<MapInfo> pMap = nullptr;
		MapInfoMap::iterator it = mp_map_list.find(card->map_id);
		if(it != mp_map_list.end()){
			pMap = it->second;
		}
		else
		{  
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_255);
			return;
		}
		finsh_length = finsh_length * pMap->map_scale;
		cur_finish_length = cur_finish_length * pMap->map_scale;
		
		if(card->driving_face_finsh_length <= finsh_length)
		{
			card->driving_face_cur_shift_finish_length = finsh_length - card->driving_face_finsh_length;
		}
		else
		{
		    finsh_length = card->driving_face_finsh_length;
			card->driving_face_cur_shift_finish_length = 0;
		}
		
	    sprintf_s(sql, LENGTH_SQL, 
			"update his_drivingface_his set end_time = '%s', finsh_length=%.3f, cur_finish_length=%.3f, end_x = %.3f, end_y=%.3f, end_z=%.3f  where card_id = %s and start_time = '%s';",
			strEndTime.c_str(),finsh_length, card->driving_face_cur_shift_finish_length, card->x, card->y, card->z, card->card_id.c_str(), strStartTime.c_str());
		
		execute_sql(sql);
		debug_print_syslog(0, "driving face upmine sql: %s", sql);
		card->is_driving_face_start = 0;
		card->state_moving = 0;
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_256);
	}
#endif
	return;
}


void CYAServerDlg::driving_face_shift_end()
{
	//store_driving_face_data();
	//load_his_driving_face_card_postion();//掘进面卡所在位置
	//init_drivingface_card_curshift_position();
	//load_his_driving_face_card_state();
	return;
}


void CYAServerDlg::process_driving_face_end_service(std::shared_ptr<Card> card)
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_241);
	char sql[LENGTH_SQL] = {'\0'};

	std::string cur_shift_start_time = "";
	std::string cur_shift_end_time = "";
	
	int shift_id = 0;
	cur_shift_start_time = CFunctions::time_t2string(GetCurShiftStartTime(shift_id));
	cur_shift_end_time = CFunctions::time_t2string(GetCurShiftEndTime());
	
	std::shared_ptr<DrivingfaceRender> pDrivingfaceRender = nullptr;
	DrivingfaceRenderMap::iterator it = mp_driving_face_render_list.find(501);
	card->is_driving_face_start = 0;
	if(it == mp_driving_face_render_list.end())
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_242);
		return;
	}
	else
	{
		pDrivingfaceRender = it->second;
		int drivingface_id = pDrivingfaceRender->drivingface_id;
		
		float last_total_finsh_length = 0;
		float cur_total_finish_length = 0;
		float cur_shift_finish_length = 0;
		
		last_total_finsh_length = sqrt(pow(card->driving_face_cur_shift_x - pDrivingfaceRender->x, 2)
			+ pow(card->driving_face_cur_shift_y - pDrivingfaceRender->y, 2)
			+ pow(card->driving_face_cur_shift_z - pDrivingfaceRender->z, 2)) * card->map_scale;
		
		cur_total_finish_length = sqrt(pow(card->x - pDrivingfaceRender->x, 2)
			+ pow(card->y - pDrivingfaceRender->y, 2)
			+ pow(card->z - pDrivingfaceRender->z, 2)) * card->map_scale;

		cur_shift_finish_length = sqrt(pow(card->x - card->driving_face_cur_shift_start_x, 2)
			+ pow(card->y - card->driving_face_cur_shift_start_y, 2)
			+ pow(card->z - card->driving_face_cur_shift_start_z, 2)) * card->map_scale;
		
		std::shared_ptr<MapInfo> pMap = nullptr;
		MapInfoMap::iterator it = mp_map_list.find(card->map_id);
		if(it != mp_map_list.end()){
			pMap = it->second;
		}
		else
		{  
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_243);
			return;
		}
		float diff_dis_flag = 0;
		diff_dis_flag = (cur_total_finish_length - last_total_finsh_length) * pMap->map_scale;
		if(diff_dis_flag >= 0)
		{
			card->driving_face_cur_shift_x = card->x;
			card->driving_face_cur_shift_y = card->y;
			card->driving_face_cur_shift_z = card->z;
		}
		else
		{
		    cur_total_finish_length = last_total_finsh_length;
		    cur_shift_finish_length = sqrt(pow(card->driving_face_cur_shift_x - card->driving_face_cur_shift_start_x, 2)
			+ pow(card->driving_face_cur_shift_y - card->driving_face_cur_shift_start_y, 2)
			+ pow(card->driving_face_cur_shift_z - card->driving_face_cur_shift_start_z, 2)) * card->map_scale;
		}

        sprintf_s(sql, LENGTH_SQL, 
			"update his_drivingface_his set end_time = '%s', finsh_length=%.3f, cur_finish_length=%.3f, end_x = %.3f, end_y=%.3f, end_z=%.3f  where card_id = %s and start_time = '%s';",
			cur_shift_end_time.c_str(), 
			cur_total_finish_length, 
			cur_shift_finish_length, 
			card->driving_face_cur_shift_x,
			card->driving_face_cur_shift_y,
			card->driving_face_cur_shift_z,
			card->card_id.c_str(), 
			cur_shift_start_time.c_str());
		
		execute_sql(sql);
		debug_print_syslog(0, "driving face end sql: %s", sql);
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_244);
		update_driving_face_data();
	}
	return;
}

void CYAServerDlg::store_driving_face_data()
{
    LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_259);
	char sql[LENGTH_SQL] = {'\0'};
	int shift_id = 0;
	string str_card_id = CFunctions::getstrwithzero(2, 3) + CFunctions::getstrwithzero(1014, 10);
	std::string s = CFunctions::time_t2string(this->GetCurShiftStartTime(shift_id));
    CardMap::iterator it = mp_card_list_all.find(str_card_id);
	
	std::shared_ptr<Card> card = nullptr;
	if(it != mp_card_list_all.end())
	{
	    LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_260);
        float last_total_finsh_length = 0;
    	float cur_total_finish_length = 0;
    	float cur_shift_finish_length = 0;
		float dis_diff_flag = 0;
    	std::shared_ptr<DrivingfaceRender> pDrivingfaceRender = nullptr;
		card = it->second;
    	DrivingfaceRenderMap::iterator it_render = mp_driving_face_render_list.find(501);		
    	if(it_render == mp_driving_face_render_list.end())
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_261);
    		return;
    	}
    	else
    	{
    	    LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_262);
    	    pDrivingfaceRender = it_render->second;
			
            last_total_finsh_length = sqrt(pow(card->driving_face_cur_shift_x - pDrivingfaceRender->x, 2)
    			+ pow(card->driving_face_cur_shift_y - pDrivingfaceRender->y, 2)
    			+ pow(card->driving_face_cur_shift_z - pDrivingfaceRender->z, 2)) * card->map_scale;
    		
    		cur_total_finish_length = sqrt(pow(card->x - pDrivingfaceRender->x, 2)
    			+ pow(card->y - pDrivingfaceRender->y, 2)
    			+ pow(card->z - pDrivingfaceRender->z, 2)) * card->map_scale;

			cur_shift_finish_length = sqrt(pow(card->x - card->driving_face_cur_shift_start_x, 2)
			    + pow(card->y - card->driving_face_cur_shift_start_y, 2)
			    + pow(card->z - card->driving_face_cur_shift_start_z, 2)) * card->map_scale;
			
    		dis_diff_flag = (cur_total_finish_length - last_total_finsh_length) * card->map_scale;
    		if(dis_diff_flag >= 0)
    		{
    			card->driving_face_cur_shift_x = card->x;
    			card->driving_face_cur_shift_y = card->y;
    			card->driving_face_cur_shift_z = card->z;
    		}
    		else
    		{
    		    cur_total_finish_length = last_total_finsh_length;
    		    cur_shift_finish_length = sqrt(pow(card->driving_face_cur_shift_x - card->driving_face_cur_shift_start_x, 2)
			        + pow(card->driving_face_cur_shift_y - card->driving_face_cur_shift_start_y, 2)
			        + pow(card->driving_face_cur_shift_z - card->driving_face_cur_shift_start_z, 2)) * card->map_scale;
    		}
    	}
		sprintf_s(
		sql, 
		LENGTH_SQL,
		"insert IGNORE into his_drivingface_shift_finish_length (drivingface_id, card_id, total_length, shift_id, finish_length, cur_time) values(%d, %s, %.3f, %d, %.3f,'%s');",
        3305,
		card->card_id.c_str(),
		cur_total_finish_length,
		this->cur_shift_id,
		cur_shift_finish_length,
		s.c_str());
		debug_print_syslog(0, "store driving face data sql: %s", sql);
	}
	debug_print_syslog(0, "store driving face data execute sql: %s", sql);
	execute_sql(sql);

	return;
}

void CYAServerDlg::update_driving_face_data()
{
    LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_263);
	char sql[LENGTH_SQL] = {'\0'};
	int shift_id = 0;
	std::string cur_shift_start_time = CFunctions::time_t2string(this->GetCurShiftStartTime(shift_id));
    string str_card_id = CFunctions::getstrwithzero(2, 3) + CFunctions::getstrwithzero(1014, 10);
	
	CardMap::iterator it = mp_card_list_all.find(str_card_id);
	
	std::shared_ptr<Card> card = nullptr;
	if(it != mp_card_list_all.end())
	{
	    LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_264);
        float last_total_finsh_length = 0;
    	float cur_total_finish_length = 0;
    	float cur_shift_finish_length = 0;
		float dis_diff_flag = 0;
		
    	std::shared_ptr<DrivingfaceRender> pDrivingfaceRender = nullptr;
		card = it->second;
    	DrivingfaceRenderMap::iterator it_render = mp_driving_face_render_list.find(501);		
    	if(it_render == mp_driving_face_render_list.end())
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_265);
    		return;
    	}
    	else
    	{
    	    LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_266);
    	    pDrivingfaceRender = it_render->second;
            last_total_finsh_length = sqrt(pow(card->driving_face_cur_shift_x - pDrivingfaceRender->x, 2)
    			+ pow(card->driving_face_cur_shift_y - pDrivingfaceRender->y, 2)
    			+ pow(card->driving_face_cur_shift_z - pDrivingfaceRender->z, 2)) * card->map_scale;
    		
    		cur_total_finish_length = sqrt(pow(card->x - pDrivingfaceRender->x, 2)
    			+ pow(card->y - pDrivingfaceRender->y, 2)
    			+ pow(card->z - pDrivingfaceRender->z, 2)) * card->map_scale;
			
    		cur_shift_finish_length = sqrt(pow(card->x - card->driving_face_cur_shift_start_x, 2)
			    + pow(card->y - card->driving_face_cur_shift_start_y, 2)
			    + pow(card->z - card->driving_face_cur_shift_start_z, 2)) * card->map_scale;
			
    		dis_diff_flag = (cur_total_finish_length - last_total_finsh_length) * card->map_scale;
    		if(dis_diff_flag >= 0)
    		{
    			card->driving_face_cur_shift_x = card->x;
    			card->driving_face_cur_shift_y = card->y;
    			card->driving_face_cur_shift_z = card->z;
    		}
    		else
    		{
    		    cur_total_finish_length = last_total_finsh_length;
    		    cur_shift_finish_length = sqrt(pow(card->driving_face_cur_shift_x - card->driving_face_cur_shift_start_x, 2)
			        + pow(card->driving_face_cur_shift_y - card->driving_face_cur_shift_start_y, 2)
			        + pow(card->driving_face_cur_shift_z - card->driving_face_cur_shift_start_z, 2)) * card->map_scale;
    		}
    	}
		sprintf_s(
		sql, 
		LENGTH_SQL,
		"update his_drivingface_shift_finish_length set drivingface_id = '%d', card_id=%s, total_length=%.3f, shift_id = %d, finish_length=%.3f	where card_id = %s and cur_time = '%s';",
        3305,
		card->card_id.c_str(),
		cur_total_finish_length,
		shift_id,
		cur_shift_finish_length,
		card->card_id.c_str(),
		cur_shift_start_time.c_str());
		debug_print_syslog(0, "update driving face shift data sql: %s", sql);
	}
	debug_print_syslog(0, "update driving face shift data sql real: %s", sql);
	execute_sql(sql);

	return;
}


void CYAServerDlg::write_his_drivingface_real(std::shared_ptr<Card> card)
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_245);
	//add his_drivingface_his
	char sql[LENGTH_SQL] = {'\0'};
	time_t tCurTime;
	std::string strCurTime = "";

	tCurTime = time(NULL);
	strCurTime = CFunctions::time_t2string(tCurTime);
	std::shared_ptr<DrivingfaceRender> pDrivingfaceRender = nullptr;
	DrivingfaceRenderMap::iterator it = mp_driving_face_render_list.find(card->reader_id);		
	if(it == mp_driving_face_render_list.end()){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_246);
		return;
	}
	else
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_247);
		pDrivingfaceRender = it->second;
		int drivingface_id = pDrivingfaceRender->drivingface_id;
		float  finsh_length = 0;
		float cur_finish_length = 0;
		finsh_length = sqrt(pow(card->x - pDrivingfaceRender->x, 2)
			+ pow(card->y - pDrivingfaceRender->y, 2)
			+ pow(card->z - pDrivingfaceRender->z, 2));
		sprintf_s(sql, LENGTH_SQL, 
			"INSERT IGNORE INTO his_drivingface_real\
			(drivingface_id, card_id, map_id,area_id, state, dat_state_card, dat_state_boject_state, \
			average_speed, speed, x, y, z, cur_time)\
			VALUES(%d, '%s', %d, %d, '%d', '%d', '%d', %.3f, %.3f, %.3f, %.3f, %.3f, '%s');",  drivingface_id,
			card->card_id.c_str(), card->map_id, card->area_id, card->state, 0, 0, card->v, card->v,
			card->x, card->y, card->z, strCurTime.c_str());
		//execute_sql(sql);
		//debug_print_syslog(0, "driving face sql: %s", sql);
		ULONGLONG cur_time = ::GetTickCount();
		if(cur_time - card->drive_face_location_write_time > 20000)
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_240);
			execute_sql(sql);
			debug_print_syslog(0, "driving face sql: %s", sql);
			card->drive_face_location_write_time = cur_time;
		}
	}
	return;
}

void CYAServerDlg::save_card_postion(std::shared_ptr<Card> card /* Card* card*/ )
{
	if (abs(card->x - INVALID_COORDINATE / card->map_scale) < 1E-4 && abs(card->x - INVALID_COORDINATE/ card->map_scale) <1E-4)
	{
		//如果回到错误点
		return;
	}
	// 位置发生变化
	double moved_dist = sqrt(pow(card->x - card->stored_x, 2) + pow(card->y - card->stored_y, 2));

	if( moved_dist * card->map_scale < 1.0/2.0){ // 移动位置小于半米，不记录数据
		return ;
	}

	if (!card->is_first_location){
		card->mileage = moved_dist * card->map_scale/1000;
	}else{
		card->mileage = 0;
		card->is_first_location = false;
	}

	int t = card->x;	
	card->stored_x = card->x;
	card->stored_y = card->y;
	card->stored_z = card->z;

	//landmark ID
	_point card_point(card->x, card->y, card->z);
	int landmark_id = GetLandmarkID(card_point);
	card->landmark_id = landmark_id;
	_point landmark_point;
	int directory_id = NODIRECTORY;
	double distance = 0;
	LandmarkInfoMap::iterator itLandmark = mp_landmark_list.find(landmark_id);		
	if(itLandmark != mp_landmark_list.end())
	{
		landmark_point.x = itLandmark->second->x;
		landmark_point.y = itLandmark->second->y;
		landmark_point.z = itLandmark->second->z;

		directory_id = GetDirectionType(card_point, landmark_point, card->map_id);
		if(NODIRECTORY != directory_id ){
			distance = GetDistance(card_point, landmark_point) *card->map_scale;
		}
	}

	card->landmark_direction = directory_id;
	card->landmark_dis = distance;

	store_data_card(card, HIS_LOCATION);
}

void CYAServerDlg::save_card_postion_ex( std::shared_ptr<Card> card )
{
	//
	if(card->_storepostions.size() < 4)
	{
		return ;
	}

	_point p1, p2, p3, p4;

	p1.x = card->_storepostions.at(0)->x;
	p1.y = card->_storepostions.at(0)->y;
	p2.x = card->_storepostions.at(1)->x;
	p2.y = card->_storepostions.at(1)->y;
	p3.x = card->_storepostions.at(2)->x;
	p3.y = card->_storepostions.at(2)->y;
	p4.x = card->_storepostions.at(3)->x;
	p4.y = card->_storepostions.at(4)->y;

	int diffms = 0;
	int nCount = 0;
	if(IsInLine(p1, p2, p3)){
		diffms = CFunctions::TimeDiffMS(card->_storepostions.at(1)->save_time, card->_storepostions.at(0)->save_time);
		if(diffms < 1000)
		{ // 小于1秒

		}
		else
		{ // 计算需要补录的条数
			nCount = diffms / 700; 
		}

		card->_storepostions.pop_front();
		return ;
	}
}
/*
* 存储红绿灯信息到数据库
*
* param
*		light	---		红绿灯对象
*		tag		---		事件类型
* 
* return
*		函数正常执行返回0，否则返回1
*/
int CYAServerDlg::store_data_light(std::shared_ptr<Light> light,int tag)
{
	char sql[LENGTH_SQL] = {'\0'};
	time_t tCurTime;
	std::string strCurTime = "";
	std::string strStartTime = "";

	tCurTime = time(NULL);
	strCurTime = CFunctions::time_t2string(tCurTime);

	//1为网络故障，2为控制失败，3为灯故障
	int nAlarmTypeId = 0;
	switch (tag)
	{
	case ALARM_LIGHT_NETWORK_START:
	case ALARM_LIGHT_NETWORK_END:
		nAlarmTypeId = 1;
		break;
	case ALARM_LIGHT_CONTROL_FAILE:
		nAlarmTypeId = 2;
		break;
	case ALARM_LIGHT_FAULT_START:
	case ALARM_LIGHT_FAULT_END:
		nAlarmTypeId = 2;
		break;
	}

	switch (tag)
	{
	case ALARM_LIGHT_NETWORK_START://insert
	case ALARM_LIGHT_CONTROL_FAILE:
	case ALARM_LIGHT_FAULT_START:
		sprintf_s(
			sql,
			LENGTH_SQL,
			"insert IGNORE into his_alarm_light(light_id,alarm_type_id,start_time) values(%d,%d,'%s');",
			light->m_nID,
			nAlarmTypeId,
			strCurTime.c_str());
		break;
	case ALARM_LIGHT_NETWORK_END://update
	case ALARM_LIGHT_FAULT_END:
		strStartTime = CFunctions::time_t2string(light->alarm_start_time);
		sprintf_s(
			sql,
			LENGTH_SQL,
			"UPDATE his_alarm_light SET end_time = '%s' WHERE light_id=%d AND alarm_type_id=%d AND start_time = '%s';",
			strCurTime.c_str(),
			light->m_nID,
			nAlarmTypeId,
			strStartTime.c_str());
		break;
	}

	execute_sql(sql);

	return 0;
}

int CYAServerDlg::store_data_traffic_red_light(std::shared_ptr<Light> light,std::shared_ptr<Card> card)
{
	char sql[LENGTH_SQL] = {'\0'};
	time_t tCurTime;

	tCurTime = time(NULL);

	std::string s = CFunctions::time_t2string(tCurTime);

	sprintf_s(
		sql, 
		LENGTH_SQL,
		"insert IGNORE into his_traffic_red_light (vehicle_id,cur_time,light_id,driver_id) values('%s','%s',%d,'%s');",
		card->card_id.c_str(),
		s.c_str(),
		light->m_nID,
		card->driver_id.c_str());

	execute_sql(sql);

	return 0;
}

/*
* 存储路段信息
*
*/
int CYAServerDlg::store_data_section(std::shared_ptr<Section> section,time_t cur_time,int tag)
{
	INT64 ev_id = section->m_event_list[ET_SECTION_OVER_COUNT];

	if(ev_id == 0) // 没有告警
	{
		if(ALARM_SECTION_START == tag){ // 创建新的事件	
			ev_id = CFunctions::GetMicroSecond();
			std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
			ev->status = ES_START;	
			ev->ev_type = ET_SECTION_OVER_COUNT;
			ev->obj_type = OT_SECTION;
			ev->cur_time = time(NULL);
			ev->map_id = section->m_nMapId;

			ev->is_sent = false;
			m_event_list[ET_SECTION_OVER_COUNT] = ev_id;
			store_data_event(ev);
			add_event(ev);
			Sleep(1);
		}
	}
	else // 已存在告警
	{
		EventMap::iterator it_ev = mp_event_list->find(ev_id);
		if(it_ev != mp_event_list->end()){
			if(ALARM_SECTION_START == tag){ // 更新事件	
				it_ev->second->cur_value = section->mp_vehicle_list.size();
				it_ev->second->is_sent = false;
			}
			else if(ALARM_SECTION_END == tag){
				it_ev->second->cur_value = section->mp_vehicle_list.size();
				it_ev->second->status = ES_END;
				it_ev->second->cur_time = time(NULL);
				it_ev->second->is_sent = false;
				store_data_event(it_ev->second);
				add_event(it_ev->second);

				section->m_event_list[ET_SECTION_OVER_COUNT] = 0;
			}
		}
	}

	return 0;
}

void CYAServerDlg::execute_sql( const char* sql )
{
	m_qsmSQL->AddString(sql);
}

/*
* 日志菜单设置
*		将日志菜单设置内容同步更新到主对话框中的相应变量
*
* param
*		无
*
* return
*		无
*/
void CYAServerDlg::OnMenuLog()
{
	CLogSetting dlg;
	dlg.DoModal();

<<<<<<< HEAD
	m_log_raw_data   = dlg.m_log_raw_data;
	m_log_parse_data = dlg.m_log_parse_data;
	m_log_recv_package = dlg.m_log_recv_package;
	m_log_send_package = dlg.m_log_send_package;
	m_log_locate_data  = dlg.m_log_locate_data;
=======
	//m_log_sys_status = dlg.m_log_sys_status;
	m_log_raw_data   = theApp.log_raw_data;
	m_log_parse_data = theApp.log_parse_data;
	m_log_recv_package = theApp.log_recv_package;
	m_log_send_package = theApp.log_send_package;
	m_log_locate_data  = theApp.log_locate_data;
>>>>>>> newprotocal
}

void CYAServerDlg::OnMenuParam()
{
	CSysSetting dlg;
	dlg.DoModal();
	
	//m_bUseFilter = theApp.use_filter;

	//if(m_bUseFilter){
	//	m_nFilterType = FILTER_KALMAN;
	//}else{
	//	m_nFilterType = NO_FILTER;
	//}

	//CardMap::iterator it = mp_card_list_all.begin();
	//for(it;it!=mp_card_list_all.end();it++){
	//	it->second->m_nFilterType = m_nFilterType;
	//	if(it->second->m_pKalmanFilter == NULL && m_nFilterType != NO_FILTER){
	//		if(theApp.use_filter_odd){
	//			std::string temp = it->second->card_id;
	//			int a = atoi(temp.substr(temp.length() - 1 , 1).c_str());
	//			if(0 == a%2){
	//				it->second->EnableFilter(m_nFilterType);
	//			}
	//		}else{
	//			it->second->EnableFilter(m_nFilterType);
	//		}
	//	}
	//}
}

void CYAServerDlg::OnLogin(string const& name, message::ptr const& data, bool isAck, message::list &ack_resp)
{
	int res_code = (int)data->get_map()["code"]->get_int();
	switch (res_code)
	{
	case -100: // 用户未登录
		{
			//ws_login();
			is_websocket_login = false;
			break;
		}
	case 0:
		{
			if("" == data->get_map()["code"]->get_string()){ // 登录成功
				is_websocket_login = true;
			}else{ // 退出登录
				is_websocket_login = false;
			}
			break;
		}
	default:
		break;
	}
}

void CYAServerDlg::OnLoginCallBack( message::list const& msglist /*= nullptr*/ )
{
	message::ptr msg_ptr = msglist[0];
	int n = (int)msg_ptr->get_map()["code"]->get_int();
	is_websocket_login = (0 == n) ? true : false;
}

void CYAServerDlg::send_call_info()
{
	EnterCriticalSection(&m_csCallInfo);

	CallInfoUserMap::iterator it_call_user = mp_user_call_info.begin();
	if(it_call_user == mp_user_call_info.end()){
		LeaveCriticalSection(&m_csCallInfo);
		return;
	}

	BYTE buf[LENGTH_SEND_BUF] = {0};
	for(it_call_user = mp_user_call_info.begin(); it_call_user != mp_user_call_info.end(); ++it_call_user)
	{
		CallInfoReaderMap::iterator it_call_reader = it_call_user->second->mpReader.begin();
		if(it_call_reader == it_call_user->second->mpReader.end())
		{
			continue;
		}
		if(!it_call_reader->second->is_start_call){
			continue;
		}

		for(; it_call_reader != it_call_user->second->mpReader.end(); ++it_call_reader){
			//初始化
			memset(buf, 0, LENGTH_SEND_BUF);
			int npos = 0, card_count = 0;
			//卡数
			card_count = it_call_reader->second->cards_count;
			memcpy(&buf[npos], &card_count, sizeof(BYTE));
			npos += sizeof(BYTE);
			//呼叫类型
			memcpy(&buf[npos], &it_call_reader->second->call_type, sizeof(BYTE));
			npos += sizeof(BYTE);

			if(!it_call_reader->second->is_call_all){
				//循环添加卡信息
				CallInfoCardMap::iterator it_call_card = it_call_reader->second->mpCard.begin();
				for(; it_call_card != it_call_reader->second->mpCard.end(); ++it_call_card){
					//呼叫类型
					memcpy(&buf[npos], &it_call_card->second->call_type, sizeof(BYTE));
					npos += sizeof(BYTE);
					//卡类型
					memcpy(&buf[npos], &it_call_card->second->card_type, sizeof(BYTE));
					npos += sizeof(BYTE);
					//卡ID长度
					BYTE id_len = (BYTE)get_card_id_len(it_call_card->second->card_type);
					memcpy(&buf[npos], &id_len, sizeof(BYTE));
					npos += sizeof(BYTE);
					//卡ID
					if(id_len > 1){ // 标准卡id为4个字节，自组网卡为1个字节
						CFunctions::memcpyDWord(buf,(DWORD)it_call_card->second->card_id, npos);
					}else{
						memcpy(&buf[npos], &it_call_card->second->card_id, id_len);
					}
					npos += id_len;
				}
				memcpy(&buf[0], &card_count, sizeof(BYTE));
			}

			for(SocketMap::iterator it_sock= mp_socket_list.begin();it_sock!=mp_socket_list.end();++it_sock){
				if(0 == it_call_reader->first){
					if(it_sock != mp_socket_list.end())
					{
						SendData(it_sock->second->dwConnID,CHAR_CALL, npos, buf);
					}
				}else{
					if(it_sock->second->reader_id == it_call_reader->first && it_sock->second->reader_type == DEVICE_TYPE::DT_CARD_READER)
					{
						SendData(it_sock->second->dwConnID,CHAR_CALL, npos, buf);
						break;
					}
				}
			}
		}
	}

	LeaveCriticalSection(&m_csCallInfo);
}

void CYAServerDlg::clear_call_info()
{
	EnterCriticalSection(&m_csCallInfo);
	CallInfoUserMap::iterator it_call_user = mp_user_call_info.begin();

	for(; it_call_user != mp_user_call_info.end(); ++ it_call_user)
	{
		time_t current_time = time(NULL);
		for(CallInfoReaderMap::iterator it_call_reader = it_call_user->second->mpReader.begin(); it_call_reader != it_call_user->second->mpReader.end(); ++it_call_reader){
			if(it_call_reader->second->is_call_all){
			}else{
				for(CallInfoCardMap::iterator it_call_card = it_call_reader->second->mpCard.begin(); it_call_card != it_call_reader->second->mpCard.end();){
					if(difftime(current_time, it_call_card->second->start_time) > it_call_card->second->time_out * 60   ){
						it_call_card = it_call_reader->second->mpCard.erase(it_call_card);
						it_call_reader->second->is_start_call = false;
					}else{
						++it_call_card;
					}
				}
			}
		}
	}
	LeaveCriticalSection(&m_csCallInfo);
}

int CYAServerDlg::get_card_id_len( int card_type )
{
	switch (card_type)
	{
		//case CT_PERSON:
		//	return 4;
		//case CT_VEHICLE:
		//	return 4;
	case CT_ADHOC:
		return 1;
	default:
		return 4;
		//break;
	}
}

/*
* 检查卡的接收时间和当前时间的间隔，大于5s未收到则重置车卡的速度为0
*
*
*/
int CYAServerDlg::modify_card_speed(int val)
{
	for (CardMap::iterator it = mp_card_list_all.begin();it != mp_card_list_all.end();++it)
	{
		if (it->second->acce_cur_state == ACCELERATE_STATE::STATE_ACCE_STATIC)
		{
			continue;
		}

		int interval = 0;
		time_t t = time(NULL);
		interval = (int)difftime(t, it->second->rec_time);

		//std::string time_str = CFunctions::time_t2string(t);
		//std::string time_str2 = CFunctions::time_t2string(it->second->rec_time);

		//判断一下当前时间与卡的上一次接收时间的间隔时间是否小于阈值
		//如果小于阈值，则重置状态
		//如果大于阈值，则继续循环，不发送卡信息
		if (interval < val)
		{
			it->second->is_over_interval = false;
		}else{
			if (it->second->is_over_interval)
			{
				continue;
			}else{
				it->second->is_over_interval = true;
			}
		}	

		//if (interval > val || it->second->count_idle >= 5)//interval > val || 
		if (it->second->count_idle >= 5)
		{
			it->second->v = 0.0;
			it->second->isdealed = true;	
			it->second->issent = false;
			it->second->isoutput = true;
			it->second->acce_cur_state = ACCELERATE_STATE::STATE_ACCE_STATIC;
		}
	}

	return 0;
}

std::string CYAServerDlg::get_json_call_test()
{
	Json::Value root;
	Json::Value val_data;
	Json::Value val_stations;
	Json::Value val_station;
	Json::Value val_cards;
	Json::Value val_card;

	char _time[STR_LEN_TIME];
	struct tm local_time;
	time_t tt = time(NULL);

	localtime_s(&local_time, &tt);
	strftime(_time, STR_LEN_TIME, "%Y-%m-%d %H:%M:%S", &local_time);
	val_data[JSON_KEY_CALL_CARD_CALL_TIME] = _time;
	val_data[JSON_KEY_CALL_CARD_CALL_TYPE] = 0;
	val_data[JSON_KEY_CALL_CARD_USER_NAME] = "aaaaaa";
	val_data[JSON_KEY_CALL_CARD_CALL_TIME_OUT] = 5;

	val_station[JSON_KEY_CALL_CARD_STATION_ID] = 233;
	val_stations.append(val_station);
	val_station[JSON_KEY_CALL_CARD_STATION_ID] = 59;
	val_stations.append(val_station);

	val_card[JSON_KEY_CALL_CARD_CARD_TYPE_ID] = 3;
	val_card[JSON_KEY_CALL_CARD_CARD_ID] = 5;
	val_cards.append(val_card);
	val_card[JSON_KEY_CALL_CARD_CARD_TYPE_ID] = 3;
	val_card[JSON_KEY_CALL_CARD_CARD_ID] = 8;
	val_cards.append(val_card);

	val_data[JSON_KEY_CALL_CARD_STATIONS] = val_stations;
	val_data[JSON_KEY_CALL_CARD_CARDS] = val_cards;

	root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_CALL_CARD_REQUEST;
	root[JSON_ROOT_KEY_DATA] = val_data;
	return root.toFastString();
}

void CYAServerDlg::init_base_data()
{
	init_setting();
	init_alarm_type();
	init_shift();
	init_dept();
	init_map();
	init_area();
	init_special_area_entry();
	init_drivingface_render();
	init_reader();

#ifdef ALGORITHM_TYPE_TOF
	init_all_readers_coverage();
#elif defined ALGORITHM_TYPE_TDOA
	init_tdoa_all_readers_coverage();
#endif
	init_dev_adhoc();
	init_antenna_sync();

	init_card();
	init_staffer();
	init_vehicle();
	init_adhoc();

	init_chamber();
	init_ctrl_reader();
	init_traffic_lights();
	init_section();
	init_light_group();

#ifdef CERTIFY_READER_RANGE_AREA
	init_reader_range_area();
#endif
	//init_patrol_info();
	init_landmark();
	init_map_direction();
	init_cell_path_map();
	init_drivingface_warning_point();
	init_drivingface_card_curshift_position();
	//TestLandmarkRequirement();    //test landmark
	debug_print_syslog(0, "Base data init success.");
}

void CYAServerDlg::load_his_data()
{
	//load_his_reader(); // 分站状态
	load_his_card_postion_vehicle(); // 标识卡所在位置
	load_his_card_postion_staff();
	//load_his_card_state();
	deal_hist_card_postion();

	//load_his_driving_face_card_postion();//掘进面卡所在位置
	//load_his_driving_face_card_state();
	//init_drivingface_card_curshift_position();
}

void CYAServerDlg::load_his_area()
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	if(pConn == NULL){
		return;
	}

	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "select la.card_id, la.area_id, la.map_id, la.enter_time from his_location_area la \
				   where not exists(select 1 from his_location_area where card_id=la.card_id and enter_time> la.enter_time) \
				   and la.leave_time is null;");
	pRes = pConn->Execute(buf, err);
	int nRow = 0;
	std::string enter_time;
	while(pRow = mysql_fetch_row(pRes)){
		CardMap::iterator it = mp_card_list_all.find(pRow[0]);
		if(it != mp_card_list_all.end()){
			it->second->area_id = atoi(pRow[1]);
			it->second->map_id = atoi(pRow[2]);
			enter_time = pRow[3];
			CFunctions::string2systemtime(enter_time,it->second->enter_area_time);
			nRow++;
		}
	}
	mysql_free_result(pRes);
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_LOAD_HIS_AREA), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
}

void CYAServerDlg::load_his_card_postion_vehicle()
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	if(pConn == NULL){
		return;
	}

	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "select l.card_id, l.cur_time, l.x, l.y, l.z, l.map_id, l.area_id, l.state, \
				   case when l.cur_time >= date_sub(now(), interval 2 minute) then l.speed else 0 end as speed, \
				   l.mileage, la.enter_time, att.start_time, \
				   case when isnull(att.end_time) then 2 else 1 end as down_state, \
				   l.landmark_id, l.direction_mapper_id, l.landmark_dist \
				   from rt_location l, rt_location_area la, rt_att_vehicle att, dat_card c, dat_vehicle v \
				   where l.card_id = c.card_id and l.card_id = la.card_id and l.card_id = att.card_id and l.card_id=v.card_id \
				   and c.state=0;");

	pRes = pConn->Execute(buf, err);

	if (err)
	{
		return;
	}

	int nRow = 0;
	std::string rec_time, enter_time, start_time;
	while(pRow = mysql_fetch_row(pRes)){
		CardMap::iterator it = mp_card_list_all.find(pRow[0]);
		if(it != mp_card_list_all.end()){
			rec_time = pRow[1];
			API_StringToTime(rec_time, it->second->rec_time);

			it->second->x = atof(pRow[2]);
			it->second->y = atof(pRow[3]);
			it->second->z = atof(pRow[4]);

			it->second->map_id = atoi(pRow[5]);	
			it->second->area_id = atoi(pRow[6]);					
			it->second->state = atoi(pRow[7]);
			it->second->set_speed(atof(pRow[8]));
			it->second->mileage = atof(pRow[9]);

			enter_time = pRow[10];
			CFunctions::string2systemtime(enter_time,it->second->enter_area_time);
			start_time = pRow[11];
			API_StringToTime(start_time, it->second->down_time);

			it->second->PosState(atoi(pRow[12]));
			it->second->PosStateOld(atoi(pRow[12]));

			it->second->landmark_id = atoi(pRow[13]);
			it->second->landmark_direction = atoi(pRow[14]);
			it->second->landmark_dis = atof(pRow[15]);

			it->second->last_x = it->second->x;
			it->second->last_y = it->second->y;
			it->second->last_z = it->second->z;

			::GetLocalTime(&it->second->deal_time);

			it->second->is_hist = true;
			it->second->isdealed = true;
			it->second->isoutput = true;
			it->second->issent = false;

			deal_his_card_list(it->second);

			nRow++;
		}
	}
	mysql_free_result(pRes);
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_LOAD_HIS_POSTION_VEHICLE), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
}

void CYAServerDlg::load_his_card_postion_staff()
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	if(pConn == NULL){
		return;
	}

	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "select l.card_id, l.cur_time, l.x, l.y, l.z, l.map_id, l.area_id, l.state, \
				   case when l.cur_time >= date_sub(now(), interval 2 minute) then l.speed else 0 end as speed, \
				   l.mileage, la.enter_time, att.start_time, \
				   case when isnull(att.end_time) then 2 else 1 end as down_state, \
				   l.landmark_id, l.direction_mapper_id, l.landmark_dist \
				   from rt_location l, rt_location_area la, rt_att_staff att, dat_card c, dat_staff s \
				   where l.card_id = c.card_id and l.card_id = la.card_id and l.card_id = att.card_id and l.card_id=s.card_id\
				   and c.state=0;");

	pRes = pConn->Execute(buf, err);

	if (err)
	{
		return;
	}

	int nRow = 0;
	std::string rec_time, enter_time, start_time;
	while(pRow = mysql_fetch_row(pRes)){
		if(PDT_UP == atoi(pRow[12]))
		{
			continue; // 已升井，不再读入
		}
		CardMap::iterator it = mp_card_list_all.find(pRow[0]);
		if(it != mp_card_list_all.end()){
			rec_time = pRow[1];
			API_StringToTime(rec_time, it->second->rec_time);

			it->second->x = atof(pRow[2]);
			it->second->y = atof(pRow[3]);
			it->second->z = atof(pRow[4]);

			it->second->map_id = atoi(pRow[5]);	
			it->second->area_id = atoi(pRow[6]);					
			it->second->state = atoi(pRow[7]);
			it->second->set_speed(atof(pRow[8]));
			it->second->mileage = atof(pRow[9]);

			enter_time = pRow[10];
			CFunctions::string2systemtime(enter_time,it->second->enter_area_time);
			start_time = pRow[11];
			API_StringToTime(start_time, it->second->down_time);

			it->second->PosState(atoi(pRow[12]));
			it->second->PosStateOld(atoi(pRow[12]));

			it->second->landmark_id = atoi(pRow[13]);
			it->second->landmark_direction = atoi(pRow[14]);
			it->second->landmark_dis = atof(pRow[15]);

			it->second->last_x = it->second->x;
			it->second->last_y = it->second->y;
			it->second->last_z = it->second->z;

			::GetLocalTime(&it->second->deal_time);

			it->second->is_hist = true;
			it->second->isdealed = true;
			it->second->isoutput = true;
			it->second->issent = false;

			deal_his_card_list(it->second);

			nRow++;
		}
	}
	mysql_free_result(pRes);
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_LOAD_HIS_POSTION_STAFF), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
}

void CYAServerDlg::load_his_driving_face_card_postion()
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	if(pConn == NULL){
		return;
	}

	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "select * from his_location where cur_time in (select max(cur_time) from his_location where card_id = 0020000001014) and card_id = 0020000001014;");

	pRes = pConn->Execute(buf, err);

	if(err)
	{
	    return;
	}

	int nRow = 0;
	std::string rec_time, enter_time, start_time;
	while(pRow = mysql_fetch_row(pRes)){
		CardMap::iterator it = mp_card_list_all.find(pRow[0]);
		if(it != mp_card_list_all.end()){
			rec_time = pRow[1];
			API_StringToTime(rec_time, it->second->rec_time);

			it->second->x = atof(pRow[2]);
			it->second->y = atof(pRow[3]);
			it->second->z = atof(pRow[4]);
			//it->second->driving_face_x = it->second->x;
			//it->second->driving_face_y = it->second->y;
			//it->second->driving_face_z = it->second->z;

			it->second->map_id = atoi(pRow[5]); 
			it->second->area_id = atoi(pRow[6]);					
			it->second->state = atoi(pRow[7]);
			it->second->set_speed(atof(pRow[8]));
			it->second->mileage = atof(pRow[9]);

			it->second->PosState(PDT_DOWN);
			it->second->PosStateOld(PDT_DOWN);
			::GetLocalTime(&it->second->deal_time);

			it->second->is_hist = true;
			it->second->isdealed = true;
			it->second->isoutput = true;
			it->second->issent = false;

			deal_his_card_list(it->second);

			//send_json_data(JSON_CMD_VALUE_PUSH, get_json_drivingface_card_position(it->second));
			nRow++;
		}
	}
	mysql_free_result(pRes);
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_LOAD_HIS_POSTION_VEHICLE), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

}

void CYAServerDlg::load_his_driving_face_card_state()
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	if(pConn == NULL){
		return;
	}

	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "select * from his_drivingface_his where end_time in (select max(end_time) from his_drivingface_his where card_id = 0020000001014) and card_id = 0020000001014;");

	pRes = pConn->Execute(buf, err);

	if(err){
		return;
	}

	int nRow = 0;
	std::string rec_time, enter_time, start_time;
	while(pRow = mysql_fetch_row(pRes)){
		CardMap::iterator it = mp_card_list_all.find(pRow[1]);
		if(it != mp_card_list_all.end()){
			rec_time = pRow[5];
			API_StringToTime(rec_time, it->second->rec_time);

			it->second->x = atof(pRow[9]);
			it->second->y = atof(pRow[10]);
			it->second->z = atof(pRow[11]);
			//send_json_data(JSON_CMD_VALUE_PUSH, get_json_drivingface_card_position(it->second));
			nRow++;
		}
	}
	mysql_free_result(pRes);
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_LOAD_HIS_DRVING_FACE_STATE), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
}

void CYAServerDlg::init_drivingface_warning_point()
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	if(pConn == NULL){
		return;
	}

	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "select warning_point_id, warning_point_name, drivingface_id, point_x, point_y, point_z, warning_threshold, isvalid from dat_drivingface_warning_point;");
	pRes = pConn->Execute(buf, err);

	if(err)
	{
		return ;
	}

	int nRow = 0;
	std::string enter_time;
	std::shared_ptr<DrivingfaceWarningPoint> pDrivingfaceWarningPoint = nullptr;
	while(pRow = mysql_fetch_row(pRes)){
		DrivingfaceWarningPointMap::iterator it = mp_drivingface_warning_point_list.find(atoi(pRow[2]));
		if(it != mp_drivingface_warning_point_list.end())
		{
			pDrivingfaceWarningPoint = it->second;
		}else{
			pDrivingfaceWarningPoint = std::make_shared<DrivingfaceWarningPoint>();
			mp_drivingface_warning_point_list.insert(make_pair(atoi(pRow[2]), pDrivingfaceWarningPoint));
		}
		pDrivingfaceWarningPoint->warning_point_id = atoi(pRow[0]);
		pDrivingfaceWarningPoint->warning_point_name = pRow[1];
		pDrivingfaceWarningPoint->driving_face_id = atoi(pRow[2]);
		pDrivingfaceWarningPoint->point_x = atof(pRow[3]);
		pDrivingfaceWarningPoint->point_y = atof(pRow[4]);
		pDrivingfaceWarningPoint->point_z = atof(pRow[5]);
		pDrivingfaceWarningPoint->warning_threshold = atof(pRow[6]);
		pDrivingfaceWarningPoint->is_valid = atoi(pRow[7]);
	}
	mysql_free_result(pRes);
}

float CYAServerDlg::get_drivingface_warning_point_dis(std::shared_ptr<Card> card)
{
    if(NULL == card)
    {
        return -1;
    }
	double distance = -1;
    DrivingfaceWarningPointMap::iterator it = mp_drivingface_warning_point_list.find(3305);
    if(it != mp_drivingface_warning_point_list.end())
    {
        _point card_position;
		_point warning_point_position;
		card_position.x = card->x;
		card_position.y = card->y;
		card_position.z = card->z;
		warning_point_position.x = it->second->point_x;
		warning_point_position.y = it->second->point_y;
		warning_point_position.z = it->second->point_z;
		distance = GetDistance(card_position, warning_point_position);
		distance = distance * card->map_scale;
    }
	return distance;
}

int CYAServerDlg::API_TimeToString( string &strDateStr,const time_t &timeData )
{
	char chTmp[100] = {0};
	memset(chTmp, 0, sizeof(chTmp));
	struct tm *p = 0;
	localtime_s(p, &timeData);
	//p = localtime(&timeData);
	p->tm_year = p->tm_year + 1900;
	p->tm_mon = p->tm_mon + 1;
	sprintf_s(chTmp,sizeof(chTmp),"%.4d-%.2d-%.2d %.2d:%.2d:%.2d",
		p->tm_year, p->tm_mon, p->tm_mday,p->tm_hour,p->tm_min,p->tm_sec);
	strDateStr = chTmp;
	return 0;
}

int CYAServerDlg::API_StringToTime( const string &strDateStr,time_t &timeData )
{
	char *pBeginPos = (char*) strDateStr.c_str();
	char *pPos = strstr(pBeginPos,"-");
	if(pPos == NULL){
		//printf("strDateStr[%s] err /n", strDateStr.c_str());
		return -1;
	}
	int iYear = atoi(pBeginPos);
	int iMonth = atoi(pPos + 1);
	pPos = strstr(pPos + 1,"-");
	if(pPos == NULL){
		//printf("strDateStr[%s] err /n", strDateStr.c_str());
		return -1;
	}
	int iDay = atoi(pPos + 1);
	int iHour=0;
	int iMin=0;
	int iSec=0;
	pPos = strstr(pPos + 1," ");
	//为了兼容有些没精确到时分秒的
	if(pPos != NULL){
		iHour=atoi(pPos + 1);
		pPos = strstr(pPos + 1,":");
		if(pPos != NULL){
			iMin=atoi(pPos + 1);
			pPos = strstr(pPos + 1,":");
			if(pPos != NULL){
				iSec=atoi(pPos + 1);
			}
		}
	}
	struct tm sourcedate;
	memset((void*)&sourcedate, 0, sizeof(sourcedate));
	sourcedate.tm_sec = iSec;
	sourcedate.tm_min = iMin;
	sourcedate.tm_hour = iHour;
	sourcedate.tm_mday = iDay;
	sourcedate.tm_mon = iMonth - 1;
	sourcedate.tm_year = iYear - 1900;
	timeData = mktime(&sourcedate);
	return 0;
}

int CYAServerDlg::init_card( string card_id /*= ""*/ )
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	if(pConn == NULL){
		return 1;
	}

	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};

	if(card_id.length() == 0){
		sprintf_s(buf, "select card_id, card_type_id, state, ident from dat_card where state = 0;");
	}else{
		sprintf_s(buf, "select card_id, card_type_id, state, ident from dat_card where state = 0 and card_id='%s';", card_id.c_str());
	}

	pRes = pConn->Execute(buf, err);

	if (err)
	{
		return 1;
	}

	std::shared_ptr<Card> pCard = nullptr;
	int nRow = 0;

	while(pRow = mysql_fetch_row(pRes)){
		CardMap::iterator it = mp_card_list_all.find(pRow[0]);
		if(it != mp_card_list_all.end()){
			pCard = it->second;
		}else{
			pCard = std::make_shared<Card>(pRow[0], atoi(pRow[1]), theApp.z_offset);
#ifdef ALGORITHM_TYPE_TOF
			pCard->set_reader_path(&mp_reader_path_list);
#elif defined ALGORITHM_TYPE_TDOA
			pCard->set_reader_path_tdoa(mp_reader_path_list_tdoa);
#endif
			mp_card_list_all.insert(make_pair(pCard->card_id, pCard));
			nRow++;

			pCard->SetMainHwnd(this->m_hWnd);

			if(m_bUseFilter){
				if(theApp.use_filter_odd){
					std::string temp = pRow[1];
					int a = atoi(temp.substr(temp.length() - 1 , 1).c_str());
					if(0 == a%2){
						pCard->EnableFilter(m_nFilterType);
					}
				}else{
					pCard->EnableFilter(m_nFilterType);
				}
			}
		}
	}
	mysql_free_result(pRes);

	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_CARD), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

void CYAServerDlg::card_up_mine(std::shared_ptr<Card> card /*Card* card*/)
{
	g_is_up_mine = true;
	card->up_time = CFunctions::systime_to_timet(card->deal_time);
	store_data_card(card, RPT_ATTEND_UP);

	// 升井 删除所有报警信息
	INT64 ev_id = 0;
	for(int i=0; i < CARD_EVENT_COUNT; i++ )
	{
		ev_id = card->m_event_list[i];		
		if(ev_id > 0 ) // 
		{			
			EventMap::iterator it_ev = mp_event_list->find(ev_id);
			if(it_ev != mp_event_list->end())
			{
				it_ev->second->status = ES_END;
				it_ev->second->cur_time = time(NULL);
				it_ev->second->is_sent = false;
				store_data_event(it_ev->second);
				add_event(it_ev->second);
			}
			card->m_event_list[i] = 0;
		}
	}

	EVENT_TYPE et = ET_UNKNOWN;
	double limit_val = 0, cur_val = 0;

	if(CT_PERSON == card->card_type){
		CardMap::iterator it_card = mp_card_list_down_person.find(card->card_id);
		if(it_card != mp_card_list_down_person.end()){			
			mp_card_list_down_person.erase(it_card); // 从井下卡列表删除
			if(mp_card_list_down_person.size() <= sls_setting.over_count_person){ // 取消报警
				et = ET_OVER_COUNT_PERSON;
				limit_val = sls_setting.over_count_person;
				cur_val = mp_card_list_down_person.size();
			}
		}
	}else if(CT_VEHICLE == card->card_type){
		//CardMap::iterator it_card = mp_card_list_down_vehicle.find(card->card_id);
		//if(it_card != mp_card_list_down_vehicle.end()){
		//	mp_card_list_down_vehicle.erase(it_card); // 从井下卡列表删除			
		//	if(mp_card_list_down_vehicle.size() < sls_setting.over_count_vehicle){
		//		et = ET_OVER_COUNT_VEHICLE;
		//		limit_val = sls_setting.over_count_vehicle;
		//		cur_val = mp_card_list_down_vehicle.size();
		//	}
		//}
	}
	if(ET_UNKNOWN != et){
		ev_id = m_event_list[et];
		if(ev_id > 0 ) // 
		{			
			EventMap::iterator it_ev = mp_event_list->find(ev_id);
			if(it_ev != mp_event_list->end())
			{
				it_ev->second->cur_value = cur_val;					
				it_ev->second->status = ES_END;
				it_ev->second->cur_time = time(NULL);
				it_ev->second->is_sent = false;
				store_data_event(it_ev->second);
				add_event(it_ev->second);

				m_event_list[et] = 0;
			}
		}
	}

	DeptMap::iterator it_dept = mp_dept_list.find(card->dept_id);
	if(it_dept != mp_dept_list.end()){
		if(CT_PERSON == card->card_type){
			CardMap::iterator it_card = it_dept->second->dept_card_list_person.find(card->card_id);
			if(it_card != it_dept->second->dept_card_list_person.end()){
				it_dept->second->dept_card_list_person.erase(it_card); 
			}
			//deal_alarm_card(card, mp_card_list_over_time_person, false, AF_CARD_OVER_TIME); // 已在删除所有报警中处理
		}else if(CT_VEHICLE == card->card_type){
			//CardMap::iterator it_card = it_dept->second->dept_card_list_vehicle.find(card->card_id);
			//if(it_card != it_dept->second->dept_card_list_vehicle.end()){
			//	it_dept->second->dept_card_list_vehicle.erase(it_card);
			//}
			//deal_alarm_card(card, mp_card_list_over_time_vehicle, false, AF_CARD_OVER_TIME); // // 已在删除所有报警中处理
		}
	}

	if(CT_PERSON == card->card_type){
		OccLevelMap::iterator it_level = mp_occlevel_list.find(card->occlevel_id);
		if(it_level != mp_occlevel_list.end())
		{
			CardMap::iterator it_card = it_level->second->level_card_list_person.find(card->card_id);
			if(it_card != it_level->second->level_card_list_person.end()){
				it_level->second->level_card_list_person.erase(it_card);
			}
		}
	}
	// 离开区域, 将区域信息补足
	AreaMap::iterator it_area = mp_area_list.find(card->area_id);
	if(it_area != mp_area_list.end()){
		if(CT_PERSON == card->card_type)
		{
			CardMap::iterator it_card = it_area->second->area_card_list_person->find(card->card_id);
			if(it_card != it_area->second->area_card_list_person->end()){
				it_area->second->area_card_list_person->erase(it_card);
			}

		}
		else if(CT_VEHICLE == card->card_type)
		{
			//CardMap::iterator it_card = it_area->second->area_card_list_vehicle->find(card->card_id);
			//if(it_card != it_area->second->area_card_list_vehicle->end()){
			//	it_area->second->area_card_list_vehicle->erase(it_card);
			//}
		}
	}
	// 加入到升井列表
	// CardMap::iterator it_card_up = mp_card_list_up_person.find(card->card_id);
	// if(it_card_up != mp_card_list_up_person.end())
	// {
	// 	it_card_up->second = card;
	// }
	// else
	// {
	// 	mp_card_list_up_person.insert(make_pair(card->card_id, card));
	// }

	if(CT_PERSON == card->card_type)
	{
		card->area_id = 0;
		remove_card(card->card_id);
	}

	g_is_up_mine = false;
}

void CYAServerDlg::card_down_mine(std::shared_ptr<Card> card /*Card* card*/ )
{
	card->down_time = CFunctions::systime_to_timet(card->deal_time);
	EVENT_TYPE et = ET_UNKNOWN;
	double limit_val = 0, cur_val = 0;

	if(CT_PERSON == card->card_type){
		CardMap::iterator it_card = mp_card_list_down_person.find(card->card_id);
		if(it_card == mp_card_list_down_person.end()){
			mp_card_list_down_person.insert(make_pair(card->card_id, card)); // 添加到井下卡列表
			if(mp_card_list_down_person.size() > sls_setting.over_count_person){
				et = ET_OVER_COUNT_PERSON;
				limit_val = sls_setting.over_count_person;
				cur_val = mp_card_list_down_person.size();
			}
		}
	}else if(CT_VEHICLE == card->card_type){
		CardMap::iterator it_card = mp_card_list_down_vehicle.find(card->card_id);
		if(it_card == mp_card_list_down_vehicle.end()){
			mp_card_list_down_vehicle.insert(make_pair(card->card_id, card));  // 添加到井下卡列表
			//如果井下车辆总数超过系统设置的车辆阈值，则存储车辆超员告警信息
			if(mp_card_list_down_vehicle.size() > sls_setting.over_count_vehicle){
				et = ET_OVER_COUNT_VEHICLE;
				limit_val = sls_setting.over_count_vehicle;
				cur_val = mp_card_list_down_vehicle.size();
			}
		}	
	}

	if(ET_UNKNOWN != et){
		INT64 ev_id = m_event_list[et];
		if(ev_id > 0 ) // 
		{			
			EventMap::iterator it_ev = mp_event_list->find(ev_id);
			if(it_ev != mp_event_list->end())
			{
				it_ev->second->cur_value = cur_val;					
				it_ev->second->is_sent = false;
			}
		}
		else
		{
			INT64 ev_id = CFunctions::GetMicroSecond();
			std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
			ev->status = ES_START;	
			ev->ev_type = et;
			ev->obj_type = OT_MINE;
			ev->cur_time = time(NULL);

			ev->is_sent = false;
			m_event_list[et] = ev_id;
			store_data_event(ev);
			add_event(ev);
			Sleep(1);
		}
	}

	DeptMap::iterator it_dept = mp_dept_list.find(card->dept_id);
	if(it_dept != mp_dept_list.end()){
		if(CT_PERSON == card->card_type){
			CardMap::iterator it_card = it_dept->second->dept_card_list_person.find(card->card_id);
			if(it_card == it_dept->second->dept_card_list_person.end()){
				it_dept->second->dept_card_list_person.insert(make_pair(card->card_id, card)); 
			}
		}else if(CT_VEHICLE == card->card_type){
			CardMap::iterator it_card = it_dept->second->dept_card_list_vehicle.find(card->card_id);
			if(it_card == it_dept->second->dept_card_list_vehicle.end()){
				it_dept->second->dept_card_list_vehicle.insert(make_pair(card->card_id, card));
			}
		}
	}

	if(CT_PERSON == card->card_type)
	{
		OccLevelMap::iterator it_level = mp_occlevel_list.find(card->dept_id);
		if(it_level != mp_occlevel_list.end())
		{
			CardMap::iterator it_card_lvl = it_level->second->level_card_list_person.find(card->card_id);
			if(it_card_lvl == it_level->second->level_card_list_person.end())
			{
				it_level->second->level_card_list_person.insert(make_pair(card->card_id, card));
			}
		}
	}
	store_data_card(card, RPT_ATTEND_DOWN);
}

void CYAServerDlg::send_sync_reader()
{
	time_t cur_time;
	struct tm local;
	int wlen = 0;
	BYTE SendBuffer[LENGTH_SEND_BUF];
	BYTE bt_tmp;
	// 遍历发送数据
	int nPos = 0;

	SocketMap::iterator it_sock = mp_socket_list.begin();
	for(; it_sock != mp_socket_list.end(); ++it_sock){
		wlen = 0;
		cur_time = time(NULL);
		memset(SendBuffer, 0, LENGTH_SEND_BUF);
		localtime_s(&local, &cur_time);
		bt_tmp = local.tm_sec; 
		memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
		wlen += sizeof(BYTE);
		bt_tmp = local.tm_min;
		memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
		wlen += sizeof(BYTE);
		bt_tmp = local.tm_hour;
		memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
		wlen += sizeof(BYTE);
		bt_tmp = local.tm_mday; 
		memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
		wlen += sizeof(BYTE);
		bt_tmp = local.tm_wday;
		memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
		wlen += sizeof(BYTE);
		bt_tmp = local.tm_mon + 1;
		memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
		wlen += sizeof(BYTE);
		bt_tmp = (local.tm_year + 1900)%100;
		memcpy(&SendBuffer[wlen], &bt_tmp, sizeof(BYTE));
		wlen += sizeof(BYTE);
		SendData(it_sock->second->dwConnID , CHAR_SYNC_TIME, wlen, SendBuffer);

		Sleep(20);
	}
}

/*
* 向红绿灯发送心跳包
*
* param
*		无
*
* return
*		成功返回0，失败返回1
*
*/
int CYAServerDlg::send_heart_package()
{
	BYTE sendBuffer[1];
	for (LightMap::iterator it = mp_light_list.begin();it != mp_light_list.end();++it)
	{
		memset(sendBuffer,0,1);
		string strIp = it->second->m_strIP;
		TCHAR* tcIp = CFunctions::c2wc(strIp.c_str());

		DWORD dwConnID = 0;
		SocketMap::iterator it_sock = mp_socket_list.find(tcIp);
		if (it_sock != mp_socket_list.end())
		{
			SendData(it_sock->second->dwConnID,CHAR_HEART_BEAT,0,sendBuffer);
		}
	}

	return 0;
}

void CYAServerDlg::send_call_his_data()
{
	if(g_is_rec_hist){
		if(MessageBox(_T("正在接受收历史数据，请稍后再试"), _T("接收历史数据"), MB_OK) == IDOK){
			return;
		}
	}

	if (MessageBox(_T("确定要接收历史数据吗？"), _T("接收历史数据"), MB_OKCANCEL) != IDOK){
		return;
	}
	UpdateData(FALSE);

	bool bExit = false;
	SocketMap::iterator it_sock = mp_socket_list.begin();
	for(; it_sock != mp_socket_list.end(); ++it_sock){
		if(it_sock->second->reader_id == m_reader_id_hist && it_sock->second->reader_type == DEVICE_TYPE::DT_CARD_READER){
			int wlen = 0;
			WORD wchr = CHAR_LOCATEDATAHIS_TDOA;
			BYTE SendBuffer[LENGTH_SEND_BUF];
			memset(SendBuffer, 0, LENGTH_SEND_BUF);			
			SendData(it_sock->second->dwConnID, wchr, wlen, SendBuffer);
			bExit = true;
			break;
		}
	}
	if(!bExit){
		//if (MessageBox(_T("此分站未连接"), _T("请求历史数据"), MB_OK) == IDOK){
		//	
		//}
	}
}

void CYAServerDlg::OnBnCallHisData()
{
	send_call_his_data();
}

void CYAServerDlg::deal_hist_card_postion()
{
	CardMap::iterator it_card = mp_card_list_all.begin();
	for(; it_card != mp_card_list_all.end(); ++it_card){
		if(it_card->second->is_hist){
			//if(PDT_DOWN == it_card->pos_state){
			if(CT_VEHICLE == it_card->second->card_type){
				MapInfoMap::iterator it_map = mp_map_list.find(it_card->second->map_id);
				if(it_map != mp_map_list.end()){
					it_map->second->map_card_list_vehicle.insert(make_pair(it_card->first, it_card->second));
					it_card->second->map_scale = it_map->second->map_scale;
				}
				mp_card_list_down_vehicle.insert(make_pair(it_card->first, it_card->second));
				AreaMap::iterator it_area = mp_area_list.find(it_card->second->area_id);
				if(it_area != mp_area_list.end()){
					it_area->second->area_card_list_vehicle->insert(make_pair(it_card->first, it_card->second));
					if(0 == it_area->second->over_count_vehicle){
						mp_card_list_forbidden_vehicle->insert(make_pair(it_card->first, it_card->second));
					}
				}
			}else if(CT_PERSON == it_card->second->card_type){
				MapInfoMap::iterator it_map = mp_map_list.find(it_card->second->map_id);
				if(it_map != mp_map_list.end()){
					it_map->second->map_card_list_person.insert(make_pair(it_card->first, it_card->second));
					it_card->second->map_scale = it_map->second->map_scale;
				}
				mp_card_list_down_person.insert(make_pair(it_card->first, it_card->second));
				AreaMap::iterator it_area = mp_area_list.find(it_card->second->area_id);
				if(it_area != mp_area_list.end()){
					it_area->second->area_card_list_person->insert(make_pair(it_card->first, it_card->second));
					if(0 == it_area->second->over_count_person){
						mp_card_list_forbidden_person->insert(make_pair(it_card->first, it_card->second));
					}
				}
			}
			//}
		}
	}
}


void CYAServerDlg::deal_his_card_list( std::shared_ptr<Card> card )
{
	if(CT_VEHICLE == card->card_type){
		// 所在地图
		MapInfoMap::iterator it_map = mp_map_list.find(card->map_id);
		if(it_map != mp_map_list.end()){
			it_map->second->map_card_list_vehicle.insert(make_pair(card->card_id, card));
			card->map_scale = it_map->second->map_scale;
		}
		mp_card_list_down_vehicle.insert(make_pair(card->card_id, card));
		// 所在区域
		AreaMap::iterator it_area = mp_area_list.find(card->area_id);
		if(it_area != mp_area_list.end()){
			it_area->second->area_card_list_vehicle->insert(make_pair(card->card_id, card));
			if(0 == it_area->second->over_count_vehicle){
				mp_card_list_forbidden_vehicle->insert(make_pair(card->card_id, card));
			}
		}
		// 所在部门
		DeptMap::iterator it_dept = mp_dept_list.find(card->dept_id);
		if(it_dept != mp_dept_list.end()){
			it_dept->second->dept_card_list_vehicle.insert(make_pair(card->card_id, card));
		}
	}else if(CT_PERSON == card->card_type){
		if(PDT_DOWN == card->PosState()){
			MapInfoMap::iterator it_map = mp_map_list.find(card->map_id);
			if(it_map != mp_map_list.end()){
				it_map->second->map_card_list_person.insert(make_pair(card->card_id, card));
				card->map_scale = it_map->second->map_scale;
			}		
			mp_card_list_down_person.insert(make_pair(card->card_id, card));
			// 所在部门
			DeptMap::iterator it_dept = mp_dept_list.find(card->dept_id);
			if(it_dept != mp_dept_list.end()){
				it_dept->second->dept_card_list_person.insert(make_pair(card->card_id, card));
			}
			// 所在岗位
			OccLevelMap::iterator it_lvl = mp_occlevel_list.find(card->occlevel_id);
			if(it_lvl != mp_occlevel_list.end()){
				it_lvl->second->level_card_list_person.insert(make_pair(card->card_id, card));
			}
		}
		AreaMap::iterator it_area = mp_area_list.find(card->area_id);
		if(it_area != mp_area_list.end()){
			it_area->second->area_card_list_person->insert(make_pair(card->card_id, card));
			if(0 == it_area->second->over_count_person){
				mp_card_list_forbidden_person->insert(make_pair(card->card_id, card));
			}
		}
	}
}

void CYAServerDlg::load_his_reader()
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	if(pConn == NULL){
		return;
	}

	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "select ar.reader_id, ar.start_time, ar.rec_time from his_alarm_reader ar \
				   where not exists(select 1 from his_alarm_reader where reader_id=ar.reader_id and start_time> ar.start_time) \
				   and ar.end_time IS NULL;");
	pRes = pConn->Execute(buf, err);
	int nRow = 0;
	std::string rec_time, lost_time;
	while(pRow = mysql_fetch_row(pRes)){
		ReaderMap::iterator it = mp_reader_list.find(atoi(pRow[0]));
		if(it != mp_reader_list.end()){
			lost_time = pRow[1];
			rec_time = pRow[2];
			API_StringToTime(rec_time, it->second->rec_time);
			API_StringToTime(lost_time, it->second->lost_time);
			it->second->reader_state = STATUS_DEVICE_ERROR;
			nRow++;
		}
	}
	mysql_free_result(pRes);
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_LOAD_HIS_READER), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
}

void CYAServerDlg::deal_card_state(std::shared_ptr<Card> card /*Card* card */)
{
	//card->get_acc_text();
	card->get_state_text();

	// 电量
	EVENT_TYPE et = ET_UNKNOWN;
	double limit_val = 0, cur_val = 0;
	bool is_alarm = false;

	if(card->power_state == 0 && card->power_state_last != 0){
		card->status_power = STATUS_NORMAL;

		et = ET_CARD_LOW_POWER;
		limit_val = 0.5;
		cur_val = 1;
	}	
	if(card->power_state_last == 0 && card->power_state != 0){
		card->low_power_time = CFunctions::systime_to_timet(card->deal_time);

		et = ET_CARD_LOW_POWER;
		limit_val = 0.5;
		cur_val = 0.5;
		is_alarm = true;
	}

	if(ET_UNKNOWN != et)
	{
		INT64 ev_id = card->m_event_list[et];
		if(ev_id > 0 )
		{			
			EventMap::iterator it_ev = mp_event_list->find(ev_id);
			if(it_ev != mp_event_list->end())
			{
				it_ev->second->cur_value = cur_val;	
				it_ev->second->map_id = card->map_id;
				it_ev->second->area_id = card->area_id;
				it_ev->second->x = card->x;
				it_ev->second->y = card->y;
				it_ev->second->landmarkid = card->landmark_id;
				it_ev->second->landmarkdirect = card->landmark_direction;
				it_ev->second->landmarkdist = card->landmark_dis;
				if(is_alarm)
				{
					it_ev->second->is_sent = false;
				}
				else
				{
					it_ev->second->status = ES_END;
					it_ev->second->cur_time = time(NULL);
					it_ev->second->is_sent = false;
					store_data_event(it_ev->second);
					add_event(it_ev->second);

					card->m_event_list[et] = 0;
				}				
			}
		}
		else
		{
			if(is_alarm){
				INT64 ev_id = CFunctions::GetMicroSecond();
				std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
				ev->status = ES_START;	
				ev->ev_type = et;
				ev->obj_type = OT_CARD;
				ev->obj_id = card->card_id;
				ev->cur_time = time(NULL);

				ev->map_id = card->map_id;
				ev->area_id = card->area_id;
				ev->x = card->x;
				ev->y = card->y;
				ev->landmarkid = card->landmark_id;
				ev->landmarkdirect = card->landmark_direction;
				ev->landmarkdist = card->landmark_dis;

				ev->is_sent = false;
				card->m_event_list[et] = ev_id;
				store_data_event(ev);
				add_event(ev);
			}
		}
	}

	card->power_state_last = card->power_state;

	//呼救状态
	EVENT_TYPE et_help = ET_UNKNOWN;
	is_alarm = false;

	if(card->status_help == STATUS_ERROR){
		et_help = ET_CARD_HELP;
		limit_val = 0;
		cur_val = 1;
		is_alarm = true;
	}else{
		et_help = ET_CARD_HELP;
		limit_val = 0;
		cur_val = 1;
		is_alarm = false;
	}

	if(ET_UNKNOWN != et_help)
	{
		INT64 ev_id = card->m_event_list[et_help];
		if(ev_id > 0)
		{			
			EventMap::iterator it_ev = mp_event_list->find(ev_id);
			if(it_ev != mp_event_list->end())
			{
				it_ev->second->cur_value = cur_val;	
				it_ev->second->map_id = card->map_id;
				it_ev->second->area_id = card->area_id;
				it_ev->second->x = card->x;
				it_ev->second->y = card->y;
				it_ev->second->landmarkid = card->landmark_id;
				it_ev->second->landmarkdirect = card->landmark_direction;
				it_ev->second->landmarkdist = card->landmark_dis;
				if(is_alarm)
				{
					it_ev->second->is_sent = false;
				}
				else
				{
					it_ev->second->status = ES_END;
					it_ev->second->cur_time = time(NULL);
					it_ev->second->is_sent = false;
					store_data_event(it_ev->second);
					add_event(it_ev->second);

					card->m_event_list[et_help] = 0;
				}				
			}
		}
		else
		{
			if(is_alarm){
				INT64 ev_id = CFunctions::GetMicroSecond();
				std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
				ev->status = ES_START;	
				ev->ev_type = et_help;
				ev->obj_type = OT_CARD;
				ev->obj_id = card->card_id;
				ev->cur_time = time(NULL);

				ev->map_id = card->map_id;
				ev->area_id = card->area_id;
				ev->x = card->x;
				ev->y = card->y;
				ev->landmarkid = card->landmark_id;
				ev->landmarkdirect = card->landmark_direction;
				ev->landmarkdist = card->landmark_dis;

				ev->is_sent = false;
				card->m_event_list[et_help] = ev_id;
				store_data_event(ev);
				add_event(ev);
				Sleep(1);
			}
		}
	}
}

void CYAServerDlg::load_his_card_state()
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	if(pConn == NULL){
		return ;
	}

	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "select ac.card_id, ac.alarm_type_id, ac.start_time from his_alarm_card ac \
				   where not exists(select 1 from his_alarm_card where card_id=ac.card_id and alarm_type_id=ac.alarm_type_id and start_time> ac.start_time) \
				   and ac.end_time is NULL;");
	pRes = pConn->Execute(buf, err);
	int nRow = 0;
	std::string start_time;
	while(pRow = mysql_fetch_row(pRes)){
		CardMap::iterator it = mp_card_list_all.find(pRow[0]);
		if(it != mp_card_list_all.end()){
			switch (atoi(pRow[1]))
			{
			case ATID_POWER:
				it->second->power_state = 1;
				it->second->power_state_last = 1;
				it->second->status_power = STATUS_ERROR;
				start_time = pRow[2];
				API_StringToTime(start_time, it->second->low_power_time);
			default:
				break;
			}
			nRow++;
		}
	}
	mysql_free_result(pRes);
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_LOAD_HIS_STATE), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
}

EnHandleResult CYAServerDlg::OnPrepareListen( ITcpServer* pSender, SOCKET soListen )
{
	TCHAR szAddress[40];
	int iAddressLen = sizeof(szAddress) / sizeof(TCHAR);
	USHORT usPort;

	pSender->GetListenAddress(szAddress, iAddressLen, usPort);
	//::PostOnPrepareListen(szAddress, usPort);
	return HR_OK;
}

EnHandleResult CYAServerDlg::OnAccept( ITcpServer* pSender, CONNID dwConnID, SOCKET soClient )
{
	BOOL bPass = TRUE;
	TCHAR szAddress[40];
	int iAddressLen = sizeof(szAddress) / sizeof(TCHAR);
	USHORT usPort;

	pSender->GetRemoteAddress(dwConnID, szAddress, iAddressLen, usPort);

	return HR_OK;
}

EnHandleResult CYAServerDlg::OnSend( ITcpServer* pSender, CONNID dwConnID, const BYTE* pData, int iLength )
{
	//::PostOnSend(dwConnID, pData, iLength);
	return HR_OK;
}
EnHandleResult CYAServerDlg::OnReceive( ITcpServer* pSender, CONNID dwConnID, const BYTE* pData, int iLength )
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_221);
	ParseData *data = BufferUtility::getInstance()->getItem();
	if(data)
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_222);
		data->handle = this;
		data->dwConnID = dwConnID;
		data->len = iLength;
		memset(data->buf, 0, LENGTH_MSG_4K);
		memcpy(data->buf, pData, iLength);
		//WT_EXECUTELONGFUNCTION 线程间跳转 WT_EXECUTEDEFAULT 执行完一个再执行另一个
		this->parse_data_server(data->buf, data->len, data->dwConnID);
		BufferUtility::getInstance()->releaseItem(data);
	}

	return HR_OK;
}

EnHandleResult CYAServerDlg::OnClose( ITcpServer* pSender, CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode )
{
	::PostMessage(this->GetSafeHwnd(), WM_REMOVE_SOCKET, NULL, (LPARAM)dwConnID);
	return HR_OK;
}

EnHandleResult CYAServerDlg::OnShutdown( ITcpServer* pSender )
{
	return HR_OK;
}

std::shared_ptr<_SOCK> CYAServerDlg::get_socket_by_Id( DWORD dwConnID )
{
	SocketMap::iterator _sock = mp_socket_list.begin();
	for(; _sock != mp_socket_list.end(); ++_sock){
		if(_sock->second->dwConnID == dwConnID){
			return _sock->second;
		}
	}
	return NULL;
}

afx_msg LRESULT CYAServerDlg::OnMsgRefreshIpList(WPARAM wParam, LPARAM lParam)
{
	EnterCriticalSection(&m_csRefreshList);
	m_listctrl_reader.SetRedraw(FALSE);

	m_listctrl_reader.DeleteAllItems();
	SocketMap::reverse_iterator it_sock = mp_socket_list.rbegin();
	for(; it_sock != mp_socket_list.rend(); ++it_sock){
		AddItem(it_sock->second->sip, it_sock->second->reader_id, it_sock->second->state, it_sock->second->reader_type);
	}
	m_listctrl_reader.SetRedraw(TRUE);
	LeaveCriticalSection(&m_csRefreshList);
	return 0;
}

void CYAServerDlg::parse_data_locate_card_his( BYTE* DataBuffer, int& nCurPos, int reader_id, DWORD wTickCount, CString strTime, unsigned short wChr)
{
	// 按时间分组解析
	// 组长度
	WORD wframelen  = 0;
	CFunctions::getWord(DataBuffer, &wframelen, nCurPos);
	nCurPos += sizeof(WORD);
	int nframepos = nCurPos;

	// 数据保存时间 7字节，年，月，周，日，时，分，秒
	BYTE btSec = 0;
	memcpy(&btSec, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btMin = 0;
	memcpy(&btMin, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btHour = 0;
	memcpy(&btHour, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btDay = 0;
	memcpy(&btDay, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btWeek = 0;
	memcpy(&btWeek, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btMonth = 0;
	memcpy(&btMonth, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btYear = 0;
	memcpy(&btYear, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	CString strhistime;
	strhistime.Format(_T("20%.2d-%.2d-%.2d %.2d:%.2d:%.2d"), btYear%100, btMonth, btDay, btHour, btMin, btSec );				

	while(nCurPos - nframepos < wframelen){ // 一组数据
		BYTE btCardType = 0;
		memcpy(&btCardType, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);

		DWORD dwCardId = 0;
		CFunctions::getDWord(DataBuffer, &dwCardId, nCurPos);
		nCurPos += sizeof(DWORD);

		string str_card_id = CFunctions::getstrwithzero(btCardType, 3) + CFunctions::getstrwithzero(dwCardId, 10);
		std::shared_ptr<Card> pCard = std::make_shared<Card>(str_card_id, btCardType, theApp.z_offset);

		pCard->reader_id = reader_id;
		pCard->str_his_time = CFunctions::wc2c(strhistime);
		pCard->reader_tickcount = wTickCount;
		pCard->str_rec_time = CFunctions::wc2c(strTime);

		//LONG64 l64cardid = btCardType;
		//l64cardid <<= 32;
		//l64cardid |= dwCardId;

		switch(btCardType)
		{
		case CT_VEHICLE:
			{
				//报文时间
				WORD wCardTickCount = 0;
				CFunctions::getWord(DataBuffer, &wCardTickCount, nCurPos);
				nCurPos += sizeof(WORD);

				pCard->time_stamp = wCardTickCount;

				BYTE btTypeAndPower = 0;
				memcpy(&btTypeAndPower, &DataBuffer[nCurPos], sizeof(BYTE));
				nCurPos += sizeof(BYTE);
				//报文类型
				BYTE btType = 0;
				btType = (btTypeAndPower >>4) & 0x0F;
				//电池电量
				BYTE btPower = 0;
				btPower = btTypeAndPower & 0x0F;
				pCard->ranging_type = btType;
				pCard->power_state = btPower;

				//保留
				nCurPos += sizeof(BYTE);

				//加速度
				BYTE btAcceleration = 0;
				memcpy(&btAcceleration, &DataBuffer[nCurPos], sizeof(BYTE));
				nCurPos += sizeof(BYTE);
				pCard->accelerate_state = btAcceleration;

				//定位时间戳Tsp // 字序
				LONG64 lTime1 = 0;
				BYTE btTemp = 0;
				int nRangingPos = nCurPos;
				memcpy(&btTemp, &DataBuffer[nCurPos], sizeof(BYTE));
				nCurPos += sizeof(BYTE);
				DWORD dwTemp = 0;
				CFunctions::getDWord(DataBuffer, &dwTemp, nCurPos);
				nCurPos += sizeof(DWORD);
				lTime1 = btTemp;
				lTime1 = lTime1 << 32;
				lTime1 |= dwTemp;
				pCard->flying_time = lTime1;

				double dbldist = CFunctions::getDistance(lTime1);
				pCard->distance = dbldist;

				BYTE btAntenna = 0;
				memcpy(&btAntenna, &DataBuffer[nCurPos], sizeof(BYTE));
				nCurPos += sizeof(BYTE);
				btAntenna = btAntenna & 0xFF;
				pCard->antenna_id = btAntenna;

				if(CHAR_LOCATEDATAHIS_TDOA == wChr ){
					// 分站时间同步序列号 
					WORD wSyncNum = 0;
					CFunctions::getWord(DataBuffer, &wSyncNum, nCurPos);
					nCurPos += sizeof(WORD);
					// 信号强度
					WORD wStrength = 0;
					CFunctions::getWord(DataBuffer, &wStrength, nCurPos);
					nCurPos += sizeof(WORD);
				}
				break;
			}
		case CT_PERSON:
			{
				break;
			}
		default:
			{				
				//strBuf.Format(_T("无法识别的卡类型:%d\r\n"), btCardType);
				break;
			}						
		}
		store_data_card(pCard, HIS_RAW_DATA);
	}
}

void CYAServerDlg::parse_data_locate_reader_his( BYTE * DataBuffer, int nLen, int& nCurPos, int& reader_id, int& nTick, CString& strtime, unsigned short wChr)
{
	strtime.Format(_T("%s"), COleDateTime::GetCurrentTime().Format(_T("%Y-%m-%d %H:%M:%S")));

	DWORD dwReaderID = 0;
	CFunctions::getDWord(DataBuffer, &dwReaderID, nCurPos);
	nCurPos += sizeof(DWORD);

	WORD wTickCount = 0;
	CFunctions::getWord(DataBuffer, &wTickCount, nCurPos);
	nCurPos += sizeof(WORD);
}

void CYAServerDlg::parse_data_reader_synctime(BYTE *DataBuffer, int nLen, int& nCurPos, WORD wChr)
{
	if(syncmanager.IsOutputLog() != m_log_parse_data) {
		syncmanager.SetOutputLog(m_log_parse_data);
	}

	while(nCurPos < nLen - sizeof(WORD)){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_9);
		DWORD dwReaderID = 0; // 本机分站号
		CFunctions::getDWord(DataBuffer, &dwReaderID, nCurPos);
		nCurPos += sizeof(DWORD);

		BYTE btAnt = 0; // 本机发送天线
		memcpy(&btAnt, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);

		DWORD dwUpperReaderID = 0; // 上级分站号
		CFunctions::getDWord(DataBuffer, &dwUpperReaderID, nCurPos);
		nCurPos += sizeof(DWORD);

		BYTE btUpperAnt = 0; // 上级天线
		memcpy(&btUpperAnt, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);

		WORD wSyncNum = 0; // 序列号
		CFunctions::getWord(DataBuffer, &wSyncNum, nCurPos);
		nCurPos += sizeof(WORD);

		WORD wSyncLevel = 0; // 同步等级
		CFunctions::getWord(DataBuffer, &wSyncLevel, nCurPos);
		nCurPos += sizeof(WORD);

		LONG64 lTime1 = 0, lTime2 = 0;
		BYTE btTemp = 0;
		memcpy(&btTemp, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		DWORD dwTemp = 0;
		CFunctions::getDWord(DataBuffer, &dwTemp, nCurPos);
		nCurPos += sizeof(DWORD);
		lTime1 = btTemp; // 本机发送时间戳
		lTime1 = lTime1 << 32;
		lTime1 |= dwTemp;

		btTemp = 0;
		dwTemp = 0;
		memcpy(&btTemp, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		CFunctions::getDWord(DataBuffer, &dwTemp, nCurPos);
		nCurPos += sizeof(DWORD);
		lTime2 = btTemp; // 本机接收时间戳
		lTime2 = lTime2 << 32;
		lTime2 |= dwTemp;

		DWORD dwRootReaderID = 0;	// root分站号
		BYTE btRootAnt = 0;			// root天线
		unsigned long long syncRootId = 0;
		if(CHAR_READER_SYNC_TIME_ROOT == wChr){
			CFunctions::getDWord(DataBuffer, &dwRootReaderID, nCurPos);
			nCurPos += sizeof(DWORD);
			memcpy(&btRootAnt, &DataBuffer[nCurPos], sizeof(BYTE));
			nCurPos += sizeof(BYTE);

			syncRootId = dwRootReaderID;
			syncRootId = (syncRootId << 8) + btRootAnt;
		}

#ifdef TRACE_MEMORY_SYNCTIMEMSG
		//debug_print_syslog(0, "Local station id:%d, root station id:%d, syncnum:%d, level:%d, send:%I64u, rec:%I64u", 
		//                 dwReaderID, dwRootReaderID, wSyncNum, wSyncLevel, lTime1, lTime2);

		HostServer::SyncTimeMsg msg;
		msg.LocalIdCode(dwReaderID);
		msg.LocalIdCode((msg.LocalIdCode() << 8) + btAnt);
		msg.UpperIdCode(dwUpperReaderID);
		msg.UpperIdCode((msg.UpperIdCode() << 8) + btUpperAnt);
		msg.RootIdCode(dwRootReaderID);
		msg.RootIdCode((msg.RootIdCode() << 8) + btRootAnt);
		msg.SyncNum(wSyncNum);
		msg.SyncLevel(wSyncLevel);
		msg.LocalStationSendTime(lTime1);
		msg.LocalStationReceiveTime(lTime2);

		syncmanager.analyzeSyncMsg(msg);
#endif // TRACE_MEMORY_SYNCTIMEMSG

		if(wSyncLevel == 0){
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_82);
			EnterCriticalSection(&m_csSyncTime);
			umpRootSyncNum[syncRootId] = wSyncNum;
			LeaveCriticalSection(&m_csSyncTime);
		}

		ReaderMap::iterator it = mp_reader_list.find(dwReaderID);
		if(it != mp_reader_list.end()){
			it->second->sync_level = wSyncLevel;
			it->second->sync_rootId = syncRootId;
		}

		if(m_log_parse_data){
			std::string strlog = "";
			char chlog[MAX_LOG_LENGTH] = {0};
			sprintf_s(chlog, "id1:%d, id2:%d, root:%d, sn:%d, level:%d, send:%I64u, rec:%I64u",
				dwReaderID, dwUpperReaderID, dwRootReaderID, wSyncNum, wSyncLevel, lTime1, lTime2);
			strlog = chlog;
			Log::write_log(FILE_TYPE::SYNC_S, strlog, true);
		}
	}
}

int CYAServerDlg::init_antenna_sync()
{
	ReaderMap::iterator itReader = mp_reader_list.begin();
	// 初始化数组，将分站添加到列表，只有一个天线
	for(; itReader != mp_reader_list.end(); ++itReader){
		syncmanager.updateAnchor(itReader->second->reader_id, 1, 
			itReader->second->ant[0]->antenna_x * itReader->second->map_scale, 
			itReader->second->ant[0]->antenna_y * itReader->second->map_scale, 
			itReader->second->ant[0]->antenna_z * itReader->second->map_scale);
	}

	// 根据坐标计算分站间距离
	for (auto it = syncmanager._anchors.begin(); it != syncmanager._anchors.end(); it++)
	{
		for (auto it2 = syncmanager._anchors.begin(); it2 != syncmanager._anchors.end(); it2++)
		{
			if(it != it2)
			{
				double d = sqrt(pow((it->second.x - it2->second.x), 2)
					+ pow((it->second.y - it2->second.y), 2) 
					+ pow((it->second.z - it2->second.z), 2)) * 10000 / (2.99702547 * 15.65);
				syncmanager.updateDistance(it->first >>8, it->first & 0xFF, it2->first >> 8, it2->first & 0xFF,d);
			}
		}
	}
	return 0;
}

/*
*	此卡是否在主巷道内
*
*	param
*		pCard		卡对象
*
*	return
*		在主巷道返回true，否则返回false
*
*/
bool CYAServerDlg::isInMainTunel(std::shared_ptr<Card> pCard)
{
	bool bRet = false;
	int nMapId = 0;
	nMapId = pCard->map_id;

	MapInfoMap::iterator it_map = mp_map_list.find(nMapId);
	if (it_map == mp_map_list.end())
	{
		return bRet;
	}

	_point p;
	p.x = pCard->x;
	p.y = pCard->y;
	p.z = pCard->z;

	for (SectionMap::iterator it_section = it_map->second->map_section_list.begin();it_section != it_map->second->map_section_list.end();++it_section)
	{
		if (it_section->second->IsInPolygon(p))
		{
			bRet = true;
			break;
		}
	}

	return bRet;
}

int CYAServerDlg::getTunelProperty(std::shared_ptr<Card> pCard)
{
	bool bRet = false;
	int nMapId = 0;
	nMapId = pCard->map_id;

	MapInfoMap::iterator it_map = mp_map_list.find(nMapId);
	if (it_map == mp_map_list.end())
	{
		return bRet;
	}

	_point p;
	p.x = pCard->x;
	p.y = pCard->y;
	p.z = pCard->z;

	SectionMap::iterator it_section = it_map->second->map_section_list.begin();
	for (;it_section != it_map->second->map_section_list.end();++it_section)
	{
		if (it_section->second->IsInPolygon(p))
		{
			bRet = true;
			break;
		}
	}

	int nProperty = 0;
	if (it_section != it_map->second->map_section_list.end())
	{
		nProperty = it_section->second->m_nProperty;
	}

	return nProperty;
}

void CYAServerDlg::AnalysisAlgoFailedData(int interval  /*=60000*//*std::shared_ptr<Card> pCard*/)
{
	std::string strLog = "";

	//存储数据到数据库中
	ULONGLONG cur_time = ::GetTickCount();
	if (cur_time - g_ullCurTime > interval)
	{
		SYSTEMTIME st;
		GetLocalTime(&st);
		std::string strCurTime = "";
		if (CFunctions::CheckSystemTimeValid(st))
		{
			strCurTime = CFunctions::localsystime2string(st);
		}
		
		//总的定位信息状态的输出
		char chLog[LENGTH_SQL] = {0};

		unsigned int counts[ALGO_LOC_TOTAL] = {0};
		for (int i = 0; i < ALGO_LOC_TOTAL;i++)
		{
			if (g_nAlgoFailedCounts[i] > 0)
			{
				char log[LENGTH_SQL] = {0};
				sprintf_s(log,LENGTH_SQL,"AlgoLocType: %d , nCounts: %d, ",i,g_nAlgoFailedCounts[i]);
				//strcat(chLog,log);
				strcat_s(chLog,LENGTH_SQL,log);
			}

			counts[i] = g_nAlgoFailedCounts[i] - g_nAlgoFailedCycleCounts[i];
		}
		g_ullCurTime = ::GetTickCount();

		if (m_log_locate_data)
		{
			std::string strLog = chLog;
			Log::write_log(FILE_TYPE::ALGO_S,strLog,true);
		}
	}
}

void CYAServerDlg::Test()
{
	time_t tCurTime;
	tCurTime = time(NULL);

	std::string s = CFunctions::time_t2string(tCurTime);

	std::shared_ptr<ReceiveDataMap> pRdm = std::make_shared<ReceiveDataMap>();
	double dMapScale = 0.01;

	std::shared_ptr<ReceiveData> prd1 = std::make_shared<ReceiveData>();
	prd1->reader_id = 104;
	prd1->antenna_id = 1;
	prd1->rec_time_stamp = 93654873396;
	prd1->x = 4727.0*dMapScale;
	prd1->y = 75*dMapScale;
	prd1->z = 0;
	prd1->special = 1;
	pRdm->insert(ReceiveDataMap::value_type(prd1->rec_time_stamp,prd1));

	std::shared_ptr<ReceiveData> prd3 = std::make_shared<ReceiveData>();
	prd3->reader_id = 202;
	prd3->antenna_id = 1;
	prd3->rec_time_stamp = 856516514627;
	prd3->x = 430*dMapScale;
	prd3->y = 800.00*dMapScale;
	prd3->z = 0;
	prd3->special = 1;
	pRdm->insert(ReceiveDataMap::value_type(prd3->rec_time_stamp,prd3));

	//34
	std::shared_ptr<ReceiveData> prd2 = std::make_shared<ReceiveData>();
	prd2->reader_id = 103;
	prd2->antenna_id = 1;
	prd2->rec_time_stamp = 1034004209845;
	prd2->x = 897.0*dMapScale;
	prd2->y = 297.4*dMapScale;
	prd2->z = 0;
	prd2->special = 0;

	pRdm->insert(ReceiveDataMap::value_type(prd2->rec_time_stamp,prd2));

	std::unique_ptr<POS> p;
	p = LocateAlgorithm::Pos(pRdm,mp_reader_path_list_tdoa);

	double x = p->posx / dMapScale;
	double y = p->posy / dMapScale;
}

void CYAServerDlg::ReadFileTest()
{
	ifstream in;
	in.open("E:/5.log");

	if (!in.is_open())
	{
		return;
	}

	std::shared_ptr<ReceiveDataMap> pRdm = std::make_shared<ReceiveDataMap>();
	char pch[200] = {0};
	double dMapScale = 2;

	std::shared_ptr<Card> card = std::make_shared<Card>("",0, 0, theApp.z_offset);
	card->set_reader_path_tdoa(mp_reader_path_list_tdoa);
	card->m_nFilterType = FILTER_KALMAN;
	card->EnableFilter(FILTER_KALMAN);
	card->map_scale = dMapScale;

	while (!in.eof())
	{
		in.getline(pch,200);
		string data = pch;
		stringstream sout;

		std::vector<std::string> metaDatas = CFunctions::split(data,",",true);
		//std::shared_ptr<ReceiveData> prd = std::make_shared<ReceiveData>();

		std::shared_ptr<_coordinate> dist = std::make_shared<_coordinate>();
		for (int i=0;i<metaDatas.size();i++)
		{	
			std::string meta = metaDatas[i];

			std::vector<std::string> vtMeta = CFunctions::split(meta,":",true);
			std::vector<std::string> vtReader;

			switch(i){
			case 0:
				{
					int len = vtMeta.size() - 1;
					//分站信息
					vtReader = CFunctions::split(vtMeta[len],"-",true);
					dist->reader_id = atoi(vtReader[0].c_str());
					//如果分站号为101,218，is_special为1
					if (dist->reader_id == 108 || dist->reader_id == 218 || dist->reader_id == 107 || dist->reader_id==320)
					{
						dist->special = 1;
					}

					dist->syncRootId = 0;
					dist->antenna_id = 1;
				}
				break;
			case 1:
				dist->sync_num = atoi(vtMeta[1].c_str());
				break;
			case 2:
				break;
			case 3:
				break;
			case 4:
				//时间戳值
				sout<<vtMeta[1];
				sout>> dist->tt;
				break;
			case 5:
				break;
			case 6:
				//x
				dist->x = atof(vtMeta[1].c_str());
				break;
			case 7:
				//y
				dist->y = atof(vtMeta[1].c_str());
				break;
			case 8:
				//z
				dist->z = atof(vtMeta[1].c_str());
				break;
			case 9:
				dist->t =  atoi(vtMeta[1].c_str());
				break;
			case 10:
				//卡号
				break;
			default:
				break;
			}
		}

		dist->acce_state = card->accelerate_state;
		dist->acce_state_last = card->accelerate_state_last;
		dist->ins_direction = card->ins_direction;

		card->add_dist(dist);

		if (card->is_deal_by_algo)
		{
			SetEvent(hEvent);
		}

		if (card->m_afmData.bStatus)
		{
			AnalysisAlgoFailedData(5);
			card->m_afmData.bStatus = false;
		}

		if(card->x != card->last_x || card->y != card->last_y){
			std::string strlog = "";
			char chlog[MAX_LOG_LENGTH] = {0};
			sprintf_s(chlog, "cx: %f, cy: %f, cz: %f, clx: %f, cly: %f, v: %f, ct: %d",
				card->x, card->y, card->z, card->last_x, card->last_y, card->get_speed(), card->time_stamp_cal);
			strlog = chlog;
			Log::write_log(FILE_TYPE::DISTXX_S, strlog, true);

			card->last_x = card->x;
			card->last_y = card->y;
			card->last_z = card->z;
		}
	}
	in.close();

	card->get_coordinate();
}

/*
* 生成当用户登陆时，返回给前端所有的模拟数据
*
* param
*		无
*
* return
*		0正常，非0失败
*
*/
int CYAServerDlg::GenerateAllDataJsonTest()
{
	//所有卡的坐标以及特殊区域升井

	int i = 0;
	for (CardMap::iterator it_card = mp_card_list_all.begin();it_card != mp_card_list_all.end(); ++it_card)
	{
#if 0
		it_card->second->x = CFunctions::random(4000,4200);
		it_card->second->y = CFunctions::random(300,400);
#endif
		it_card->second->map_id = 5;
		if (it_card->second->x > 4100)
		{
			it_card->second->PosState(PDT_UP);
			it_card->second->area_id = 5;
		}else{
			it_card->second->area_id = 6;
		}

		i++;
	}

	//构造event
	for (int i=0;i<3;i++)
	{
		INT64 ev_id = CFunctions::GetMicroSecond();
		std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
		ev->status = ES_START;
		ev->ev_type = ET_CARD_PATROL_ERROR;
		ev->obj_type = OT_CARD;
		switch (i)
		{
		case 0:
			ev->obj_id = "0020000001062";
			ev->x = 4000;
			ev->y = 300;
			break;
		case 1:
			ev->obj_id = "0020000001063";
			ev->x = 4100;
			ev->y = 310;
			break;
		case 2:
			ev->obj_id = "0020000001064";
			ev->x = 4200;
			ev->y = 320;
			break;
		}
		ev->cur_time = time(NULL);
		ev->map_id = 5;
		ev->area_id = 5;

		ev->is_sent = false;
		add_event(ev);
		Sleep(1);
	}

	//构造callcardlist

	return 0;
}

int CYAServerDlg::SaveCellData2DB()
{
	std::string strContent = "";
	for (CardMap::iterator it = mp_card_list_all.begin();it != mp_card_list_all.end();++it)
	{
		if (it->second->originCellId == 0 && it->second->curCellId == 0)
		{
			continue;
		}

		//根据两次处理时间来决定前进格数
		char sql[LENGTH_SQL] = {0};
		char chTime[STR_LEN_TIME] = {0};
		char chIntervalTime[STR_LEN_TIME] = {0};
		sprintf_s(chTime,
			STR_LEN_TIME,
			"%u-%u-%u %u:%u:%u.%u",
			it->second->cellDealTime.wYear,
			it->second->cellDealTime.wMonth,
			it->second->cellDealTime.wDay,
			it->second->cellDealTime.wHour,
			it->second->cellDealTime.wMinute,
			it->second->cellDealTime.wSecond,
			it->second->cellDealTime.wMilliseconds);

		sprintf_s(chIntervalTime,
			STR_LEN_TIME,
			"%u-%u-%u %u:%u:%u.%u",
			it->second->last_cell->interval_time.wYear,
			it->second->last_cell->interval_time.wMonth,
			it->second->last_cell->interval_time.wDay,
			it->second->last_cell->interval_time.wHour,
			it->second->last_cell->interval_time.wMinute,
			it->second->last_cell->interval_time.wSecond,
			it->second->last_cell->interval_time.wMilliseconds);

		sprintf_s(sql,
			LENGTH_SQL,
			"insert ignore into his_cell_location(card_id,cur_time,interval_time,origin_reader_name,origin_cell_id,real_reader_name,real_cell_id,card_stamp_time,isFit,speed,mileage,map_id,area_id) values('%s','%s','%s','%s',%d,'%s',%d,%d,%d,%.4f,%.4f,%d,%d);",
			it->second->card_id.c_str(),
			chTime,
			chIntervalTime,
			it->second->originCellReaderName.c_str(),
			it->second->originCellId,
			it->second->curCellReaderName.c_str(),
			it->second->curCellId,
			it->second->time_stamp_last,
			it->second->is_fit_pos,
			it->second->get_speed(),
			it->second->mileage,
			it->second->map_id,
			it->second->area_id);
		std::string strSql = "";
		strSql = sql;
		strContent += strSql;
	}

	if (strContent != "")
	{
		ExecuteSql(strContent);
	}

	return 0;
}

int CYAServerDlg::WriteLog()
{
	for (CardMap::iterator it = mp_card_list_all.begin();it != mp_card_list_all.end();++it)
	{
		if (it->second->x == INVALID_COORDINATE && it->second->y == INVALID_COORDINATE)
		{
			continue;
		}
		CString strLog = _T("");
		std::string flag = it->second->is_fit_pos?"Y":"N";
		int nSource = 0;
		if (it->second->last_cell)
		{
			nSource = it->second->last_cell->dataSource;
		}				

		strLog.Format(_T("cardid: %s, sync_num: %d, ct: %d, ox: %f, oy: %f, x: %f,y: %f, readerName: %s, cellId : %d, originId: %d, oReaderName: %s, ov: %f, cv: %f, fit: %s, source: %d"),
			CFunctions::c2wc(it->second->card_id.c_str()),
			it->second->m_nCalcSyncNum,
			it->second->time_stamp_cal,
			it->second->origin_locate.x,
			it->second->origin_locate.y,
			it->second->x, 
			it->second->y,
			CFunctions::c2wc(it->second->curCellReaderName.c_str()),
			it->second->curCellId,
			it->second->originCellId,
			CFunctions::c2wc(it->second->originCellReaderName.c_str()),
			it->second->origin_locate.v,
			it->second->get_speed(),
			CFunctions::c2wc(flag.c_str()),
			nSource
			);
		char* chLog = CFunctions::CString2char(strLog);
		Log::write_log(FILE_TYPE::KALMAN_S,chLog);
		free(chLog);
	}
	return 0;
}

/*
 * 功能：在500ms的周期内，往前走一格
*/
int CYAServerDlg::ModifyCardInfo()
{
	int nCounts = 0;
	std::string strContent = "";
	for (CardMap::iterator it = mp_card_list_all.begin();it != mp_card_list_all.end();++it)
	{
		if (it->second->card_type == CT_PERSON)
		{
			continue;
		}
		if (it->second->last_cell == nullptr)
		{
			continue;
		}
		if (it->second->nStartLocateCounts < 5)
		{
			continue;
		}

		SYSTEMTIME lastTime;
		lastTime = it->second->last_cell->interval_time;

		if (!CFunctions::CheckSystemTimeValid(lastTime))
		{
			continue;
		}

		SYSTEMTIME curTime;
		::GetLocalTime(&curTime);
		
		//加500ms
		it->second->ChangeSystemTime(lastTime);
		int ret = CFunctions::CompareSystemTime(curTime,lastTime);
		if (ret <= 0)
		{
			continue;
		}

		::GetLocalTime(&it->second->cellDealTime);

		int nStep = it->second->last_cell->nStep;
		if (nStep < 1)
		{
			nStep = 1;
		}

		std::shared_ptr<Cell> cell = it->second->GetNextCell(it->second->last_cell,it->second->nIncrease,nStep,nullptr);//20170705生成一个新的格子	
		if (cell == nullptr)
		{
			continue;
		}
		cell->nStep = nStep;
        //+500需要调整
		//新的cell的interval_time是上一个格子的该属性加上500ms，下一个时刻用改值+500ms作为补数据的deadline
		//it->second->ChangeSystemTime(it->second->last_cell->interval_time);
		it->second->ChangeSystemTime(lastTime);
		//cell->interval_time = it->second->last_cell->interval_time;

		//根据两次处理时间来决定前进格数
		cell->dataSource = 2;
		it->second->curCellId = cell->id;
		it->second->originCellId = 0;
		it->second->originCellReaderName = "";

		std::mutex mu;
		mu.lock();
		cell->interval_time = it->second->last_cell->interval_time;
		it->second->ChangeSystemTime(cell->interval_time);
		if (cell)
		{
			it->second->last_cell = cell;
		}
		it->second->locate_cells.push_back(it->second->last_cell);
		mu.unlock();

		nCounts++;

		/*if (it->second->curCellReaderName == "" && it->second->originCellReaderName == "")
		{
			continue;
		}

		nCounts++;

		char sql[LENGTH_SQL] = {0};
		char chTime[STR_LEN_TIME] = {0};
		char chIntervalTime[STR_LEN_TIME] = {0};
		//确定下面不是Interval_time?@lsp
		sprintf_s(chTime,
			STR_LEN_TIME,
			"%u-%u-%u %u:%u:%u.%u",
			it->second->cellDealTime.wYear,
			it->second->cellDealTime.wMonth,
			it->second->cellDealTime.wDay,
			it->second->cellDealTime.wHour,
			it->second->cellDealTime.wMinute,
			it->second->cellDealTime.wSecond,
			it->second->cellDealTime.wMilliseconds);

		sprintf_s(chIntervalTime,
			STR_LEN_TIME,
			"%u-%u-%u %u:%u:%u.%u",
			it->second->last_cell->interval_time.wYear,
			it->second->last_cell->interval_time.wMonth,
			it->second->last_cell->interval_time.wDay,
			it->second->last_cell->interval_time.wHour,
			it->second->last_cell->interval_time.wMinute,
			it->second->last_cell->interval_time.wSecond,
			it->second->last_cell->interval_time.wMilliseconds);

		std::string strTime = "";
		strTime = chIntervalTime;
#ifdef DEBUG
		TRACE(_T("modifycardinfo: interval_time = %s\r\n"),CFunctions::c2wc(strTime.c_str()));
#else
		//char log[200] = {0};
		//sprintf_s(log,"modifycardinfo: interval_time = %s",strTime.c_str());
		//std::string strLog = log;
		//Log::write_log(FILE_TYPE::SYS_S,strLog,true);
#endif // DEBUG
		sprintf_s(sql,
			LENGTH_SQL,
			"insert ignore into his_cell_location(card_id,cur_time,interval_time,origin_reader_name,origin_cell_id,real_reader_name,real_cell_id,card_stamp_time,isFit,speed,mileage,map_id,area_id) values('%s','%s','%s','%s',%d,'%s',%d,%d,%d,%.4f,%.4f,%d,%d);",
			it->second->card_id.c_str(),
			chTime,
			chIntervalTime,
			it->second->originCellReaderName.c_str(),
			it->second->originCellId,
			it->second->curCellReaderName.c_str(),
			it->second->curCellId,
			it->second->time_stamp_last,
			it->second->is_fit_pos,
			it->second->get_speed(),
			it->second->mileage,
			it->second->map_id,
			it->second->area_id);
		std::string strSql = "";
		strSql = sql;
		strContent += strSql;*/
		it->second->locateCounts++;
	}
	/*if (strContent != "")
	{
		ExecuteSql(strContent);
	}*/

	return nCounts;
}

afx_msg LRESULT CYAServerDlg::OnWriteErrorLog(WPARAM wParam, LPARAM lParam)
{
	LogMsg* pMsg = (LogMsg*)wParam;
	CString strFile = pMsg->strFile;
	bool bTime = pMsg->isNeedTime;
	CString strErr = pMsg->strLog;
	writeErrorLogEx(strFile, strErr, bTime);
	strErr.Empty();
	strFile.Empty();
	delete pMsg;
	return 0;
}

void CYAServerDlg::parse_data_server( const BYTE * pData, int nLen, DWORD dwConnId )
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_92);
	EnterCriticalSection(&m_csParseDataServer);
	int read_length = 0;
	int pkg_len = 0;
	std::shared_ptr<BYTE> Buf(new BYTE[LENGTH_MSG_1M],[](BYTE* Buf){delete[] Buf;});
	BYTE* buf = Buf.get();

	if(buf == nullptr){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_93);
		LeaveCriticalSection(&m_csParseDataServer);
		return;
	}

	memset(buf, 0, LENGTH_MSG_1M);

	TCHAR szAddress[40];
	int iAddressLen = sizeof(szAddress) / sizeof(TCHAR);
	USHORT usPort;
	if(	_server.GetRemoteAddress(dwConnId, szAddress, iAddressLen, usPort)){
		SocketBufferMap::iterator it = mp_socket_buffer_list.find(szAddress);
		if(it != mp_socket_buffer_list.end()){ // 有此socket数据
			if(nLen + it->second->wReadLen > LENGTH_MSG_1M){
				// 删除此元素
				it->second->wLen = 0;
				it->second->wReadLen = 0;
				it->second->dwConnID = dwConnId;
				mp_socket_buffer_list.erase(it);

				LeaveCriticalSection(&m_csParseDataServer);
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_94);
				return ;
			}

			if(it->second->wReadLen > 0){
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_95);
				memcpy(buf, it->second->pData, it->second->wReadLen);
			}
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_96);
			memcpy(buf + it->second->wReadLen, pData, nLen);
			it->second->wReadLen += nLen;
			nLen = it->second->wReadLen;
		}else{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_97);
			memcpy(buf, pData, nLen);
		}

		while (read_length < nLen){
			pkg_len = MAKEWORD(buf[read_length + 1], buf[read_length]);
			pkg_len += sizeof(WORD); // 长度

			if(read_length + pkg_len > nLen){
				break; // 有半个包，溢出，保留与下个包合并
			}
			//将完整包送出
			//ParseData *data = (ParseData*)malloc(sizeof(ParseData));
			ParseData *data = (ParseData *)(BufferUtility::getInstance()->getItem());
			if(data){
				data->handle = this;
				data->dwConnID = dwConnId;
				data->len = pkg_len;
				memset(data->buf, 0, LENGTH_MSG_4K);
				//由于存在pkg_len大于LENGTH_MSG_4K的情况，导致memcpy出错的问题；
				//原因猜测可能是第三方库缓存过大再发送过来的原因
				if(pkg_len > LENGTH_MSG_4K){

					if(it != mp_socket_buffer_list.end()){ // 应从列表删除
						it->second->wLen = 0;
						it->second->wReadLen = 0;
						it->second->dwConnID = dwConnId;
						mp_socket_buffer_list.erase(it);
					}

					//free(data);
					//data = NULL;
					BufferUtility::getInstance()->releaseItem(data);

					LeaveCriticalSection(&m_csParseDataServer);
					return;
				}
				memcpy(data->buf, buf + read_length, pkg_len);
				//QueueUserWorkItem(_parse_package_data, (LPVOID)data, WT_EXECUTEDEFAULT);
				//send thread message
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_98);
				send_tcp_thread_message(data);
			}
			read_length += pkg_len;
		}

		if(read_length >= nLen){ //没剩下数据, 直接解析
			if(it != mp_socket_buffer_list.end()){
				it->second->wLen = 0;
				it->second->wReadLen = 0;
				it->second->dwConnID = dwConnId;
				mp_socket_buffer_list.erase(it);
			}
		}else{ // 有剩余数据，保存起来
			if(it != mp_socket_buffer_list.end()){
				try{
					if(it->second->wReadLen > 0){
						memset(&it->second->pData[it->second->wReadLen], 0, LENGTH_MSG_1M - it->second->wReadLen);
					}
				}catch(...){
					int tt = it->second->wReadLen;
				}
				try{
					memcpy(&it->second->pData[it->second->wReadLen], buf + read_length, nLen - read_length);
				}catch(...){
					int tt = it->second->wReadLen;
				}
				it->second->wReadLen += nLen - read_length;
			}else{
				std::shared_ptr<_SOCKET_BUFFER> _sockbuf = std::make_shared<_SOCKET_BUFFER>();
				if(_sockbuf){
					_sockbuf->wReadLen = 0;
					_sockbuf->dwConnID = dwConnId;
					_sockbuf->wLen = pkg_len;
					memset(_sockbuf->pData, 0, LENGTH_MSG_1M);
					memcpy(_sockbuf->pData, buf + read_length, nLen - read_length);
					_sockbuf->wReadLen += nLen - read_length;
					mp_socket_buffer_list.insert(make_pair(szAddress, _sockbuf));
				}
			}
		}
	}

	LeaveCriticalSection(&m_csParseDataServer);
}

void CYAServerDlg::deal_card_msg( std::shared_ptr<Card> card/*Card* card*/, bool is_hist /*= false*/ )
{
	//接收到从硬件发过来的消息20170705
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_109);
	DWORD dw;
	if(!is_hist){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_129);
		if(card->card_type == CT_ADHOC){ // 此处不需处理，已经在解析时计算了坐标位置		
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_218);
		}else if( LT_READER == theApp.locate_type){
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_111);
			card->x = card->p_reader->ant[card->antenna_id]->antenna_x;
			card->y = card->p_reader->ant[card->antenna_id]->antenna_y;
			card->z = card->p_reader->ant[card->antenna_id]->antenna_z;
			card->a = card->p_reader->ant[card->antenna_id]->antenna_angle;
			card->reader_id = card->p_reader->reader_id;
		}else{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_112);
			// 将距离加入到距离列表
			std::shared_ptr<_coordinate> dist = std::make_shared<_coordinate>();
			dist->t = card->time_stamp;//哈哈哈哈哈  卡的ct
			if(dist->t == 2091)
			{

				TRACE(_T("DDDDDDDDDDDDDDDDDDDDDD"));
			
			}
			dist->x = card->p_reader->ant[card->antenna_id]->antenna_x;
			dist->y = card->p_reader->ant[card->antenna_id]->antenna_y;
			dist->z = card->p_reader->ant[card->antenna_id]->antenna_z;
			dist->a = card->p_reader->ant[card->antenna_id]->antenna_angle;
			dist->reader_id = card->p_reader->reader_id;
			dist->syncRootId = card->p_reader->sync_rootId;
			dist->antenna_id = card->antenna_id;
			dist->d = card->distance;
			dist->special = card->p_reader->m_nIsSpecial;
			dist->sync_num = card->sync_num;
			dist->acce_state = card->accelerate_state;
			dist->acce_state_last = card->accelerate_state_last;
			dist->ins_direction = card->ins_direction;

			

			unsigned long long rootId = dist->syncRootId;
			bool bUseAlgo = false;
			unsigned short root_sync_num = 0;

			if (umpRootSyncNum.count(rootId) > 0)
			{
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_113);
				root_sync_num = umpRootSyncNum[rootId];

				if (root_sync_num - (unsigned short)dist->sync_num <= MAX_CALCLINER_NUM) // unsigned short, ignore cross period
				{
					LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_115);
					bUseAlgo = true;
				}
				else
				{
					LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_116);
					//此处需要输出计数
					ALGORITHM_FAILED(ALGO_FAILED_CONDITION_1);
					card->m_afmData.bStatus = true;
					card->m_afmData.strCardId = card->card_id;
					card->m_afmData.nCardStamp = dist->t;
					card->m_afmData.nType = ALGO_FAILED_CONDITION_1;
				}
			}
			else
			{
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_219);
			}
			if(card->card_type == CT_PERSON){
				TRACE(_T("person \r\n"));
			}
			if(card->p_reader->sync_level == 0){
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_119);
				bUseAlgo = true;
			}

			if(bUseAlgo){
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_120);
#ifdef TRACE_MEMORY_TAGMSG
				HostServer::TagMsg tagMsg;
				tagMsg.ReceiveTime = card->flying_time;
				tagMsg.StationIdCode = HostServer::SyncHelper::parseId((unsigned long long)card->reader_id, (unsigned long long)(card->antenna_id + 1));
				tagMsg.SyncNum = card->sync_num;
				tagMsg.SyncRootIdCode = card->p_reader->sync_rootId;
				if(card->p_reader->sync_level == 0){
					LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_121);
					dist->tt = card->flying_time;
				}else{
					LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_122);
					dist->tt = syncmanager.calTimeByLinar(tagMsg);
					if (dist->tt == 0)
					{
						dist->tt = LLONG_MAX;

						LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_123);
					}
				}
#endif // TRACE_MEMORY_TAGMSG
				card->is_deal_by_algo = false;

				// 井上分站的数据，不进算法
				if(PDT_DOWN ==  card->p_reader->pos_state)
				{
					card->add_dist(dist);
				}
			}else{
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_220);
			}

			if (card->m_afmData.bStatus)
			{
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_124);
				AnalysisAlgoFailedData();
				card->m_afmData.bStatus = false;
			}

			if(m_log_locate_data){
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_125);
<<<<<<< HEAD
#ifdef ENABLE_MY_LOG
				char chLog[LOG_BUF_SIZE] = {0};
				sprintf_s(chLog,"r: %d-%d, t: %d, max_t: %d, l:%d, tt: %I64u, ft: %I64u, x1: %f, y1: %f, z1: %f, ct: %d, cardid:%s",
					dist->reader_id, dist->antenna_id + 1, dist->sync_num, root_sync_num,card->p_reader->sync_level, dist->tt, card->flying_time,  dist->x, dist->y, dist->z, dist->t, card->card_id.c_str());	
				Log::write_log(FILE_TYPE::DIST_S,chLog,true);
#else
				CString strLog = _T("");

				wchar_t* p_card_id = CFunctions::c2wc(card->card_id.c_str());

				strLog.Format(_T("r: %d-%d, t: %d, max_t: %d, l:%d, tt: %I64u, ft: %I64u, x1: %f, y1: %f, z1: %f, ct: %d, cardid:%s"),
					dist->reader_id, dist->antenna_id + 1, dist->sync_num, root_sync_num,card->p_reader->sync_level, dist->tt, card->flying_time,  dist->x, dist->y, dist->z, dist->t, p_card_id/*CFunctions::c2wc(card->card_id.c_str())*/);
				writeErrorLog(_T("DIST_S"), strLog, true);
				strLog.Empty();
#endif // ENABLE_MY_LOG
=======
				char chlog[MAX_LOG_LENGTH] = {0};
				std::string strlog = "";
				sprintf_s(chlog, "r: %d-%d, t: %d, max_t: %d, l:%d, tt: %I64u, ft: %I64u, x1: %f, y1: %f, z1: %f, ct: %d, cardid:%s",
					dist->reader_id, dist->antenna_id + 1, dist->sync_num, root_sync_num,card->p_reader->sync_level,
					dist->tt, card->flying_time,  dist->x, dist->y, dist->z, dist->t, card->card_id.c_str());
				strlog = chlog;
				Log::write_log(FILE_TYPE::DIST_S, strlog, true);

>>>>>>> newprotocal
				//此处和save_card_msg消息存在不一致
				if(card->x != card->last_x || card->y != card->last_y){
					LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_126);
#ifdef ENABLE_MY_LOG
					
#else
					const time_t t = time(NULL);
					struct tm* current_time = new tm;
					localtime_s(current_time,&t);
					int nfit = -1;
					nfit = card->is_ref_pos?0:1;
<<<<<<< HEAD
					strLog.Format(_T("[%4d-%02d-%02d %02d:%02d:%02d], cardid:%s, cx: %f, cy: %f, cz: %f, clx: %f, cly: %f, v: %f, fit: %d, ct: %d"),
						current_time->tm_year + 1900,
						current_time->tm_mon + 1,
						current_time->tm_mday,
						current_time->tm_hour,
						current_time->tm_min,
						current_time->tm_sec,
						p_card_id /*CFunctions::c2wc(card->card_id.c_str())*/, card->x, card->y, card->z, card->last_x, card->last_y, card->get_speed(), nfit, card->time_stamp_cal);
					writeErrorLog(_T("DISTEX_S"), strLog, false);
					strLog.Empty();
#endif // ENABLE_MY_LOG			
=======

					memset(chlog, 0, MAX_LOG_LENGTH);
					sprintf_s(chlog, "cardid:%s, cx: %f, cy: %f, cz: %f, clx: %f, cly: %f, v: %f, ct: %d",
						card->card_id.c_str(), card->x, card->y, card->z, card->last_x, card->last_y, card->get_speed(), card->time_stamp_cal);
					strlog = chlog;
					Log::write_log(FILE_TYPE::DISTEX_S, strlog, true);

					memset(chlog, 0, MAX_LOG_LENGTH);
					sprintf_s(chlog, "%d,%f,%f,%f,%f,%f,iw: %f,uw: %f,as: %d,asl: %d,ct: %d, ov: %f,cv: %f,av: %f, lsn: %d,cardid: %s", 
						card->m_nCalcSyncNum,card->origin_locate.x,card->origin_locate.y,card->x, card->y,card->z,card->ins_weight,
						card->uwb_weight,card->accelerate_state,card->accelerate_state_last,card->time_stamp_cal,card->origin_locate.v,
						card->get_speed(),card->last_locate.acceleration,card->m_nSyncNumInList,card->card_id.c_str());
					strlog = chlog;
					Log::write_log(FILE_TYPE::KALMAN_S,strlog,true);

>>>>>>> newprotocal
					card->last_x = card->x;
					card->last_y = card->y;
					card->last_z = card->z;
				}else{		
					if(card->is_deal_by_algo){
<<<<<<< HEAD
						LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_127);						
#ifdef ENABLE_MY_LOG
						//CString strLog = _T("");
						///*
						//trLog.Format(_T("cardid: %s, sync_num: %d, ct: %d, ox: %f, oy: %f, x: %f,y: %f, ov: %f,cv: %f"),
						//	p_card_id,
						//	card->m_nCalcSyncNum,
						//	card->time_stamp_cal,
						//	card->origin_locate.x,
						//	card->origin_locate.y,
						//	card->x, 
						//	card->y,
						//	card->origin_locate.v,
						//	card->get_speed()
						//	);
						//	*/

						//char* chLog = CFunctions::CString2char(strLog);
						//Log::write_log(FILE_TYPE::KALMAN_S,chLog,true);
						//free(chLog);
#else
						CString strLog = _T("");
						strLog = _T("");
						strLog.Format(_T("%d,%f,%f,%f,%f,%f,iw: %f,uw: %f,as: %d,asl: %d,ct: %d, ov: %f,cv: %f,av: %f, lsn: %d,cardid: %s"),card->m_nCalcSyncNum,card->origin_locate.x,card->origin_locate.y,card->x, card->y,card->z,card->ins_weight,card->uwb_weight,card->accelerate_state,card->accelerate_state_last,card->time_stamp_cal,card->origin_locate.v,card->get_speed(),card->last_locate.acceleration,card->m_nSyncNumInList,p_card_id);
						writeErrorLog(_T("KALMAN_S"),strLog,false);
#endif // ENABLE_MY_LOG
=======
						LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_127);
						
						memset(chlog, 0, MAX_LOG_LENGTH);
						sprintf_s(chlog, "cardid: %s, sync_num: %d, ox: %f, oy: %f, x: %f,y: %f,ct: %d, ov: %f,cv: %f",
							card->card_id.c_str(),
							card->m_nCalcSyncNum,
							card->origin_locate.x,
							card->origin_locate.y,
							card->x, 
							card->y,
							card->time_stamp_cal,
							card->origin_locate.v,
							card->get_speed()
							);
						strlog =  chlog;
						Log::write_log(FILE_TYPE::KALMAN_S,strlog,true);
						card->is_deal_by_algo = false;
						card->last_locate_time = time(NULL);
>>>>>>> newprotocal
					}
				}
			}
		}
	}
	if(LT_READER == theApp.locate_type){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_130);
		time_t cur_time = time(NULL);
		time_t c_time = CFunctions::systime_to_timet(card->deal_time);
		if(difftime(cur_time, c_time) <30){
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_131);
			return ;
		}
	}
	::GetLocalTime(&card->deal_time);
	//业务逻辑 写入数据库
	save_card_postion(card);
	card_enter_map(card); // 切换地图
	card_enter_area(card);//区域的切换
	card_enter_mine(card);//升入井下
	deal_card_state(card);//处理卡的状态
	if (card->card_type == CT_VEHICLE)
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_132);
		deal_traffic_lights(card);//处理红绿灯
		//select_pos_output(card);
	}
	card->isdealed = true;
	if(LT_READER != theApp.locate_type){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_133);
		card->issent = false;
	}
}

afx_msg LRESULT CYAServerDlg::OnRemoveSocket(WPARAM wParam, LPARAM lParam)
{
	DWORD dwConnID = (DWORD)lParam;
	remove_socket(dwConnID);
	return 0;
}

void CYAServerDlg::writeErrorLogEx( const CString strFile, const CString strErr ,bool bTime /*= true*/ )
{
	EnterCriticalSection(&m_csWriteLog);
	if(openLogFile(strFile)){
		CString strTempInfo;
		if(bTime){
			COleDateTime t = COleDateTime::GetCurrentTime(); 
			strTempInfo.Format(_T("%s\r\n%s\r\n"), t.Format(_T("%H:%M:%S")), strErr);
		}else{
			strTempInfo.Format(_T("%s\r\n"), strErr);
		}
		TRY{
			cfErrorLog.SeekToEnd();
			char* old_locale = _strdup(setlocale(LC_CTYPE,NULL));
			setlocale( LC_CTYPE, "chs" );//设定

			cfErrorLog.WriteString(strTempInfo);

			setlocale( LC_CTYPE, old_locale );
			free( old_locale );//还原区域设定
		}
		CATCH(CFileException, e){
			if(cfErrorLog.m_pStream)
				cfErrorLog.Close();
		}
		END_CATCH
	}
	LeaveCriticalSection(&m_csWriteLog);
}

void CYAServerDlg::writeErrorLogEx( const char* strFile, const char* strErr ,bool bTime /*= true*/ )
{
	EnterCriticalSection(&m_csWriteLog);
	if(openLogFile(strFile)){
		CString strTempInfo;
		if(bTime){
			COleDateTime t = COleDateTime::GetCurrentTime(); 
			strTempInfo.Format(_T("%s\r\n"), t.Format(_T("%H:%M:%S")));
			USES_CONVERSION;
			CString tmp = A2T(strErr);
			strTempInfo += tmp + _T("\r\n");
		}else{
			USES_CONVERSION;
			strTempInfo = CFunctions::c2wc(strErr);
			strTempInfo += _T("\r\n");
		}
		TRY{
			cfErrorLog.SeekToEnd();
			char* old_locale = _strdup(setlocale(LC_CTYPE,NULL));
			setlocale( LC_CTYPE, "chs" );//设定

			cfErrorLog.WriteString(strTempInfo);

			setlocale( LC_CTYPE, old_locale );
			free( old_locale );//还原区域设定
		}
		CATCH(CFileException, e){
			if(cfErrorLog.m_pStream)
				cfErrorLog.Close();
		}
		END_CATCH
	}
	LeaveCriticalSection(&m_csWriteLog);
}

void CYAServerDlg::init_queuestring()
{
	m_qsmSQL = new QueueStrManager(SQL_EXECUTE_SENTENCE_COUNT_MAX,
		SQL_SENTENCE_LENGTH_MAX, _exec_sql);//50,7500
}

BOOL CYAServerDlg::SendData( DWORD dwConnID, WORD wCharacterWord, int wLength, BYTE* DataBuffer )
{
	BYTE SendBuffer[LENGTH_MSG_2K];
	WORD nlength = wLength + sizeof(WORD) + sizeof(WORD); //socket的数据长度 数据的长度(n) + 特征字(2) + 校验码（2）
	memset(SendBuffer, 0, LENGTH_MSG_2K);

	int nPos = 0;
	CFunctions::memcpyWord(SendBuffer, nlength, nPos);//长度
	nPos += sizeof(WORD);
	CFunctions::memcpyWord(SendBuffer, wCharacterWord, nPos);
	nPos += sizeof(WORD);
	memcpy(&SendBuffer[nPos], &DataBuffer[0], wLength);
	nPos += wLength;

	WORD wCrc = CFunctions::getCRC(&SendBuffer[sizeof(WORD)], wLength + sizeof(WORD)); // 数据长度 + 特征字
	CFunctions::memcpyWord(SendBuffer, wCrc, nPos);
	nPos += sizeof(WORD);

	//char pch[30] = {0};
	//sprintf_s(pch,"%s",SendBuffer);
	BOOL ret = _server.Send(dwConnID, &SendBuffer[0], nPos);

	//delete[] SendBuffer;
	Sleep(20);

	return ret;
}

void CYAServerDlg::parse_data_locate_card_his_tdoa( BYTE* DataBuffer, int nLen, int reader_id, DWORD wTickCount, CString strTime)
{
	// 按时间分组解析
	// 组长度
	int nCurPos = 0;

	// 数据保存时间 7字节，年，月，周，日，时，分，秒
	BYTE btSec = 0;
	memcpy(&btSec, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btMin = 0;
	memcpy(&btMin, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btHour = 0;
	memcpy(&btHour, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btDay = 0;
	memcpy(&btDay, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btWeek = 0;
	memcpy(&btWeek, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btMonth = 0;
	memcpy(&btMonth, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	BYTE btYear = 0;
	memcpy(&btYear, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	CString strhistime;
	strhistime.Format(_T("20%.2d-%.2d-%.2d %.2d:%.2d:%.2d"), btYear%100, btMonth, btDay, btHour, btMin, btSec );				

	std::shared_ptr<BYTE> sp_bt(new BYTE[nLen],[](BYTE* bt){
		delete[] bt;
	});
	BYTE* bt = sp_bt.get();

	while(nCurPos < nLen){ // 一组数据
		// 一个数据包
		WORD wPkgLen = 0;
		CFunctions::getWord(DataBuffer, &wPkgLen, nCurPos);
		nCurPos += sizeof(WORD);

		if(bt){
			memset(bt, 0, nLen);
			memcpy(bt, &DataBuffer[nCurPos], wPkgLen);
			parse_data_locate_card_his_tdoa_package(bt, wPkgLen, reader_id, wTickCount, strTime, strhistime);
		}
		nCurPos += wPkgLen;
	}
	//delete[] bt;
}

void CYAServerDlg::parse_data_locate_card_his_tdoa_package( BYTE* DataBuffer, int nLen, int reader_id, DWORD wTickCount, CString strTime, CString strHistTime )
{
	// 命令字
	int nCurPos = 0;
	WORD wChr = 0;
	CFunctions::getWord(DataBuffer, &wChr, nCurPos);
	nCurPos += sizeof(WORD);

	BYTE* bt = new BYTE[LENGTH_RECORD_MAX];
	if(NULL == bt){
		return;
	}
	while(nCurPos < nLen){
		switch (wChr)
		{
		case CHAR_LOCATEDATA:
			{
				memset(bt, 0, LENGTH_RECORD_MAX);
				memcpy(bt, &DataBuffer[nCurPos], LENGTH_TOF_VEHICLE);
				parse_data_locate_card_his_tof_card(bt, LENGTH_TOF_VEHICLE, reader_id, wTickCount, strTime, strHistTime);
				nCurPos += LENGTH_TOF_VEHICLE;
				break;
			}
		case CHAR_LOCATEDATA_TDOA:
			{
				memset(bt, 0, LENGTH_RECORD_MAX);
				memcpy(bt, &DataBuffer[nCurPos], LENGTH_TDOA_VEHICLE);
				parse_data_locate_card_his_tdoa_card(bt, LENGTH_TOF_VEHICLE, reader_id, wTickCount, strTime, strHistTime);
				nCurPos += LENGTH_TDOA_VEHICLE;
				break;
			}
		case CHAR_READER_SYNC_TIME:
			{
				memset(bt, 0, LENGTH_RECORD_MAX);
				memcpy(bt, &DataBuffer[nCurPos], LENGTH_SYNC_TIME);
				parse_data_locate_card_his_sync_time(bt, LENGTH_TOF_VEHICLE, strTime, strHistTime, CHAR_READER_SYNC_TIME);
				nCurPos += LENGTH_SYNC_TIME;
				break;
			}
		case CHAR_READER_SYNC_TIME_ROOT:
			{
				memset(bt, 0, LENGTH_RECORD_MAX);
				memcpy(bt, &DataBuffer[nCurPos], LENGTH_SYNC_TIME_ROOT);
				parse_data_locate_card_his_sync_time(bt, LENGTH_TOF_VEHICLE, strTime, strHistTime, CHAR_READER_SYNC_TIME_ROOT);
				nCurPos += LENGTH_SYNC_TIME;
				break;
			}
		default:
			break;
		}
	}
	delete[] bt;
	bt = NULL;
}

void CYAServerDlg::parse_data_locate_card_his_tof_card( BYTE* DataBuffer, int nLen, int reader_id, DWORD wTickCount, CString strTime, CString strHistTime )
{
	int nCurPos = 0;
	BYTE btCardType = 0;
	memcpy(&btCardType, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	DWORD dwCardId = 0;
	CFunctions::getDWord(DataBuffer, &dwCardId, nCurPos);
	nCurPos += sizeof(DWORD);

	string str_card_id = CFunctions::getstrwithzero(btCardType, 3) + CFunctions::getstrwithzero(dwCardId, 10);

	char sql[LENGTH_SQL] = {0};
	bool b_exec = false;

	switch(btCardType)
	{
	case CT_VEHICLE:
	case CT_PERSON:
		{
			//报文时间
			WORD wCardTickCount = 0;
			CFunctions::getWord(DataBuffer, &wCardTickCount, nCurPos);
			nCurPos += sizeof(WORD);

			BYTE btTypeAndPower = 0;
			memcpy(&btTypeAndPower, &DataBuffer[nCurPos], sizeof(BYTE));
			nCurPos += sizeof(BYTE);
			//报文类型
			BYTE btType = 0;
			btType = (btTypeAndPower >>4) & 0x0F;
			//电池电量
			BYTE btPower = 0;
			btPower = btTypeAndPower & 0x0F;

			//保留
			BYTE btCallType = 0;
			memcpy(&btCallType,&DataBuffer[nCurPos],sizeof(BYTE));
			nCurPos += sizeof(BYTE);
			//加速度
			BYTE btAcceleration = 0;
			memcpy(&btAcceleration, &DataBuffer[nCurPos], sizeof(BYTE));
			nCurPos += sizeof(BYTE);

			//定位时间戳Tsp // 字序
			LONG64 lTime1 = 0;
			BYTE btTemp = 0;
			int nRangingPos = nCurPos;
			memcpy(&btTemp, &DataBuffer[nCurPos], sizeof(BYTE));
			nCurPos += sizeof(BYTE);
			DWORD dwTemp = 0;
			CFunctions::getDWord(DataBuffer, &dwTemp, nCurPos);
			nCurPos += sizeof(DWORD);
			lTime1 = btTemp;
			lTime1 = lTime1 << 32;
			lTime1 |= dwTemp;

			double dbldist = CFunctions::getDistance(lTime1);

			BYTE btAntenna = 0;
			memcpy(&btAntenna, &DataBuffer[nCurPos], sizeof(BYTE));
			nCurPos += sizeof(BYTE);
			btAntenna = btAntenna & 0xFF;

			b_exec = true;
			sprintf_s(sql, LENGTH_SQL,
				"INSERT IGNORE INTO his_raw_data(card_id, reader_id, antenna_id, reader_stamp, card_stamp, \
				fly_time, distance, ranging_type, power_state, accelerate, his_time, rec_time ) \
				VALUES(%s, %d, %d, %d, %d, %lld, %4.f, %d, %d, %d, '%s', '%s');",
				str_card_id.c_str(), reader_id, btAntenna, wTickCount, wCardTickCount, lTime1, dbldist, btType, 
				btPower,btAcceleration,	CFunctions::wc2c(strHistTime), CFunctions::wc2c(strTime));

			//if(CHAR_LOCATEDATAHIS_TDOA == wChr ){
			//	// 分站时间同步序列号
			//	WORD wSyncNum = 0;
			//	CFunctions::getWord(DataBuffer, &wSyncNum, nCurPos);
			//	nCurPos += sizeof(WORD);
			//	// 信号强度
			//	WORD wStrength = 0;
			//	CFunctions::getWord(DataBuffer, &wStrength, nCurPos);
			//	nCurPos += sizeof(WORD);
			//}
			break;
		}
		/*case CT_PERSON:
		{
		break;
		}*/
	default:
		{
			break;
		}						
	}

	try
	{
		if(b_exec){
			execute_sql(sql);
		}
	}
	catch (...)
	{
	}
}

void CYAServerDlg::parse_data_locate_card_his_tdoa_card( BYTE* DataBuffer, int nLen, int reader_id, DWORD wTickCount, CString strTime, CString strHistTime )
{
	int nCurPos = 0;
	BYTE btCardType = 0;
	memcpy(&btCardType, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	DWORD dwCardId = 0;
	CFunctions::getDWord(DataBuffer, &dwCardId, nCurPos);
	nCurPos += sizeof(DWORD);

	string str_card_id = CFunctions::getstrwithzero(btCardType, 3) + CFunctions::getstrwithzero(dwCardId, 10);

	char sql[LENGTH_SQL] = {0};
	bool b_exec = false;

	switch(btCardType)
	{
	case CT_VEHICLE:
		{
			//报文时间
			WORD wCardTickCount = 0;
			CFunctions::getWord(DataBuffer, &wCardTickCount, nCurPos);
			nCurPos += sizeof(WORD);

			BYTE btTypeAndPower = 0;
			memcpy(&btTypeAndPower, &DataBuffer[nCurPos], sizeof(BYTE));
			nCurPos += sizeof(BYTE);
			//报文类型
			BYTE btType = 0;
			btType = (btTypeAndPower >>4) & 0x0F;
			//电池电量
			BYTE btPower = 0;
			btPower = btTypeAndPower & 0x0F;

			//保留
			nCurPos += sizeof(BYTE);
			//加速度
			BYTE btAcceleration = 0;
			memcpy(&btAcceleration, &DataBuffer[nCurPos], sizeof(BYTE));
			nCurPos += sizeof(BYTE);

			//定位时间戳Tsp // 字序
			LONG64 lTime1 = 0;
			BYTE btTemp = 0;
			int nRangingPos = nCurPos;
			memcpy(&btTemp, &DataBuffer[nCurPos], sizeof(BYTE));
			nCurPos += sizeof(BYTE);
			DWORD dwTemp = 0;
			CFunctions::getDWord(DataBuffer, &dwTemp, nCurPos);
			nCurPos += sizeof(DWORD);
			lTime1 = btTemp;
			lTime1 = lTime1 << 32;
			lTime1 |= dwTemp;

			double dbldist = 0;

			BYTE btAntenna = 0;
			memcpy(&btAntenna, &DataBuffer[nCurPos], sizeof(BYTE));
			nCurPos += sizeof(BYTE);
			btAntenna = btAntenna & 0xFF;

			// 分站时间同步序列号
			WORD wSyncNum = 0;
			CFunctions::getWord(DataBuffer, &wSyncNum, nCurPos);
			nCurPos += sizeof(WORD);
			// 信号强度
			WORD wStrength = 0;
			CFunctions::getWord(DataBuffer, &wStrength, nCurPos);
			nCurPos += sizeof(WORD);

			double dblaccx, dblaccy, dblaccz;
			dblaccx = dblaccy = dblaccz = 0;

			b_exec = true;
			sprintf_s(sql, LENGTH_SQL,
				"INSERT IGNORE INTO his_raw_data_tdoa(card_id, reader_id, antenna_id, reader_stamp, card_stamp, \
				fly_time, distance, ranging_type, power_state, accelerate, his_time, rec_time, sync_num, strength, acc_x, acc_y, acc_z) \
				VALUES(%s, %d, %d, %d, %d, %lld, %4.f, %d, %d, %d, '%s', '%s', %d, %d, %4.f, %4.f, %4.f);",
				str_card_id.c_str(), reader_id, btAntenna, wTickCount, wCardTickCount, lTime1, dbldist, btType, 
				btPower,btAcceleration,	CFunctions::wc2c(strHistTime), CFunctions::wc2c(strTime), wSyncNum, wStrength, dblaccx, dblaccy, dblaccz);
			break;
		}
	case CT_PERSON:
		{
			break;
		}
	default:
		{
			break;
		}						
	}

	try
	{
		if(b_exec){
			execute_sql(sql);
		}
	}
	catch (...)
	{
	}
}

void CYAServerDlg::parse_data_locate_card_his_sync_time( BYTE* DataBuffer, int nLen, CString strTime, CString strHistTime, WORD wChr )
{
	char sql[LENGTH_SQL] = {0};
	bool b_exec = false;
	int nCurPos = 0;

	DWORD dwReaderID = 0; // 本机分站号
	CFunctions::getDWord(DataBuffer, &dwReaderID, nCurPos);
	nCurPos += sizeof(DWORD);

	BYTE btAnt = 0; // 本机发送天线
	memcpy(&btAnt, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	DWORD dwUpperReaderID = 0; // root分站号
	CFunctions::getDWord(DataBuffer, &dwUpperReaderID, nCurPos);
	nCurPos += sizeof(DWORD);

	BYTE btUpperAnt = 0; // root天线
	memcpy(&btUpperAnt, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	WORD wSyncNum = 0; // 序列号
	CFunctions::getWord(DataBuffer, &wSyncNum, nCurPos);
	nCurPos += sizeof(WORD);

	WORD wSyncLevel = 0; // 同步等级
	CFunctions::getWord(DataBuffer, &wSyncLevel, nCurPos);
	nCurPos += sizeof(WORD);

	LONG64 lTime1 = 0, lTime2 = 0;
	BYTE btTemp = 0;
	memcpy(&btTemp, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	DWORD dwTemp = 0;
	CFunctions::getDWord(DataBuffer, &dwTemp, nCurPos);
	nCurPos += sizeof(DWORD);
	lTime1 = btTemp; // 本机发送时间戳
	lTime1 = lTime1 << 32;
	lTime1 |= dwTemp;

	btTemp = 0;
	dwTemp = 0;
	memcpy(&btTemp, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);
	CFunctions::getDWord(DataBuffer, &dwTemp, nCurPos);
	nCurPos += sizeof(DWORD);
	lTime2 = btTemp; // 本机接收时间戳
	lTime2 = lTime2 << 32;
	lTime2 |= dwTemp;

	DWORD dwRootReaderID = 0; // root分站号
	BYTE btRootAnt = 0; // root天线

	if(CHAR_READER_SYNC_TIME_ROOT == wChr){
		CFunctions::getDWord(DataBuffer, &dwRootReaderID, nCurPos);
		nCurPos += sizeof(DWORD);

		memcpy(&btRootAnt, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
	}

	sprintf_s(sql, LENGTH_SQL,
		"INSERT IGNORE INTO his_raw_data_sync_time(reader_id, ant_id, parent_reader_id, parent_ant_id, sync_num, sync_level,\
		send_timestamp, rec_timestamp, his_time, rec_time, root_reader_id, root_ant_id) \
		VALUES(%d, %d, %d, %d, %d, %d, %lld, %lld, '%s', '%s', %d, %d);",
		dwReaderID, btAnt, dwUpperReaderID, btUpperAnt , wSyncNum, wSyncLevel, lTime1, lTime2,
		CFunctions::wc2c(strHistTime), CFunctions::wc2c(strTime), dwRootReaderID, btRootAnt);

	try
	{
		execute_sql(sql);
	}
	catch (...)
	{
	}
}

void CYAServerDlg::OnEnUpdateEditReaderid()
{
	// TODO:  在此添加控件通知处理程序代码
	UpdateData(TRUE);
}

void CYAServerDlg::parse_json_data_call_card_cancel(message::ptr const& data )
{
	//EnterCriticalSection(&m_csCallInfo);

	CString strlog;
	string call_id, user_name, call_time;
	string cardid, readerid;
	int call_time_out, reader_count, card_count;

	map<string,message::ptr> data_map = data->get_map()[JSON_ROOT_KEY_DATA]->get_map();

	call_id = data_map[JSON_KEY_CALL_CARD_CALL_ID]->get_string();
	user_name = data_map[JSON_KEY_CALL_CARD_USER_NAME]->get_string();
	call_time = data_map[JSON_KEY_CALL_CARD_CALL_TIME]->get_string();

	vector<message::ptr> reader_vec = data_map[JSON_KEY_CALL_CARD_STATIONS]->get_vector();
	vector<message::ptr> card_vec = data_map[JSON_KEY_CALL_CARD_CARDS]->get_vector();

	if(reader_vec.size() == 0 && card_vec.size() == 0)
	{
		return;
	}

	int reader_id, npos;
	SocketMap::iterator it_sock;
	BYTE buf[LENGTH_SEND_BUF];

	std::shared_ptr<_call_info_user> call_user;
	std::shared_ptr<_call_info_reader> call_reader;
	_call_info_card* call_card;
	//取消呼叫有两种：
	//取消全员呼叫
	//对指定卡取消呼叫

	CallInfoUserMap::iterator it_call_user = mp_user_call_info.find(user_name);
	if(it_call_user == mp_user_call_info.end())
	{
		//LeaveCriticalSection(&m_csCallInfo);
		return ;
	}

	vector<message::ptr>::const_iterator it_reader = reader_vec.begin();
	if(reader_vec.size() > 0){
		for(; it_reader != reader_vec.end(); ++it_reader){
			string s_reader_id = (*it_reader)->get_map()[JSON_KEY_CALL_CARD_STATION_ID]->get_string();
			reader_id = atoi(s_reader_id.c_str());
			if (reader_id == 0)
			{
				CallInfoReaderMap::iterator it_reader = it_call_user->second->mpReader.find(reader_id);
				if (it_reader != it_call_user->second->mpReader.end())
				{
					call_reader = it_reader->second;
				}else{
					continue;
				}
				call_reader->is_start_call = false;
				call_reader->is_call_all = false;

				vector<message::ptr>::const_iterator it_card = card_vec.begin();
				if(card_vec.size() == 0 || "" == (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string()){
					if(call_reader->cards_count){
						CallInfoCardMap::iterator it_reader_card = call_reader->mpCard.begin();
						for(; it_reader_card != call_reader->mpCard.end();){
							it_reader_card = call_reader->mpCard.erase(it_reader_card);
						}
					}
					call_reader->mpCard.clear();
					call_reader->cards_count = 0;
				}else{
					BYTE card_type = 0;
					for(; it_card != card_vec.end(); ++it_card){
						string s_card_id = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string();
						string s_card_type = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID]->get_string();

						CallInfoCardMap::iterator it_call_card = call_reader->mpCard.find(s_card_id);
						if(it_call_card != call_reader->mpCard.end()){ // 已在呼叫列表
							call_reader->mpCard.erase(it_call_card);
						}
					}
					if(call_reader->mpCard.size() == 0){
						call_reader->mpCard.clear();
						it_call_user->second->mpReader.erase(0);
					}
				}
			}else{
				CallInfoReaderMap::iterator it_call_reader = it_call_user->second->mpReader.find(reader_id);
				if(it_call_reader != it_call_user->second->mpReader.end()){
					call_reader = it_call_reader->second;
					call_reader->is_start_call = false;
					call_reader->is_call_all = false;

					vector<message::ptr>::const_iterator it_card = card_vec.begin();
					if(card_vec.size() == 0 || "" == (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string()){
						if(call_reader->cards_count){
							CallInfoCardMap::iterator it_reader_card = call_reader->mpCard.begin();
							for(; it_reader_card != call_reader->mpCard.end();){
								call_reader->mpCard.erase(++it_reader_card);
							}
						}
						call_reader->mpCard.clear();
						it_call_user->second->mpReader.erase(it_call_reader);
						call_reader->cards_count = 0;
					}else{
						BYTE card_type = 0;
						for(; it_card != card_vec.end(); ++it_card){
							string s_card_id = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string();
							string s_card_type = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID]->get_string();

							CallInfoCardMap::iterator it_call_card = call_reader->mpCard.find(s_card_id);
							if(it_call_card != call_reader->mpCard.end()){ // 已在呼叫列表
								call_reader->mpCard.erase(it_call_card);
							}
						}
						if(call_reader->mpCard.size() == 0){
							call_reader->mpCard.clear();
							it_call_user->second->mpReader.erase(it_call_reader);
						}
					}
					call_reader->cards_count = 0;
				}
			}
		}
	}

	it_reader = reader_vec.begin();
	if(it_reader == reader_vec.end() && card_vec.size() > 0){
		vector<message::ptr>::const_iterator it_card = card_vec.begin();
		BYTE card_type = 0;
		for(; it_card != card_vec.end(); ++it_card){
			string s_card_id = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string();
			string s_card_type = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID]->get_string();

			int reader_id = mp_card_list_down_adhoc.find(s_card_id)->second->reader_id;

			call_reader = it_call_user->second->mpReader.find(reader_id)->second;
			call_reader->is_start_call = false;
			CallInfoCardMap::iterator it_call_card = call_reader->mpCard.find(s_card_id);
			if(it_call_card != call_reader->mpCard.end()){ // 已在呼叫列表
				call_reader->mpCard.erase(it_call_card);
			}
		}
	}

	//取消呼叫
	Json::Value root;
	Json::Value resp_data;
	Json::Value callinfo;
	Json::Value stations;
	Json::Value cards;

	callinfo[JSON_KEY_CALL_CARD_CALL_ID]   = call_id;
	callinfo[JSON_KEY_CALL_CARD_CALL_TIME] = call_time;
	callinfo[JSON_KEY_CALL_CARD_USER_NAME] = user_name;

	//构造stations和cards
	for (vector<message::ptr>::const_iterator it_reader = reader_vec.begin();it_reader != reader_vec.end();++it_reader)
	{
		Json::Value station;
		string s_reader_id = (*it_reader)->get_map()[JSON_KEY_CALL_CARD_STATION_ID]->get_string();
		station[JSON_KEY_CALL_CARD_STATION_ID] = s_reader_id;
		stations.append(station);
	}
	for (vector<message::ptr>::const_iterator it_card = card_vec.begin();it_card != card_vec.end();++it_card)
	{
		Json::Value card;

		card[JSON_KEY_CALL_CARD_CARD_ID] = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_ID]->get_string();
		card[JSON_KEY_CALL_CARD_CARD_TYPE_ID] = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID]->get_string();
		cards.append(card);
	}

	callinfo[JSON_KEY_CALL_CARD_STATIONS] = stations;
	callinfo[JSON_KEY_CALL_CARD_CARDS]    = cards;

	std::string ret = "";

	if(callinfo.size() > 0){
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_CALL_CARD_CANCEL_RESPONSE;
		root[JSON_ROOT_KEY_DATA] = callinfo;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		ret = root.toFastString();
		send_json_data(JSON_CMD_VALUE_PUSH,ret);
	}

	//LeaveCriticalSection(&m_csCallInfo);
	strlog.Format(_T("%s%s"), _T(LOG_CANCEL_CALL_CARD), _T(LOG_SUCCESS));
	show_log(strlog);
}

void CYAServerDlg::OnAbout()
{
	// TODO: 在此添加命令处理程序代码
	CAboutDlg dlg;
	dlg.DoModal();
}

void CYAServerDlg::OnReConnect( unsigned, unsigned )
{
	is_websocket_login = false;
	is_websocket_ok = false;
}

int CYAServerDlg::init_patrol_info(std::string card_id) //int task_id)
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	if(pConn == NULL){
		return 1;
	}

	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};

	if(card_id == ""){
		sprintf_s(buf, "select pt.patrol_task_id, s.card_id, pt.staff_id, pt.start_time, pt.end_time,\
					   ppd.patrol_point_id, ppd.idx, ppd.duration_last, ppd.duration_stay_min, ppd.duration_stay_max,\
					   ppd.duration_ranging, ps.x, ps.y, ps.z, ps.map_id, ps.ranging, pt.patrol_path_id\
					   from dat_patrol_task pt, dat_patrol_path_detail ppd, dat_patrol_point ps, dat_staff s\
					   where pt.patrol_path_id = ppd.patrol_path_id and ppd.patrol_point_id = ps.patrol_point_id\
					   and pt.card_id = s.card_id -- and pt.end_time >= curtime()\
					   and not exists(select 1 from dat_patrol_task where staff_id = pt.staff_id and start_time < pt.start_time)\
					   order by pt.patrol_task_id, ppd.idx");
	}else{
		sprintf_s(buf, "select pt.patrol_task_id, pt.card_id, s.staff_id, pt.start_time, pt.end_time,\
					   ppd.patrol_point_id, ppd.idx, ppd.duration_last, ppd.duration_stay_min, ppd.duration_stay_max,\
					   ppd.duration_ranging, ps.x, ps.y, ps.z, ps.map_id, ps.ranging, pt.patrol_path_id\
					   from dat_patrol_task pt, dat_patrol_path_detail ppd, dat_patrol_point ps, dat_staff s\
					   where pt.card_id = %s and pt.patrol_path_id = ppd.patrol_path_id and ppd.patrol_point_id = ps.patrol_point_id\
					   and pt.card_id = s.card_id -- and pt.end_time >= curtime()\
					   and not exists(select 1 from dat_patrol_task where staff_id = pt.staff_id and start_time < pt.start_time)\
					   order by pt.patrol_task_id, ppd.idx;", card_id.c_str());
	}

	pRes = pConn->Execute(buf, err);

	if (err)
	{
		return 1;
	}

	std::shared_ptr<PatrolTask> pTask = nullptr;
	std::shared_ptr<PatrolPoint> pPatrolPoint = nullptr;
	int nRow = 0;
	int tmp_task_id = 0, last_task_id = 0;
	int tmp_duration = 0;
	std::string tmp_time;
	while(pRow = mysql_fetch_row(pRes)){
		tmp_task_id = atoi(pRow[0]);
		if(tmp_task_id != last_task_id){
			last_task_id = tmp_task_id;
			nRow++;

			PatrolTaskCheckMap::iterator it_card_task = mp_card_task_list.find(pRow[1]); // 卡的任务列表
			if(it_card_task != mp_card_task_list.end()){
				pTask = it_card_task->second; // 查找到本条任务
			}else{
				pTask = std::make_shared<PatrolTask>();
				pTask->patrol_task_id = atoi(pRow[0]);
				pTask->card_id = pRow[1];
				pTask->starffer_id = pRow[2];
				pTask->patrol_path_id = atoi(pRow[16]);
				//tmp_time = pRow[3];
				API_StringToTime(pRow[3], pTask->start_time);
				API_StringToTime(pRow[4], pTask->end_time);
				mp_card_task_list.insert(make_pair(pRow[1], pTask));
			}

			tmp_duration = 0;
		}		
		tmp_duration += atoi(pRow[12]);
		PatrolPointMap::iterator it_point = pTask->mpPoint.find(atoi(pRow[5]));
		if(it_point != pTask->mpPoint.end()){
			pPatrolPoint = it_point->second;
		}else{
			pPatrolPoint = std::make_shared<PatrolPoint>();
			pPatrolPoint->idx = atoi(pRow[5]);
		}
		pPatrolPoint->patrol_point_id = atoi(pRow[6]);
		pPatrolPoint->x = atof(pRow[7]);
		pPatrolPoint->y = atof(pRow[8]);
		pPatrolPoint->z = atof(pRow[9]);
		pPatrolPoint->map_id = atoi(pRow[10]);
		pPatrolPoint->ranging = atof(pRow[11]);
		pPatrolPoint->duration_last = tmp_duration; //atoi(pRow[12]);
		pPatrolPoint->duration_stay_min = atoi(pRow[13]);
		pPatrolPoint->duration_stay_max = atoi(pRow[14]);
		pPatrolPoint->duration_ranging = atoi(pRow[15]);
	}
	mysql_free_result(pRes);
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_PATROL), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;	
}

void CYAServerDlg::deal_call_edit_patrol_task( string id, EDIT_TYPE_ID edit_type_id )
{
	CString strlog = _T("");
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			init_patrol_info(id);
			break;
		}
	case ET_UPDATE:
		{
			init_patrol_info(id);
			break;
		}
	case ET_DELETE:
		{
			PatrolTaskCheckMap::iterator it_task = mp_card_task_list.begin();
			for(; it_task != mp_card_task_list.end(); ++it_task){
				if(it_task->second->card_id == id){
					mp_card_task_list.erase(it_task);
					break;
				}
			}
			break;
		}
	default:
		break;
	}
	strlog.Format(_T("%s%s"), _T(LOG_EDIT_PATROL_TASK), _T(LOG_SUCCESS));
	show_log(strlog);
}

void CYAServerDlg::check_patrol()
{
	std::shared_ptr<PatrolTask> pTask = nullptr;
	std::shared_ptr<Card> pCard = nullptr;
	std::shared_ptr<PatrolPoint> pPoint, pNextPoint = nullptr;
	double cur_point_dist = 0;
	time_t tmp_time = time(NULL);
	PatrolTaskCheckMap::iterator it_card_task = mp_card_task_list.begin();
	for(; it_card_task != mp_card_task_list.end(); ++it_card_task){
		pTask = it_card_task->second;
		CardMap::iterator it_card = mp_card_list_down_person.find(pTask->card_id);
		if(it_card != mp_card_list_down_person.end()){
			pCard = it_card->second;
			PatrolPointMap::iterator it_point = pTask->mpPoint.find(pTask->cur_point_idx); //

			if(it_point != pTask->mpPoint.end()){
				pPoint = it_point->second;
				pNextPoint = (++it_point)->second;
				cur_point_dist = sqrt(pow(pCard->x - pPoint->x, 2) + pow(pCard->y - pPoint->y, 2) + pow(pCard->z - pPoint->z, 2));
				if(!pTask->is_in_cur_point){ // 未进入当前节点区域
					if(cur_point_dist < pPoint->ranging){ // 在合法范围内
						pTask->is_in_cur_point = true;
						pTask->enter_time = tmp_time;
						// 当前时间小于应到时间
						if(difftime(pTask->start_time, tmp_time) < (pPoint->duration_last - pPoint->duration_ranging) * 60){
							// 早到						
							pTask->state = PS_EARLY;
						}else if(difftime(pTask->start_time, tmp_time) <= (pPoint->duration_last + pPoint->duration_ranging ) * 60 &&  // 在合理时间范围
							difftime(pTask->end_time, tmp_time) >= (pPoint->duration_last - pPoint->duration_ranging) * 60){
								// 正常
								pTask->state = PS_NORMAL;
						}else if(difftime(pTask->start_time, tmp_time) > (pPoint->duration_last + pPoint->duration_ranging) * 60){ // 超过最晚应到时间
							// 迟到
							pTask->state = PS_LATE;
						}
					}else{ // 不再范围内，判断是否超过最晚应到时间，超过，直接按未到计算（即按照下一节点计算）
						if(difftime(pTask->start_time, tmp_time) > (pPoint->duration_last + pPoint->duration_ranging) * 60){
							pTask->state = PS_NON_ARRIVAL;
							//保存数据本节点数据
							save_patrol_data(pTask, pPoint);
							pTask->cur_point_idx++;
						}
					}					
				}else{ // 已进入当前节点区域
					if(cur_point_dist > pPoint->ranging){ // 在合法范围外，即离开合法范围
						pTask->is_in_cur_point = false;
						pTask->leave_time = tmp_time;

						pTask->duration_stay = difftime(pTask->leave_time, pTask->enter_time);
						if(pTask->duration_stay < pPoint->duration_stay_min){
							pTask->stay_state = PSS_TOO_SHORT;
						}else if(pTask->duration_stay <= pPoint->duration_stay_max){
							pTask->stay_state = PSS_NORMAL;
						}else{
							pTask->stay_state = PSS_TOO_LONG;
						}

						// 保存本节点数据
						save_patrol_data(pTask, pPoint);
						pTask->cur_point_idx++;
					}
				}				
			}
		}
	}
}

void CYAServerDlg::save_patrol_data( std::shared_ptr<PatrolTask> pTask, std::shared_ptr<PatrolPoint> pPoint )
{
	char sql[LENGTH_SQL] = {'\0'};
	char _time[STR_LEN_TIME], _time_ex[STR_LEN_TIME];
	struct tm local_time, local_time_ex;
	localtime_s(&local_time, &pTask->enter_time);
	localtime_s(&local_time_ex, &pTask->leave_time);
	strftime(_time, 30, "%Y-%m-%d %H:%M:%S", &local_time);
	strftime(_time_ex, 30, "%Y-%m-%d %H:%M:%S", &local_time_ex);

	sprintf_s(sql, LENGTH_SQL, 
		"INSERT IGNORE INTO his_patrol_data(patrol_task_id, patrol_path_id, patrol_point_id, idx, enter_time, leave_time, patrol_state_id, patrol_stay_state_id, card_id)\
		values(%d, %d, %d, %d, '%s', '%s', %d, %d, '%s');",
		pTask->patrol_task_id, pTask->patrol_path_id, pPoint->patrol_point_id, pPoint->idx, _time, _time_ex, pTask->state, pTask->stay_state, pTask->card_id);
	execute_sql(sql);

	CardMap::iterator it_card = mp_card_list_down_person.find(pTask->card_id);
	if(it_card != mp_card_list_all.end())
	{
		INT64 ev_id = it_card->second->m_event_list[ET_CARD_PATROL_ERROR];
		if(0 == ev_id) // 之前没有告警
		{
			if(pTask->state != PS_NORMAL || pTask->stay_state != PSS_NORMAL) // 现在有告警
			{
				ev_id = CFunctions::GetMicroSecond();
				std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
				ev->status = ES_START;
				ev->ev_type = ET_CARD_PATROL_ERROR;
				ev->obj_type = OT_CARD;
				ev->obj_id = it_card->first;
				ev->cur_time = time(NULL);

				ev->map_id = it_card->second->map_id;
				ev->area_id = it_card->second->area_id;
				ev->x = it_card->second->x;
				ev->y = it_card->second->y;
				ev->landmarkid = it_card->second->landmark_id;
				ev->landmarkdirect = it_card->second->landmark_direction;
				ev->landmarkdist = it_card->second->landmark_dis;

				ev->is_sent = false;

				it_card->second->m_event_list[ET_CARD_PATROL_ERROR] = ev_id;
				store_data_event(ev);
				add_event(ev);
				Sleep(1);
			}
		}
		else
		{
			EventMap::iterator it_ev = mp_event_list->find(ev_id);
			if(it_ev != mp_event_list->end()){
				if(pTask->state == PS_NORMAL && pTask->stay_state == PSS_NORMAL) // 之前有告警，当前告警结束
				{
					it_ev->second->status = ES_END;
					it_ev->second->cur_time = time(NULL);

					it_ev->second->map_id = it_card->second->map_id;
					it_ev->second->area_id = it_card->second->area_id;
					it_ev->second->x = it_card->second->x;
					it_ev->second->y = it_card->second->y;
					it_ev->second->landmarkid = it_card->second->landmark_id;
					it_ev->second->landmarkdirect = it_card->second->landmark_direction;
					it_ev->second->landmarkdist = it_card->second->landmark_dis;

					it_ev->second->is_sent = false;
					store_data_event(it_ev->second);
					add_event(it_ev->second);

					it_card->second->m_event_list[ET_CARD_PATROL_ERROR] = 0;
				}
				else // 更新告警信息
				{
					it_ev->second->status = ES_START;
					it_ev->second->cur_time = time(NULL);

					it_ev->second->map_id = it_card->second->map_id;
					it_ev->second->area_id = it_card->second->area_id;
					it_ev->second->x = it_card->second->x;
					it_ev->second->y = it_card->second->y;
					it_ev->second->landmarkid = it_card->second->landmark_id;
					it_ev->second->landmarkdirect = it_card->second->landmark_direction;
					it_ev->second->landmarkdist = it_card->second->landmark_dis;

					it_ev->second->is_sent = false;
				}	
			}
		}
	}
}

int CYAServerDlg::delete_patrol_info( std::string card_id )
{
	return 0;

	PatrolTaskCheckMap::iterator it_card_task = mp_card_task_list.find(card_id); // 卡的任务列表
	if(it_card_task != mp_card_task_list.end()){
		mp_card_task_list.erase(it_card_task);
	}
	return 0;
}

int CYAServerDlg::get_special_area_id(shared_ptr<Card> card)
{
	int specail_area_id = -1;	
	SpecilaAreaEntryMap::iterator it = mp_special_area_entry_list.begin();
	for(; it != mp_special_area_entry_list.end(); ++it)
	{
		if((card->x <= max(it->second->start_point_x, it->second->end_point_x))
			&&(card->x >= min(it->second->start_point_x, it->second->end_point_x))
			&&(card->y <= max(it->second->start_point_y, it->second->end_point_y))
			&&(card->y >= min(it->second->start_point_y, it->second->end_point_y))
			&&(card->z <= max(it->second->start_point_z, it->second->end_point_z))
			&&(card->z >= min(it->second->start_point_z, it->second->end_point_z)))
		{
			specail_area_id = it->second->special_area_id;
			break;
		}
	}
	return specail_area_id;
}
void CYAServerDlg::deal_card_lost_state()
{
	time_t time_current = time(NULL);
	STATUS_CARD nLost = STATUS_NORMAL;

	std::shared_ptr<Card> card = nullptr;

	CardMap::iterator it_staff = mp_card_list_down_person.begin();
	for (; it_staff != mp_card_list_down_person.end();)
	{
		nLost = difftime(time_current, it_staff->second->rec_time) < CARD_LOST_TIME_OUT ? STATUS_NORMAL : STATUS_LOST;
		card = nullptr;
		if (it_staff->second->status_lost != nLost)
		{
			it_staff->second->status_lost = nLost;
			if (nLost == STATUS_LOST)
			{
				card = it_staff->second;
			}
		}
		++it_staff;

		if(card)
		{
			card->reset();
			//if(PDT_UP == card->PosState())
			//{
			//	card_enter_mine(card, POS_DEVICE_TYPE::PDT_UP);
			//	remove_card(card->card_id);
			//}
		}
	}

	nLost = STATUS_NORMAL;
	card = nullptr;
	CardMap::iterator it_vehicle = mp_card_list_down_vehicle.begin();
	for(; it_vehicle != mp_card_list_down_vehicle.end(); ){
		nLost = difftime(time_current, it_vehicle->second->rec_time) < CARD_LOST_TIME_OUT ? STATUS_NORMAL :STATUS_LOST;

		card = it_vehicle->second;
		++it_vehicle;

		// 丢失数据
		if(card->status_lost != nLost)
		{
			if(STATUS_LOST == nLost)
			{
				if(1 == card->is_driving_face_start)
				{
					process_driving_face_end_service(card);
				}
				AreaMap::iterator it_area_cur = mp_area_list.find(card->area_id);
				if(it_area_cur != mp_area_list.end())
				{
					//check state is static or not
					if(0 == card->accelerate_state)
					{
						//static: do nothing but set speed to 0
						card->v = 0;
					}
					else
					{
						// 处理非特殊区域的卡
						if(0 == it_area_cur->second->is_special()){
							// check area is special or not
							int special_area_id = get_special_area_id(card);
							if(-1 != special_area_id)
							{
								card->status_lost = nLost;
								card_leave_area(card, it_area_cur->second);
								store_data_card(card, HIS_AREA_LOCATION_LEAVE);

								card_enter_special_area(card, special_area_id);
								send_json_data(JSON_CMD_VALUE_PUSH, get_json_special_area_process(card));
								debug_print_syslog(0, "lost state, moving: %s", get_json_special_area_process(card).c_str());
							}
							else
							{
								// 非特殊区域超过CARD_LOST_TIME_OUT秒，未接收到数据，升井处理
<<<<<<< HEAD
								if(difftime(time_current, card->rec_time) > CARD_LOST_TIME_OUT)
=======
								if(difftime(time_current, card->rec_time) > CARD_LOST_TIME_OUT_SPECIAL_AREA)
>>>>>>> newprotocal
								{
									card->status_lost = nLost;
									card_enter_mine(card, POS_DEVICE_TYPE::PDT_UP);
									debug_print_syslog(0, "lost state, not enter special area: card_id: %s, area_id:%d, speed: %f, x: %f, y: %f, z: %f\n", 
										(card->card_id).c_str(), card->area_id, card->get_speed(), card->x, card->y, card->z);
								}
							}
						}	    
					}	
				}
			}
			else
			{
				card->status_lost = nLost;
			}
			card->reset();
		}
	}
}

void CYAServerDlg::store_data_event( std::shared_ptr<YaEvent> ev )
{
	char sql[LENGTH_SQL] = {'\0'};
	char _time[STR_LEN_TIME];
	struct tm local_time;
	localtime_s(&local_time, &ev->cur_time);
	strftime(_time, STR_LEN_TIME, "%Y-%m-%d %H:%M:%S", &local_time);

	sprintf_s(sql, LENGTH_SQL, 
		"INSERT IGNORE INTO his_event_data(event_id, stat, event_type_id, obj_type_id, obj_id, \
		map_id, area_id, limit_value, cur_value, x, y, cur_time, description)\
		VALUES(%lld, %d, %d, %d, %s, %d, %d, %.2f, %.2f, %f, %f, '%s', '%s');",
		ev->get_id(), ev->status, ev->ev_type, ev->obj_type, ev->obj_id.c_str(), 
		ev->map_id, ev->area_id, ev->limit_value, ev->cur_value, ev->x, ev->y, _time, ev->desc.c_str());
	execute_sql(sql);
}

void CYAServerDlg::add_event( std::shared_ptr<YaEvent> ev )
{
	EventMap::iterator it_ev = mp_event_list->find(ev->get_id());
	if(it_ev != mp_event_list->end()){
		it_ev->second->status = ev->status ;
		it_ev->second->ev_type = ev->ev_type;
		it_ev->second->obj_type = ev->obj_type;
		it_ev->second->obj_id = ev->obj_id;
		it_ev->second->cur_time = ev->cur_time;
		it_ev->second->map_id = ev->map_id;
		it_ev->second->area_id = ev->area_id;
		it_ev->second->x = ev->x;
		it_ev->second->y = ev->y;
		it_ev->second->limit_value = ev->limit_value;
		it_ev->second->cur_value = ev->cur_value;
		it_ev->second->is_sent = ev->is_sent;
	}else{
		mp_event_list->insert(make_pair(ev->get_id(), ev));
	}
}

std::string CYAServerDlg::get_json_event()
{
	Json::Value root;
	Json::Value data;

	char _time[STR_LEN_TIME];
	struct tm local_time;
	char ev_id[STR_LEN_TIME];

	if(mp_event_list->empty()){return "";}

	EventMap::iterator it_ev = mp_event_list->begin();
	for(; it_ev != mp_event_list->end();){
		if(!it_ev->second->is_sent){
			Json::Value ev;
			sprintf_s(ev_id, "%lld", it_ev->second->get_id());
			ev[JSON_KEY_EVENT_EVENT_ID] = ev_id;
			ev[JSON_KEY_EVENT_STATUS] = it_ev->second->status;
			ev[JSON_KEY_EVENT_TYPE_ID] = it_ev->second->ev_type;
			ev[JSON_KEY_EVENT_OBJ_TYPE_ID] = it_ev->second->obj_type;
			ev[JSON_KEY_EVENT_OBJ_ID] = it_ev->second->obj_id;
			ev[JSON_KEY_EVENT_MAP_ID] = it_ev->second->map_id;
			ev[JSON_KEY_EVENT_AREA_ID] = it_ev->second->area_id;
			ev[JSON_KEY_EVENT_X] = it_ev->second->x;
			ev[JSON_KEY_EVENT_Y] = it_ev->second->y;
			ev[JSON_KEY_EVENT_LIMIT_VALUE] = it_ev->second->limit_value;
			ev[JSON_KEY_EVENT_CUR_VALUE] = it_ev->second->cur_value;
			ev[JSON_KEY_EVENT_LANDMARK_ID] = it_ev->second->landmarkid;
			ev[JSON_KEY_EVENT_LANDMARK_DIRECTION] = it_ev->second->landmarkdirect;
			ev[JSON_KEY_EVENT_LANDMARK_DISTANCE] = it_ev->second->landmarkdist;


			localtime_s(&local_time, &it_ev->second->cur_time);
			strftime(_time, STR_LEN_TIME, "%Y-%m-%d %H:%M:%S", &local_time);
			ev[JSON_KEY_EVENT_CUR_TIME] = _time;

			data.append(ev);

			it_ev->second->is_sent = true;

			++it_ev;
		}else{
			if(it_ev->second->status == ES_END){ // 删除
				it_ev = mp_event_list->erase(it_ev);
			}else{
				++it_ev;
			}
		}
	}

	std::string ret = "";
	if(data.size() > 0){
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_EVENT;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		root[JSON_ROOT_KEY_DATA] = data;
		//ret = root.toFastString();
		ret = root.toFastString();
	}

	return ret;
}

std::string CYAServerDlg::get_json_new_device_state()
{
	std::string ret = "";
	Json::Value root;	
	Json::Value data;

	MapInfoMap::iterator it_map = mp_map_list.begin();

	for(; it_map != mp_map_list.end(); ++it_map){
		//通信分站列表
		ReaderMap::iterator it_ctrl_reader = mp_ctrl_reader_list.begin();
		for (it_ctrl_reader;it_ctrl_reader!=mp_ctrl_reader_list.end();++it_ctrl_reader)
		{
			if (it_ctrl_reader->second->map_id != it_map->second->map_id)
			{
				continue;
			}

			Json::Value state_dev;
			state_dev.append(it_ctrl_reader->second->reader_id);
			state_dev.append(it_ctrl_reader->second->device_type_id);
			state_dev.append(it_ctrl_reader->second->reader_state);
			int ms = 1000; //转为ms
			//入井时间戳
			double t = *((int64_t*)&it_ctrl_reader->second->rec_time)*ms;
			state_dev.append(t);
			state_dev.append(it_map->second->map_id);
			state_dev.append(0);
			data.append(state_dev);
		}

		//红绿灯
		LightMap::iterator it_light = mp_light_list.begin();
		for (it_light;it_light!=mp_light_list.end();++it_light)
		{
			if (it_light->second->m_nMapID != it_map->second->map_id)
			{
				continue;
			}

			Json::Value state_dev;
			state_dev.append(it_light->second->m_nID);
			state_dev.append(it_light->second->device_type_id);
			state_dev.append(it_light->second->m_nShape);
			//state_dev.append(it_light->second->get_light_state());
			ReaderMap::iterator it_ctrl_reader = mp_ctrl_reader_list.find(it_light->second->m_nReaderID);
			double t = 0;
			if (it_ctrl_reader != mp_ctrl_reader_list.end())
			{
				int ms = 1000; //转为ms
				//入井时间戳
				t = *((int64_t*)&it_ctrl_reader->second->rec_time)*ms;				
			}
			state_dev.append(t);
			state_dev.append(it_map->second->map_id);
			state_dev.append(it_light->second->m_nIsCtrl);
			data.append(state_dev);
		}
	}

	if (data.size() > 0)
	{
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_DEV_STATE;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		root[JSON_ROOT_KEY_DATA] = data;
		ret = root.toFastString();
	}

	return ret;
}

std::string CYAServerDlg::get_json_count_area()
{
	Json::Value root;
	Json::Value data;

	Json::Value area;
	for (AreaMap::iterator it = mp_area_list.begin();it!=mp_area_list.end();++it)
	{
		Json::Value area_data;
		area_data.append(it->first);
		area_data.append(it->second->area_card_list_person->size());
		area.append(area_data);
	}
	data[JSON_KEY_COUNTING_AREA_PERSON_COUNT] = area;
	std::string ret = "";
	if (data.size() > 0)
	{
		root[JSON_ROOT_KEY_DATA] = data;
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_COUNTING;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		ret = root.toFastString();
	}

	return ret;
}

void CYAServerDlg::parse_data_lights_state( BYTE* DataBuffer, int& nCurPos, int reader_id, unsigned short wChr )
{
#ifdef DEBUG
	TRACE(_T("get state \r\n"));
#endif // DEBUG

	time_t cur_time = time(NULL);
	WORD wlen = 0; // 段长度 2 byte
	//CFunctions::getWord(DataBuffer, &wlen, nCurPos);
	//nCurPos += sizeof(WORD);
	wlen = 8;			//只针对认证，此处写死为8个


	BYTE btCmd = 0; // 控制码 1 byte 0x01 响应红绿灯设置状态 0x02 响应请求红绿灯状态
	memcpy(&btCmd, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	//BYTE btResult = 0; // 返回结果
	//memcpy(&btResult, &DataBuffer[nCurPos], sizeof(BYTE));
	//nCurPos += sizeof(BYTE);

	//// 段数据 
	//BYTE btDevType = 0; // 设备类型 1 byte 0x01灯，0x02 报警器，0x03 显示屏
	//memcpy(&btDevType, &DataBuffer[nCurPos], sizeof(BYTE));
	//nCurPos += sizeof(BYTE);

	// 设备类型 
	BYTE btDevType = 0; // 设备类型 1 byte ：0x00：读卡分站；0x01：控制分站；0x03：红绿灯；0x04：告警器；0x05：道岔；0x06：显示屏
	memcpy(&btDevType, &DataBuffer[nCurPos], sizeof(BYTE));
	nCurPos += sizeof(BYTE);

	if(btDevType == DEVICE_TYPE::DT_LIGHT){
		BYTE btId = 0; // 设备编号 1 byte
		memcpy(&btId, &DataBuffer[nCurPos], sizeof(BYTE));

		nCurPos += sizeof(BYTE);
		BYTE btCtrlState = 0; // 设备控制状态 1byte 0x01 自动控制，0x02 手动控制，0x03 故障
		memcpy(&btCtrlState, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		BYTE btColor = 0; // 颜色 1 byte 0x01 红色, 0x02 绿色
		memcpy(&btColor, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);
		BYTE btShape = 0; // 图案 1 byte 0x01 实心圆形，0x02 空心圆形，0x03 叉形，0x04 - 0x07 上下左右箭头，0xFF 警告闪烁
		memcpy(&btShape, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);

		LightMap::iterator it_light = mp_light_list.begin();
		for(; it_light != mp_light_list.end(); ++it_light){
			if(it_light->second->m_nPort == btId && it_light->second->m_nReaderID == reader_id){
				it_light->second->m_nColor = btColor;
				it_light->second->m_nShape = btShape;
				//it_light->second->m_nIsCtrl = btCtrlState;
				it_light->second->m_nIsCtrl = LIGHT_CTRL_STATE::CTRL_STATE_AUTO;
				it_light->second->rec_time = cur_time;
				break;
			}
		}
	}	
}

void CYAServerDlg::add_light_to_call_list( LIGHTS_SELECT_TYPE lst, LIGHT_COLOR clr, LIGHT_CTRL_STATE ctrl, int tkid, LIGHT_SHAPE ls, int light_id /*= 0*/ )
{
	if(lst == LIGHTS_SELECT_TYPE::LST_SOME_LIGHTS){
		LightCallMap::iterator it_light_call = mp_light_call_list->find(light_id);

		if(it_light_call != mp_light_call_list->end()){
			it_light_call->second->ctrl_color = clr;
			it_light_call->second->ctrl_type = ctrl;
			it_light_call->second->task_id = tkid;
			it_light_call->second->light_state = ls;
		}else{
			std::shared_ptr<LightCallInfo> pCall = std::make_shared<LightCallInfo>();
			pCall->ctrl_color = clr;
			pCall->ctrl_type = ctrl;
			pCall->light_id = light_id;
			pCall->task_id = tkid;
			pCall->light_state = ls;
			mp_light_call_list->insert(make_pair(light_id, pCall));
		}
		return ;
	}
	LightMap::iterator it_light = mp_light_list.begin();
	for(; it_light != mp_light_list.end(); ++it_light){
		if(LST_ALL_LIGHTS == lst){
			add_light_to_call_list(LIGHTS_SELECT_TYPE::LST_SOME_LIGHTS, clr, ctrl, tkid, ls, it_light->first);
		}else if(LST_ALL_UP_LIGHTS == lst && LIGHT_STREAM::UP_STREAM == it_light->second->m_nStream ){
			add_light_to_call_list(LIGHTS_SELECT_TYPE::LST_SOME_LIGHTS, clr, ctrl, tkid, ls, it_light->first);
		}else if(LST_ALL_DWON_LIGHTS == lst && LIGHT_STREAM::DOWN_STREAM == it_light->second->m_nStream){
			add_light_to_call_list(LIGHTS_SELECT_TYPE::LST_SOME_LIGHTS, clr, ctrl, tkid, ls, it_light->first);
		}
	}
}

void CYAServerDlg::send_call_light()
{
	LightCallMap::iterator it_light_call = mp_light_call_list->begin();
	for(; it_light_call != mp_light_call_list->end(); ++ it_light_call){
		send_call_light(CC_SET_LIGHTS_STATE,it_light_call->second->light_id, it_light_call->second->ctrl_type, it_light_call->second->ctrl_color,it_light_call->second->light_state);
		Sleep(2000);
	}
}

void CYAServerDlg::send_call_light(BYTE ctrl_cmd, int light_id, int ctrl_type, int ctrl_color,int light_shape)
{
	BYTE buf[LENGTH_SEND_BUF];

	SocketMap::iterator it_sock;
	LightMap::iterator it_light;

	int npos = 0;
	BYTE btCmd = ctrl_cmd, btDevType = DEVICE_TYPE::DT_LIGHT, btShape = light_shape;
	WORD wCrc;
	switch (ctrl_cmd)
	{
	case 0x01:
		it_light = mp_light_list.find(light_id);
		if(it_light != mp_light_list.end()){
			it_sock = mp_socket_list.find(CFunctions::c2wc(it_light->second->m_strIP.c_str()));
			if(it_sock != mp_socket_list.end()){
				memset(buf, 0, LENGTH_SEND_BUF);
				npos = 0;
				memcpy(&buf[npos], &btCmd, sizeof(BYTE)); // 控制码
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &btDevType, sizeof(BYTE)); // 设备类型
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &it_light->second->m_nPort, sizeof(BYTE)); // 设备ID
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &ctrl_type, sizeof(BYTE)); // 控制状态
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &ctrl_color, sizeof(BYTE)); // 颜色
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &btShape, sizeof(BYTE)); // 图案
				npos += sizeof(BYTE);

				//CRC校验
				wCrc = CFunctions::getCRC(&buf[0], npos); // 数据长度 + 特征字
				CFunctions::memcpyWord(&buf[0], wCrc, npos);
				npos += sizeof(WORD);

				BOOL ret = SendData(it_sock->second->dwConnID,CHAR_CTRL_READER_CMD, npos, buf);
#ifdef _DEBUG
				if (ret)
				{
					TRACE(_T("send successful. \r\n"));
				}else{
					TRACE(_T("send failed. \r\n"));
				}
#endif
			}
		}
		break;
	case 0x02:
		it_light = mp_light_list.find(light_id);
		if(it_light != mp_light_list.end()){
			it_sock = mp_socket_list.find(CFunctions::c2wc(it_light->second->m_strIP.c_str()));
			if(it_sock != mp_socket_list.end()){
				memset(buf, 0, LENGTH_SEND_BUF);
				npos = 0;
				memcpy(&buf[npos], &btCmd, sizeof(BYTE)); // 控制码
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &btDevType, sizeof(BYTE)); // 设备类型
				npos += sizeof(BYTE);
				memcpy(&buf[npos], &it_light->second->m_nPort, sizeof(BYTE)); // 设备ID
				npos += sizeof(BYTE);
				//CRC校验
				wCrc = CFunctions::getCRC(&buf[0], npos); // 数据长度 + 特征字
				CFunctions::memcpyWord(&buf[0], wCrc, npos);
				npos += sizeof(WORD);
				SendData(it_sock->second->dwConnID,CHAR_CTRL_READER_CMD, npos, buf);
			}
		}
		break;
	default:
		break;
	}
}

std::string CYAServerDlg::get_json_call_list()
{
	//呼叫
	//目前实现的方式，web端发起呼叫，通过采集和分站将呼叫信息下发到呼叫
	//卡将状态类型返回到指定某个字节表示收到了呼叫信息，卡需要保存是哪个分站将信息上传到采集的
	Json::Value root;	
	Json::Value data;
	double t = 0;
	for(CallInfoUserMap::iterator it_call_user = mp_user_call_info.begin(); it_call_user != mp_user_call_info.end(); ++it_call_user)
	{
		CallInfoReaderMap::iterator it_call_reader = it_call_user->second->mpReader.begin();
		for(; it_call_reader != it_call_user->second->mpReader.end(); ++ it_call_reader)
		{
			if (it_call_reader->first == 0)
			{
				if (it_call_reader->second->is_call_all)
				{
					for (CardMap::iterator it_card = mp_card_list_all.begin();it_card!=mp_card_list_all.end();++it_card)
					{
						if (it_card->second->call_type != 0)
						{
							Json::Value callinfo;
							Json::Value temp;
							callinfo.append(it_call_user->first);
							callinfo.append(it_card->second->card_id);
							callinfo.append(0);
							t = *((int64_t*)&it_card->second->recv_call_time)*1000;
							callinfo.append(t);
							callinfo.append(it_call_reader->second->call_type);
							callinfo.append(1);

							data.append(callinfo);

							//std::shared_ptr<_call_info_card> sp_call_card = std::shared_ptr<_call_info_card>();
							//sp_call_card->call_type = it_call_reader->second->call_type;
							//sp_call_card->card_type = it_card->card_type;
							//sp_call_card->str_card_id = it_card->card_id;
							//it_call_reader->second->mpCard.insert(make_pair(it_card->card_id,sp_call_card));
						}
					}
				}
			}else{
				CallInfoCardMap::iterator it_call_card = it_call_reader->second->mpCard.begin();
				for(; it_call_card != it_call_reader->second->mpCard.end(); ++ it_call_card)
				{
					Json::Value callinfo;
					Json::Value temp;
					callinfo.append(it_call_user->first);
					callinfo.append(it_call_card->second->str_card_id);
					temp = it_call_reader->first;
					callinfo.append(temp);
					t = *((int64_t*)&it_call_card->second->start_time)*1000;
					callinfo.append(t);
					callinfo.append(it_call_reader->second->call_type);
					callinfo.append(it_call_card->second->call_state);

					data.append(callinfo);
				}
			}
		}
	}

	std::string ret = "";
	if(data.size() > 0){
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_CALL_CARD_LIST;
		root[JSON_ROOT_KEY_DATA] = data;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION;
		ret = root.toFastString();
	}
	return ret;
}

bool CYAServerDlg::IsInLine( _point p1, _point p2, _point p3 )
{
	return true;
}

void CYAServerDlg::OnBnClickedButton1()
{
	//list<std::shared_ptr<POS>> his_pos;
	//his_pos.resize(0);

	//std::shared_ptr<POS> p1 = std::make_shared<POS>();
	//p1->posx = 4727;
	//p1->posy = -27.6;
	//p1->card_count = 4202;
	//his_pos.push_back(p1);

	//std::shared_ptr<POS> p2 = std::make_shared<POS>();
	//p2->posx = 4727;
	//p2->posy = -28.07;
	//p2->card_count = 4203;
	//his_pos.push_back(p2);

	//std::shared_ptr<POS> p3 = std::make_shared<POS>();
	//p3->posx = 4727;
	//p3->posy = -28.56;
	//p3->card_count = 4204;
	//his_pos.push_back(p3);

	//std::shared_ptr<POS> p4 = std::make_shared<POS>();
	//p4->posx = 4727;
	//p4->posy = -28.75;
	//p4->card_count = 4205;
	//his_pos.push_back(p4);

	//std::shared_ptr<POS> p5 = std::make_shared<POS>();
	//p5->posx = 4727;
	//p5->posy = -29.48;
	//p5->card_count = 4206;
	//his_pos.push_back(p5);

	//double dx[5],dy[5],dt[5];
	//std::vector<double> vx,vy,vt;
	//vx.resize(0);
	//vy.resize(0);
	//vt.resize(0);

	//int i = 0;
	//for (list<std::shared_ptr<POS>>::iterator it = his_pos.begin();it!=his_pos.end();++it)
	//{
	//	dt[i] = (*it)->card_count;
	//	vt.push_back(dt[i]);
	//	dx[i] = (*it)->posx;
	//	vx.push_back(dx[i]);
	//	dy[i] = (*it)->posy;
	//	vy.push_back(dy[i]);
	//	i++;
	//}

	//double cx[5],cy[5];
	//Fitting::EMatrix(dt,dx,5,3,cx);
	//Fitting::EMatrix(dt,dy,5,3,cy);
	//double fx[5] = {0} , fy[5] = {0};
	//for (int i=0;i<5;i++)
	//{
	//	fx[i] = Fitting::polyval(cx,dt[4] + i);
	//	fy[i] = Fitting::polyval(cy,dt[4] + i);
	//}	

	//Fit fit_x;
	//fit_x.linearFit(vt,vx);
	//Fit fit_y;
	//fit_y.linearFit(vt,vy);

	//double fx1[5],fy1[5];
	//for (int i = 0;i < 4;i++)
	//{
	//	fx1[i] = fit_x.getY(vt[4] + i);
	//	fy1[i] = fit_y.getY(vt[4] + i);
	//}

	ReadFileTest();
}

int CYAServerDlg::DivideCell(double width, std::shared_ptr<TDOAReaderPathMap> pTdoaReaderPathMap)
{
	if (abs(width) < 1E-2)
	{
		return 1;
	}

	int start_reader_id = 0;
	int end_reader_id = 0;
	
	bool bb = false;
	for (TDOAReaderPathMap::iterator it = pTdoaReaderPathMap->begin();it!=pTdoaReaderPathMap->end();++it)
	{
		bb = false;
		start_reader_id = it->first;
		ReaderInfo start_reader;
		start_reader.reader_id = start_reader_id;
		for (ReaderPathMap::iterator it_rpm = it->second->begin();it_rpm != it->second->end();++it_rpm)
		{
			end_reader_id = it_rpm->first;

			ReaderInfo end_reader;
			end_reader.reader_id = end_reader_id;

			string name1 = CFunctions::getCellName(start_reader_id,end_reader_id);
			string name2 = CFunctions::getCellName(end_reader_id,start_reader_id);

			//格子列表是否存在，存在则继续
			CellPathMap::iterator it = mpCellPath->find(name1);
			if (it != mpCellPath->end())
			{
				continue;
			}
			//分站35与分站36的格子表和分站36与分站35的格子表是一样的
			it = mpCellPath->find(name2);
			if (it != mpCellPath->end())
			{
				continue;
			}

			std::list<std::shared_ptr<Cell>> ltCell;
			ltCell.resize(0);

			double xStart = it_rpm->second->x[0];
			double yStart = it_rpm->second->y[0];
			start_reader.x = xStart;
			start_reader.y = yStart;

			double xEnd = it_rpm->second->x[1];
			double yEnd = it_rpm->second->y[1];
			end_reader.x = xEnd;
			end_reader.y = yEnd;

			double distance = sqrt(pow(xStart - xEnd,2) + pow(yStart - yEnd,2));
			int nCounts = 0;
			//ceil向上取整，floor向下取整
			nCounts = ceil(distance/width);

			//分站之间的格子始终按两分站从小到大的顺序
			for (int i = 0;i < nCounts;i++)
			{
				std::shared_ptr<Cell> cl = std::make_shared<Cell>();
				cl->strSubjectReader = name1;
				cl->id = i + 1;
				cl->minReaderId = 0;
				cl->maxReaderId = 0;

				if (start_reader < end_reader)
				{
					cl->minReaderId = start_reader.reader_id;
					cl->maxReaderId = end_reader.reader_id;
				} 
				else
				{
					cl->minReaderId = end_reader.reader_id;
					cl->maxReaderId = start_reader.reader_id;
				}	

				if (cl->id == nCounts)
				{
					//如果是最后一格,
					if (abs(xStart - xEnd) < 1E-2)
					{
						//如果在Y轴上
						if (yStart < yEnd)
						{
							cl->left.x = cl->top.x = (xStart - width/2);
							cl->right.x = cl->bottom.x = (xStart + width/2);
							cl->right.y = cl->top.y = (yStart + i*width);
							cl->left.y = cl->bottom.y = yEnd;
						}else{
							cl->left.x = cl->top.x = (xEnd - width/2);
							cl->right.x = cl->bottom.x = (xEnd + width/2);
							cl->right.y = cl->top.y = yStart + i*width;
							cl->left.y = cl->bottom.y = yStart;
						}
					}else{
						double k = 0;
						//求斜率
						if (abs(yStart - yEnd) < 1E-2)
						{
							k = 0;
						}else{
							k = (yStart - yEnd)/(xStart - xEnd);
						}
						//double k = (yStart - yEnd)/(xStart - xEnd);
						//在有斜率的地方
						double arg = atan(k);

						if (xStart < xEnd)
						{
							//cl->minReaderId = start_reader_id;
							//cl->maxReaderId = end_reader_id;
							/*cl->top.x = cl->left.x = xStart + i*width*cos(arg);
							cl->right.x = cl->bottom.x = xEnd;
							cl->top.y = yStart + width/2 - i*width*sin(arg);
							cl->right.y = yStart + width/2-(i+1)*width*sin(arg);
							cl->left.y = yStart - width/2 - i*width*sin(arg);
							cl->bottom.y = yStart - width/2 - (i+1)*width*sin(arg);*/
							cl->top.x = cl->left.x = xStart + i*width*cos(arg);
							cl->right.x = cl->bottom.x = xStart + (i+1)*width*cos(arg);

							cl->top.y = yStart + width/2 + i*width*sin(arg);
							cl->right.y = yStart + width/2 + (i+1)*width*sin(arg);
							cl->left.y = yStart - width/2 + i*width*sin(arg);
							cl->bottom.y = yStart - width/2 + (i+1)*width*sin(arg);
						}else{
							//cl->minReaderId = end_reader_id;
							//cl->maxReaderId = start_reader_id;
							/*cl->top.x = cl->left.x = xEnd + i*width*cos(arg);
							cl->right.x = cl->bottom.x = xStart;
							cl->top.y = yEnd + width/2 - i*width*sin(arg);
							cl->right.y = yEnd + width/2-(i+1)*width*sin(arg);
							cl->left.y = yEnd - width/2 - i*width*sin(arg);
							cl->bottom.y = yEnd - width/2 - (i+1)*width*sin(arg);*/
							cl->top.x = cl->left.x = xEnd + i*width*cos(arg);
							cl->right.x = cl->bottom.x = xEnd + (i+1)*width*cos(arg);

							cl->top.y = yEnd + width/2 + i*width*sin(arg);
							cl->right.y = yEnd + width/2 + (i+1)*width*sin(arg);
							cl->left.y = yEnd - width/2 + i*width*sin(arg);
							cl->bottom.y = yEnd - width/2 + (i+1)*width*sin(arg);
						}
					} 
				} 
				else
				{
					//如果不是最后一格
					if (abs(xStart - xEnd) < 1E-2)
					{
						//如果在Y轴上
						if (yStart < yEnd)
						{
							cl->left.x = cl->top.x = (xStart - width/2);
							cl->right.x = cl->bottom.x = (xStart + width/2);
							cl->right.y = cl->top.y = (yStart + i*width);
							cl->left.y = cl->bottom.y = (yStart + (i+1)*width);
						}else{
							cl->left.x = cl->top.x = (xEnd - width/2);
							cl->right.x = cl->bottom.x = (xEnd + width/2);
							cl->right.y = cl->top.y = (yEnd + i*width);
							cl->left.y = cl->bottom.y = (yEnd + (i+1)*width);
						}
					} 
					else
					{
						double k = 0;
						//求斜率
						if (abs(yStart - yEnd) < 1E-2)
						{
							k = 0;
						}else{
							k = (yStart - yEnd)/(xStart - xEnd);
						}
						//double k = (yStart - yEnd)/(xStart - xEnd);
						//在有斜率的地方
						double arg = atan(k);
						double ca = cos(arg);
						double sa = sin(arg);

						if (xStart < xEnd)
						{
							cl->top.x = cl->left.x = xStart + i*width*cos(arg);
							cl->right.x = cl->bottom.x = xStart + (i+1)*width*cos(arg);
							cl->top.y = yStart + width/2 + i*width*sin(arg);
							cl->right.y = yStart + width/2 + (i+1)*width*sin(arg);
							cl->left.y = yStart - width/2 + i*width*sin(arg);
							cl->bottom.y = yStart - width/2 + (i+1)*width*sin(arg);
						}else{
							cl->top.x = cl->left.x = xEnd + i*width*cos(arg);
							cl->right.x = cl->bottom.x = xEnd + (i+1)*width*cos(arg);
							cl->top.y = yEnd + width/2 + i*width*sin(arg);
							cl->right.y = yEnd + width/2 + (i+1)*width*sin(arg);
							cl->left.y = yEnd - width/2 + i*width*sin(arg);
							cl->bottom.y = yEnd - width/2 + (i+1)*width*sin(arg);
						}
					}
				}	
				ltCell.push_back(cl);
			}
			mpCellPath->insert(std::make_pair(name1,ltCell));
		}
	}

	if (mpCellPath->size() == 0)
	{
		return 1;
	}

	return 0; 
}

/*
 * 对格子进行分支初始化设置
*/
int CYAServerDlg::InitCellBranch()
{
	for (CellPathMap::iterator it = mpCellPath->begin();it != mpCellPath->end();++it)
	{
		std::string readerName = it->first;
		std::vector<std::string> vtReaders = CFunctions::split(readerName,"-",true);
		int nFirstReader = atoi(vtReaders[0].c_str());
		int nSecondReader = atoi(vtReaders[1].c_str());
		bool bFirstHasBranch = false;
		bool bSecondHasBranch = false;
		point firstReader,secondReader;

		//从地图路径集判定，哪个分站有分支
		for (TDOAReaderPathMap::iterator it_reader = mp_reader_path_list_tdoa->begin();it_reader != mp_reader_path_list_tdoa->end();++it_reader)
		{
			if (it_reader->first == nFirstReader)
			{
				if (it_reader->second->size() > 2)
				{
					bFirstHasBranch = true;
					firstReader.x = it_reader->second->find(nSecondReader)->second->x[0];
					firstReader.y = it_reader->second->find(nSecondReader)->second->y[0];
					secondReader.x = it_reader->second->find(nSecondReader)->second->x[1];
					secondReader.y = it_reader->second->find(nSecondReader)->second->y[1];
				}
			} 
			else if(it_reader->first == nSecondReader )
			{
				if (it_reader->second->size() > 2)
				{
					bSecondHasBranch = true;
					firstReader.x = it_reader->second->find(nFirstReader)->second->x[1];
					firstReader.y = it_reader->second->find(nFirstReader)->second->y[1];
					secondReader.x = it_reader->second->find(nFirstReader)->second->x[0];
					secondReader.y = it_reader->second->find(nFirstReader)->second->y[0];				
				}
			}		
		}

		int nCounts = BRANCH_RANGE / CELL_WIDTH;

		for (int i = 0;i < nCounts;i++)
		{
			if (bFirstHasBranch)
			{
				//是否从最小的开始
				bool bStartMin = false;
				if (abs(firstReader.x - secondReader.x) < 1E-2)
				{
					if (firstReader.y < secondReader.y)
					{
						bStartMin = true;
					}
				}
				for (std::list<std::shared_ptr<Cell>>::iterator it_cell = it->second.begin();it_cell != it->second.end();++it_cell)
				{
					//分支属性
					if ((*it_cell)->id == i+1 && bStartMin)
					{
						(*it_cell)->isHasBranch = true;
					}

					if ((*it_cell)->id == it->second.size()-i && !bStartMin)
					{
						(*it_cell)->isHasBranch = true;
					}
				}
			}

			if (bSecondHasBranch)
			{
				//是否从最小的开始
				bool bStartMax = false;
				if (abs(firstReader.x - secondReader.x) < 1E-2)
				{
					if (firstReader.y > secondReader.y)
					{
						bStartMax = true;
					}
				}
				for (std::list<std::shared_ptr<Cell>>::iterator it_cell = it->second.begin();it_cell != it->second.end();++it_cell)
				{
					//分支属性
					if ((*it_cell)->id == it->second.size()-i && bStartMax)
					{
						(*it_cell)->isHasBranch = true;
					}

					if ((*it_cell)->id == i+1 && !bStartMax)
					{
						(*it_cell)->isHasBranch = true;
					}
				}
			}
		}	
	}

	return 0;
}

/*
 * 作用：执行sql语句
 *
 * param
 *		sql		sql语句
 *
 * return
 *		执行成功返回0，失败返回1
 *
*/
int CYAServerDlg::ExecuteSql(std::string sql)
{
	//从数据库中读取
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);
	if(pConn == NULL){
		return 1;
	}
	MYSQL_RES *pRes = NULL;
	int err = 0;
	
	pRes = pConn->Execute(sql.c_str(), err);

	if (err > 0)
	{
		return 1;
	}

	return 0;
}

LRESULT CYAServerDlg::UpdateCardMessage(WPARAM wParam,LPARAM lParam)
{
	Card* pCard = (Card*)wParam;
	Cell* pCell = (Cell*)lParam;

	char sql[LENGTH_SQL] = {0};
	char chTime[30] = {0};
	char chIntervalTime[30] = {0};
	sprintf_s(chTime,
		30,
		"%u-%u-%u %u:%u:%u.%u",
		pCell->deal_time.wYear,
		pCell->deal_time.wMonth,
		pCell->deal_time.wDay,
		pCell->deal_time.wHour,
		pCell->deal_time.wMinute,
		pCell->deal_time.wSecond,
		pCell->deal_time.wMilliseconds);

	sprintf_s(chIntervalTime,
		30,
		"%u-%u-%u %u:%u:%u.%u",
		pCell->interval_time.wYear,
		pCell->interval_time.wMonth,
		pCell->interval_time.wDay,
		pCell->interval_time.wHour,
		pCell->interval_time.wMinute,
		pCell->interval_time.wSecond,
		pCell->interval_time.wMilliseconds);

	pCard->map_id = 5;
	pCard->area_id = 1;

	sprintf_s(sql,
		"insert ignore into his_cell_location(card_id,cur_time,interval_time,origin_reader_name,origin_cell_id,real_reader_name,real_cell_id,card_stamp_time,isFit,speed,mileage,map_id,area_id) values('%s','%s','%s','%s',%d,'%s',%d,%d,%d,%.4f,%.4f,%d,%d);",
		pCard->card_id.c_str(),
		chTime,
		chIntervalTime,
		pCard->originCellReaderName.c_str(),
		pCard->originCellId,
		pCard->curCellReaderName.c_str(),
		pCard->curCellId,
		pCard->time_stamp_last,
		pCard->is_fit_pos,
		pCard->get_speed(),
		pCard->mileage,
		pCard->map_id,
		pCard->area_id);

	std::string strSql = "";
	strSql = sql;
	//ExecuteSql(sql);
	execute_sql(sql);
	
	CardMap::iterator it_card = mp_card_list_all.end();
	for (it_card = mp_card_list_all.begin();it_card != mp_card_list_all.end();++it_card)
	{
		if (it_card->second->card_id == pCard->card_id)
		{
			break;
		}
	}

	if (it_card != mp_card_list_all.end())
	{
		std::string strJson = "";
		strJson = get_json_position(it_card->second);
		send_json_data(JSON_CMD_VALUE_PUSH,strJson);
	}
	
	return 0;
}

int CYAServerDlg::init_cell_path_map()
{
	mpCellPath = nullptr;

	mpCellPath = std::make_shared<CellPathMap>();

	if (mpCellPath == nullptr)
	{
		return 1;
	}

	DivideCell(0.3,mp_reader_path_list_tdoa);
	InitCellBranch();

	if (mpCellPath->size() > 0)
	{
		int i = 0;
		for (CardMap::iterator it = mp_card_list_all.begin();it != mp_card_list_all.end();++it)
		{
			if (!it->second->bInitalCellPath)
			{
				it->second->SetCellPathMap(mpCellPath);
			}	
		}
	}

	//if (mpCellPath->size() > 0)
	//{
	//	//先清除数据库中的所有数据
	//	CMysqlConn* pConn = NULL;
	//	CDBConnGuard pDbGuard(pConn);
	//	if(pConn == NULL){
	//		return 1;
	//	}
	//	MYSQL_ROW pRow;
	//	MYSQL_RES *pRes = NULL;
	//	int err = 0;
	//	char strsql[LENGTH_SQL] = {0};	
	//	
	//	sprintf_s(strsql,"delete from dat_cell;");

	//	pRes = pConn->Execute(strsql, err);

	//	if (err > 0)
	//	{
	//		return 1;
	//	}

	//	int nCounts = 0;

	//	for (std::map<std::string,std::list<std::shared_ptr<Cell>>>::iterator it = mpCellPath->begin();it != mpCellPath->end();++it)
	//	{
	//		std::string reader_name = "";
	//		std::string strSql = "";

	//		reader_name = it->first;
	//		
	//		for (std::list<std::shared_ptr<Cell>>::iterator it_cell = it->second.begin();it_cell != it->second.end();++it_cell)
	//		{
	//			int nCellId = 0;
	//			double x = 0.0,y = 0.0;

	//			x = ((*it_cell)->top.x + (*it_cell)->bottom.x)/2;
	//			y = ((*it_cell)->top.y + (*it_cell)->bottom.y)/2;

	//			nCellId = (*it_cell)->id;

	//			std::string strTop = "",strLeft = "", strBottom = "",strRight = "";

	//			char ch[50] = {0};
	//			sprintf_s(ch,"%.4f,%.4f",(*it_cell)->top.x,(*it_cell)->top.y);
	//			strTop = ch;
	//			memset(ch,50,0);
	//			sprintf_s(ch,"%.4f,%.4f",(*it_cell)->left.x,(*it_cell)->left.y);
	//			strLeft = ch;
	//			memset(ch,50,0);
	//			sprintf_s(ch,"%.4f,%.4f",(*it_cell)->bottom.x,(*it_cell)->bottom.y);
	//			strBottom = ch;
	//			memset(ch,50,0);
	//			sprintf_s(ch,"%.4f,%.4f",(*it_cell)->right.x,(*it_cell)->right.y);
	//			strRight = ch;

	//			int nBranch = 0;
	//			nBranch = (*it_cell)->isChangePath?1:0;

	//			//执行写库操作
	//			char sql[LENGTH_SQL] = {0};
	//			sprintf_s(sql,
	//				"insert ignore into dat_cell (reader_name,cell_id,x,y,cell_top,cell_left,cell_bottom,cell_right,isHasBranch) values('%s',%d,%.4f,%.4f,'%s','%s','%s','%s',%d);",
	//				reader_name.c_str(),
	//				nCellId,
	//				x,
	//				y,
	//				strTop.c_str(),
	//				strLeft.c_str(),
	//				strBottom.c_str(),
	//				strRight.c_str(),
	//				nBranch
	//				);
	//			//pConn->Execute(sql, err);
	//			std::string tmpSql = sql;
	//			strSql += tmpSql;
	//			nCounts++;
	//			if (nCounts>=10)
	//			{
	//				pConn->MultiExecute(strSql.c_str(),err);
	//				nCounts = 0;
	//			}
	//		}
	//		if (nCounts > 0)
	//		{
	//			pConn->MultiExecute(strSql.c_str(),err);
	//		}
	//	}
	//}
	
	return 0;
}

double CYAServerDlg::GetDistance(_point p1, _point p2)
{
	double distance = 0.0;
	distance = sqrt(pow(p1.x - p2.x, 2) 
		+ pow(p1.y - p2.y, 2));
	return distance;
}

int CYAServerDlg::GetLandmarkID(_point card_point)
{
	int minLandmarkID = -1;
	double minDistance = 100000;
	std::shared_ptr<LandmarkInfo> pLandmarkInfo = nullptr;
	int nRow = 0;
	LandmarkInfoMap::iterator it = mp_landmark_list.begin();		
	while(it != mp_landmark_list.end())
	{
		pLandmarkInfo = it->second;
		_point landmark_position (pLandmarkInfo->x, 
			pLandmarkInfo->y, 
			pLandmarkInfo->z);
		_point card_position (card_point.x, 
			card_point.y, 
			card_point.z);
		double distance = 0.0;
		distance = GetDistance(landmark_position, card_position);
		if(distance < minDistance)
		{
			minDistance = distance;
			minLandmarkID = pLandmarkInfo->landmark_id;
		}
		it++;
	}
	return minLandmarkID;
}

DIRECTION_TYPE CYAServerDlg::GetDirectionType(_point card_point, _point landmark_point, int map_id)
{
	DIRECTION_TYPE direction = NODIRECTORY;
	int x_offset = 0;
	int y_offset = 0;
	int angle = 0; // x,y坐标系与地理北极的角度
	x_offset = card_point.x - landmark_point.x;
	y_offset = card_point.y - landmark_point.y;


	if(abs(x_offset) < 1)
	{
		x_offset = 0;
	}
	if(abs(y_offset) < 1)
	{
		y_offset = 0;
	}

	std::shared_ptr<MapDirectionInfo> pMapDirectoryInfo = nullptr;
	MapDirectionInfoMap::iterator it = mp_map_direction_list.find(map_id);		
	if(it == mp_map_direction_list.end())
	{
		return NODIRECTORY;
	}
	else
	{ 
		pMapDirectoryInfo = it->second;
	}

	//get direction
	if(0 == y_offset)
	{
		if(x_offset > 0)
		{
			angle = pMapDirectoryInfo->north_angle + 0;
		}
		if(x_offset < 0)
		{
			angle = pMapDirectoryInfo->north_angle - 180;
		}
	}
	else if(0 == x_offset)
	{
		if(y_offset < 0)
		{
			angle = pMapDirectoryInfo->north_angle - 90;
		}
		if(y_offset > 0)
		{
			angle = pMapDirectoryInfo->north_angle + 90;
		}
	}
	else if(abs(x_offset) >= abs(y_offset))
	{
		if(x_offset > 0)
		{
			angle = pMapDirectoryInfo->north_angle + 0;
		}
		if(x_offset < 0)
		{
			angle = pMapDirectoryInfo->north_angle - 180;
		}
	}
	else
	{
		if(y_offset < 0)
		{
			angle = pMapDirectoryInfo->north_angle - 90;
		}
		if(y_offset > 0)
		{
			angle = pMapDirectoryInfo->north_angle + 90;
		}
	}

	direction = (DIRECTION_TYPE)((angle % 360) / 90);
	if(angle % 360 == 0)
	{
		direction = NORTH;
	}
	if((0 == y_offset) && (0 == x_offset))
	{
		direction = NODIRECTORY;
	}

	return direction;
}

void CYAServerDlg::TestLandmarkRequirement()
{
	_point card_point;
	_point landmark_point;
	int directory_id = 0;
	int landmark_id = 0;
	LandmarkInfoMap::iterator itLandmark = mp_landmark_list.begin();

	//test 1
	card_point.x = 4727;
	card_point.y = 90;
	card_point.z = 0;
	landmark_id = GetLandmarkID(card_point);
	itLandmark = mp_landmark_list.find(landmark_id);		
	if(itLandmark != mp_landmark_list.end())
	{
		landmark_point.x = itLandmark->second->x;
		landmark_point.y = itLandmark->second->y;
		landmark_point.z = itLandmark->second->z;
	}
	directory_id = GetDirectionType(card_point, landmark_point, 5);

	//test 2
	card_point.x = 4727;
	card_point.y = 70;
	card_point.z = 0;
	landmark_id = GetLandmarkID(card_point);
	itLandmark = mp_landmark_list.find(landmark_id);		
	if(itLandmark != mp_landmark_list.end())
	{
		landmark_point.x = itLandmark->second->x;
		landmark_point.y = itLandmark->second->y;
		landmark_point.z = itLandmark->second->z;
	}
	directory_id = GetDirectionType(card_point, landmark_point, 5);

	//test 3
	card_point.x = 4727;
	card_point.y = 80;
	card_point.z = 0;
	landmark_id = GetLandmarkID(card_point);
	itLandmark = mp_landmark_list.find(landmark_id);		
	if(itLandmark != mp_landmark_list.end())
	{
		landmark_point.x = itLandmark->second->x;
		landmark_point.y = itLandmark->second->y;
		landmark_point.z = itLandmark->second->z;
	}
	directory_id = GetDirectionType(card_point, landmark_point, 5);

	//test 4
	card_point.x = 4727;
	card_point.y = 82.5;
	card_point.z = 0;
	landmark_id = GetLandmarkID(card_point);
	itLandmark = mp_landmark_list.find(landmark_id);		
	if(itLandmark != mp_landmark_list.end())
	{
		landmark_point.x = itLandmark->second->x;
		landmark_point.y = itLandmark->second->y;
		landmark_point.z = itLandmark->second->z;
	}
	directory_id = GetDirectionType(card_point, landmark_point, 5);

	//test 5
	card_point.x = 3200;
	card_point.y = 75;
	card_point.z = 0;
	landmark_id = GetLandmarkID(card_point);
	itLandmark = mp_landmark_list.find(landmark_id);
	if(itLandmark != mp_landmark_list.end())
	{
		landmark_point.x = itLandmark->second->x;
		landmark_point.y = itLandmark->second->y;
		landmark_point.z = itLandmark->second->z;
	}
	directory_id = GetDirectionType(card_point, landmark_point, 5);

	//test 6
	card_point.x = 3400;
	card_point.y = 75;
	card_point.z = 0;
	landmark_id = GetLandmarkID(card_point);
	itLandmark = mp_landmark_list.find(landmark_id);		
	if(itLandmark != mp_landmark_list.end())
	{
		landmark_point.x = itLandmark->second->x;
		landmark_point.y = itLandmark->second->y;
		landmark_point.z = itLandmark->second->z;
	}
	directory_id = GetDirectionType(card_point, landmark_point, 5);

	//test 7
	card_point.x = 5200;
	card_point.y = 250;
	card_point.z = 0;
	landmark_id = GetLandmarkID(card_point);
	itLandmark = mp_landmark_list.find(landmark_id);		
	if(itLandmark != mp_landmark_list.end())
	{
		landmark_point.x = itLandmark->second->x;
		landmark_point.y = itLandmark->second->y;
		landmark_point.z = itLandmark->second->z;
	}
	directory_id = GetDirectionType(card_point, landmark_point, 5);

	//test 8
	card_point.x = 5400;
	card_point.y = 300;
	card_point.z = 0;
	landmark_id = GetLandmarkID(card_point);
	itLandmark = mp_landmark_list.find(landmark_id);		
	if(itLandmark != mp_landmark_list.end())
	{
		landmark_point.x = itLandmark->second->x;
		landmark_point.y = itLandmark->second->y;
		landmark_point.z = itLandmark->second->z;
	}
	directory_id = GetDirectionType(card_point, landmark_point, 5);

	return;
}

void CYAServerDlg::save_raw_data_card_tof( std::shared_ptr<Card> card )
{
	char sql[LENGTH_SQL] = {0};
	char _time[STR_LEN_TIME];
	struct tm local_time;
	time_t t = time(NULL);

	bool b_exec = false;

	sprintf_s(sql, LENGTH_SQL, 
		"INSERT INTO his_raw_data_card_tof(card_id, ct, ft, power_state, acc_state, reader_id, antenna_id, distance) VALUES(%s, %d, %I64u, %d, %d, %d, %d, %.3f);",  
		card->card_id.c_str(), card->time_stamp, card->flying_time, card->power_state, card->accelerate_state, card->reader_id, card->antenna_id, card->distance);
	try
	{
		execute_sql(sql);
	}
	catch (...)
	{

	}
}

int CYAServerDlg::init_shift()
{
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn);

	if(pConn == NULL){
		return 1;
	}

	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	pRes = pConn->Execute("select shift_id, start_time, end_time from dat_shift where shift_type_id = 1;", err);
	
	if(err)
	{
		return 2;
	}

	std::shared_ptr<BanShift> banshift = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))	{
		BanShiftMap::iterator it = mp_banshift_list.find(atoi(pRow[0]));		
		if(it != mp_banshift_list.end()){
			banshift = it->second;
		}else{
			banshift = std::make_shared<BanShift>(atoi(pRow[0]), pRow[1], pRow[2]);
			mp_banshift_list.insert(make_pair(banshift->shift_id, banshift));
			nRow++;
		}
		banshift->start_time = pRow[1];
		banshift->end_time = pRow[2];
	}
	mysql_free_result(pRes);
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_INIT_BANSHIFT), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	return 0;
}
