// YAServerDlg.cpp : 实现文件
#include <stdio.h>
#include <windows.h>
#include <cstdio>
#include <process.h>
#include <exception> 
#include <algorithm>
#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 "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"

#include "../thirdparty/include/rapidjson/include/rapidjson/rapidjson.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;
const int ms = 1000;
int g_anchorNum  = 0;

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

const std::string testJson = "{\"cmd\":\"pos_map\",\"data\":{\"s\":{\"detail\":[\
							 [\"0010000000002\",3231.210,75.0,1499515328000.0,1499515328000.0,1499515472000.0,147000.0,5,2,2,0,1,0,0.0,6,4,1243.0,4], \
							 [\"0010000000044\",4917.260,147.620,1499514950000.0,1499515018000.0,1499515475000.0,525000.0,5,4,2,0,1,0,0.0,8,4,63.0,4], \
							 [\"0010000000079\",4727.0,-71.51000000000001,1499514756000.0,1499514892000.0,1499514892000.0,719000.0,5,1,2,0,1,0,0.0,9,1,75.0,4]],\
							 \"stat\":{\"dept\":{\"2\":{\"area\":[[2,2],[1,2],[5,1],[3,1],[4,1]],\"dept\":[[2,7]],\"occupation_level\":[[4,7]],\"sum\":7}},\
							 \"glbl\":{\"area\":[[2,2],[1,2],[5,1],[3,1],[4,1]],\"dept\":[[2,7]],\"occupation_level\":[[4,7]],\"sum\":7}}},\"v\":\
							 {\"detail\":[[\"0020000001001\",4747.660,-75.410,1499514870000.0,1499514870000.0,1499515082000.0,605000.0,5,5,2,0,0,0,0.0,10,3,71.0,0]],\
							 \"stat\":{\"dept\":{\"2\":{\"area\":[[5,25],[7,2],[6,4],[28,1],[3,2],[9,4],[22,1],[26,3],[2,3],[4,1]],\"dept\":[[2,46]],\"sum\":46}},\
							 \"glbl\":{\"area\":[[5,25],[7,2],[6,4],[28,1],[3,2],[9,4],[22,1],[26,3],[2,3],[4,1]],\"dept\":[[2,46]],\"sum\":46}}}},\"version\":\"1.0.0.4\"}";

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

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

bool g_is_rec_hist = 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())
	, _io_ex(new client())
	, m_reader_id_hist(0)
{
	ws_init();
	ws_init_ex();
	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::OnBnTest)
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;
}

DWORD time_send_json_device_state;
DWORD time_send_json_alarm;
DWORD time_send_json_postion;
DWORD time_send_call;
DWORD time_send_help;
DWORD time_send_leader;
DWORD time_load_leader;
DWORD time_ws_connect;
DWORD time_ws_connect_ex;
DWORD time_send_heart;
DWORD time_driving_face_check_interval;
DWORD time_driving_face_check_interval_alarm; //lemon
bool g_exit=false;
volatile LONG g_QueueItemCount = 0;

CMysqlConnPool* g_pConnPool = NULL;
CMysqlConnPool* g_pConnPool_Bk = NULL;
bool g_StoreMultDatabase = false;

DWORD WINAPI _exec_sql(const char * lparam)
{
	if (g_pConnPool->m_needConnect)
	{
		debug_print_syslog(0, "_EXEC_SQL_ERROR_FOR_LOST_SERVER:%s",lparam);
		return 1;
	}
	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;
	}

	debug_print_syslog(0, "[lemon]_exec_sql [%s]",lparam);

	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn, g_pConnPool);

	//MYSQL_RES *pRes = NULL;
	//pRes = getMysqlRes(strsql);

	if(pConn == NULL)
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_86);
		::InterlockedDecrement(&g_QueueItemCount);
		return 1;
	}
	int err = 0;

	pConn->MultiExecute(lparam, err);
	switch (err)
	{
	case CR_COMMANDS_OUT_OF_SYNC:
		break;
	case CR_SERVER_GONE_ERROR:
	case CR_SERVER_LOST:
		{	
			pDbGuard.isVaild();
		}
		break;
	case CR_UNKNOWN_ERROR:

	default:
		break;
	}
	if(err > 0){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_87);
		debug_print_syslog(0, "sql error: [%d] , %s", err,lparam);
	}
	if(g_StoreMultDatabase){
		CMysqlConn* pConnBk = NULL;
		CDBConnGuard pDbGuardBk(pConnBk, g_pConnPool_Bk);
		if(pConnBk == NULL)
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_267);
			::InterlockedDecrement(&g_QueueItemCount);
			return 1;
		}
		err = 0;

		pConnBk->MultiExecute(lparam, err);
		switch (err)
		{
		case CR_COMMANDS_OUT_OF_SYNC:
			break;
		case CR_SERVER_GONE_ERROR:
		case CR_SERVER_LOST:
			{			
				pDbGuardBk.isVaild();
			}
			break;
		case CR_UNKNOWN_ERROR:

		default:
			break;
		}
		if(err > 0){
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_268);
			debug_print_syslog(0, "sql_bk error: [%d]%s", err,lparam);

		}
	}
	::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);
	::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();
		if(cur_time - time_send_json_alarm > theApp.send_json_alarm){
			time_send_json_alarm = cur_time; 
			//处理区域超员告警
			dlg->deal_areas();
			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.time_send_call){
			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->clear_call_info();
			dlg->send_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();
		}

		if(!dlg->is_websocket_login_ex && cur_time - time_ws_connect_ex > theApp.ws_connect_interval){
			time_ws_connect_ex = cur_time;
			if(!dlg->is_websocket_ok_ex){
				dlg->ws_open_ex();
			}
			dlg->ws_login_ex();
		}
		//当掘进机有数据的时候再来进行操作。
		// update driving face status
		if(cur_time - time_driving_face_check_interval > theApp.send_json_drivingface){
			time_driving_face_check_interval = cur_time;	
			//check driving face shift state
			dlg->driving_face_shift_start();
			dlg->send_drivingface_card_position_json();
		}
		//drivingfaceWarningPoint alarm
		if (cur_time-time_driving_face_check_interval_alarm>theApp.warning_point_alarm)
		{
			time_driving_face_check_interval_alarm = cur_time;
			dlg->deal_drivingface_alarm_all();
		}
		
    
		if(cur_time - time_send_leader > theApp.send_json_leader)
		{
			time_send_leader = cur_time;
			dlg->send_json_data(JSON_CMD_VALUE_PUSH, dlg->get_json_leader_arrange());
		}

		if(cur_time - time_load_leader > theApp.load_leader)
		{
			time_load_leader = cur_time;
			dlg->init_leader_arrange();
		}
		//if (cur_time - time_send_heart > theApp.heart_interval)
		//{
		//	time_send_heart = cur_time;
		//	//dlg->send_heart_package();
		//}
		//WaitForMS(10);
		Sleep(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));
		}
		WaitForS(10);
	}
	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_device_state=time_send_json_alarm=time_send_json_postion= ::GetTickCount();
	time_send_call=time_send_help=time_driving_face_check_interval= ::GetTickCount();
	time_load_leader = time_send_leader = ::GetTickCount();

	m_thread_timer = ::AfxBeginThread(_thread_timer, this, THREAD_PRIORITY_HIGHEST);

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

	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()
{
	if(!is_websocket_login){
		ws_login();
	}

	if(!is_websocket_login_ex){
		ws_login_ex();
	}
	start_tcp_server();
}

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

	if(is_websocket_login_ex){
		ws_logout_ex();
	}
}

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_tof = 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_card_list_over_count_vehicle = std::make_shared<CardMap>();

	mp_card_warning_point_alarm = std::make_shared<CardMap>();//lemon
	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>();
	mp_ins_cal_data_list = std::shared_ptr<CalDataMap>();

	return 0;
}

/*
* 初始化对话框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);

	sls_setting.over_count_person = 1000;
	sls_setting.over_count_vehicle = 100;
	sls_setting.over_speed = 30;
	sls_setting.over_time_person = 36000;
	sls_setting.over_time_vehicle = 18000;
	sls_setting.att_endtime_offset_staff = 600;
	sls_setting.att_endtime_offset_vehicle = 600;
	sls_setting.att_starttime_offset_staff = 900;
	sls_setting.att_starttime_offset_vehicle = 600;

	g_pConnPool = new CMysqlConnPool();
	g_pConnPool_Bk = new CMysqlConnPool();

	m_time_last_rec = time(NULL);

	m_nPort = PORT_SERVER_MASTER;
	m_nCountClick = 0;
	m_ws_url = TEST_WS_URL;
	m_ws_url_ex = 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();
	}
	if(is_websocket_login_ex){
		ws_logout_ex();
	}
	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);
		WaitForS(3);
	}

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

	clear_all_list();

	g_pConnPool->CloseAllConn();
	g_pConnPool_Bk->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_rules(int id)
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	if(id == 0){
		sprintf_s(strsql, "SELECT rules_id ,STATUS FROM dat_rules;");
	}else{
		sprintf_s(strsql, "SELECT rules_id ,STATUS FROM dat_rules WHERE rules_id = %d; ", id);
	}
	pRes = getMysqlRes(strsql);

	if (NULL == pRes)
	{
		return 1;
	}
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		RulesMap::iterator it = m_rules_list.find(atoi(pRow[0]));
		if(it != m_rules_list.end()){
			it->second = atoi(pRow[1]);
		}else{
			m_rules_list.insert(make_pair(atoi(pRow[0]),atoi(pRow[1])));
			nRow++;
		}
	}
	mysql_free_result(pRes);

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

	return 0;
}

int CYAServerDlg::init_staffer(string staff_id /* = "" */, bool is_card /*= false*/ )
{
	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.dept_id, s.group_id, s.occupation_id, \
					   ol.occupation_level_id,s.worktype_id,s.need_display \
					   FROM dat_staff_extend s \
					   LEFT JOIN dat_card c ON s.card_id = c.card_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 c.state_id = 0;");
	}else if(is_card){
		sprintf_s(buf, "SELECT staff_id, s.card_id, c.card_type_id, s.dept_id, s.group_id, s.occupation_id, \
					   ol.occupation_level_id,s.worktype_id,s.need_display \
					   FROM dat_staff_extend s \
					   LEFT JOIN dat_card c ON s.card_id = c.card_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 c.state_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.dept_id, s.group_id, s.occupation_id, \
					   ol.occupation_level_id,s.worktype_id,s.need_display \
					   FROM dat_staff_extend s \
					   LEFT JOIN dat_card c ON s.card_id = c.card_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 c.state_id = 0 AND staff_id = '%s';", staff_id.c_str());
	}

	pRes = getMysqlRes(buf);
	if (NULL == pRes)
	{
		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;
			nRow++;
		}else{
			pCard = std::make_shared<Card>(pRow[1], atoi(pRow[2]), theApp.z_offset);
			pCard->is_registered = false;			
			pCard->set_reader_path(mp_reader_path_list_tof, mp_reader_path_list_tdoa);
		}
		pCard->id = atoi(pRow[0]);
		pCard->dept_id = atoi(pRow[3]);
		pCard->group_id = atoi(pRow[4]);
		pCard->occ_id = atoi(pRow[5]);
		pCard->level_id = (pRow[6] == NULL) ? 0 : atoi(pRow[6]);
		pCard->worktype_id = atoi(pRow[7]);//lemon 2017/07/31
		pCard->need_display = atoi(pRow[8]);//lmeon 2017/08/01

		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*/)
{
	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	if(vehicle_id.length() == 0){
		sprintf_s(buf, "SELECT ve.vehicle_id, ve.card_id, c.card_type_id, \
					   ve.dept_id, ve.group_id, v.vehicle_type_id, vt.vehicle_level_id, \
					   vt.is_railroad as vt_is_railroad,ve.need_display \
					   FROM dat_vehicle_extend ve \
					   LEFT JOIN dat_vehicle v ON ve.vehicle_id = v.vehicle_id \
					   LEFT JOIN dat_card c ON ve.card_id = c.card_id \
					   LEFT JOIN dat_dept d ON ve.dept_id = d.dept_id \
					   LEFT JOIN dat_group g ON ve.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 c.state_id = 0;");
	}else if(is_card){
		sprintf_s(buf, "SELECT ve.vehicle_id, ve.card_id, c.card_type_id, \
					   ve.dept_id, ve.group_id, v.vehicle_type_id, vt.vehicle_level_id, \
					   vt.is_railroad as vt_is_railroad,ve.need_display \
					   FROM dat_vehicle_extend ve \
					   LEFT JOIN dat_vehicle v ON ve.vehicle_id = v.vehicle_id \
					   LEFT JOIN dat_card c ON ve.card_id = c.card_id \
					   LEFT JOIN dat_dept d ON ve.dept_id = d.dept_id \
					   LEFT JOIN dat_group g ON ve.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 c.state_id = 0 AND ve.card_id ='%s';", vehicle_id.c_str());
	}else{
		sprintf_s(buf, "SELECT ve.vehicle_id, ve.card_id, c.card_type_id, \
					   ve.dept_id, ve.group_id, v.vehicle_type_id, vt.vehicle_level_id, \
					   vt.is_railroad as vt_is_railroad,ve.need_display \
					   FROM dat_vehicle_extend ve \
					   LEFT JOIN dat_vehicle v ON ve.vehicle_id = v.vehicle_id \
					   LEFT JOIN dat_card c ON ve.card_id = c.card_id \
					   LEFT JOIN dat_dept d ON ve.dept_id = d.dept_id \
					   LEFT JOIN dat_group g ON ve.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 c.state_id = 0 AND ve.vehicle_id='%s';", vehicle_id.c_str());
	}
	
	pRes = getMysqlRes(buf);
	if (NULL == pRes)
	{
		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;
			nRow++;
		}else{
			pCard = std::make_shared<Card>(pRow[1], atoi(pRow[2]), theApp.z_offset);
			pCard->is_registered = false;
			pCard->set_reader_path(mp_reader_path_list_tof, mp_reader_path_list_tdoa);
		}
		pCard->id = atoi(pRow[0]);
		pCard->dept_id = atoi(pRow[3]);
		pCard->group_id = atoi(pRow[4]);
		pCard->vehice_type_id  = (pRow[5] == NULL) ? 0 : atoi(pRow[5]);
		pCard->level_id  = (pRow[6] == NULL) ? 0 : atoi(pRow[6]);
		pCard->m_nIsRailroad = (pRow[7] == NULL) ? 0 : atoi(pRow[7]);
		pCard->need_display = atoi(pRow[8]);//lemon 2017/08/01

		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*/)
{
	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 = getMysqlRes(buf);
	if (NULL == pRes)
	{
		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;
			nRow++;
		}else{
			pCard = std::make_shared<Card>(pRow[1], CT_ADHOC, theApp.z_offset);
			pCard->is_registered = false;
			//mp_card_list_all.insert(make_pair(pCard->card_id, pCard));
		}
		pCard->id = atoi(pRow[0]); // (pRow[0] == NULL) ? "" : pRow[0];
		pCard->card_id = (pRow[1] == NULL) ? "" : pRow[1];
		pCard->dept_id = (pRow[2] == NULL) ? 0:atoi(pRow[2]);
	}
	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*/)
{
	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 = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}

	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 */)
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	if(0 == area_id){
		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 = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}
	std::shared_ptr<Area> pArea = nullptr;

	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)
{
	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 = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		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_permission_card()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	sprintf_s(strsql, "SELECT worktype_id,worktype_des FROM dat_drivingface_worktype_permission;");
	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		WorkTypePermissionMap::iterator it = mp_worktype_permission_list.find(atoi(pRow[0]));		
		if(it == mp_worktype_permission_list.end())
		{
			mp_worktype_permission_list.insert(make_pair(atoi(pRow[0]),pRow[1]));
			nRow++;
		}
	}
	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_card()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	char strsql[LENGTH_SQL] = {0};	
	sprintf_s(strsql, "SELECT c.card_id, b.base_point_x, b.base_point_y, b.base_point_z, b.drivingface_id, \
					  a.area_id,a.warning_threshold ,a.over_count_num,b.map_id\
					  FROM dat_drivingface_vehicle a,dat_drivingface b,dat_vehicle_extend c \
					  WHERE	a.vehicle_id = c.vehicle_id AND a.drivingface_id = b.drivingface_id;");

	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		return 1;
	}
	std::shared_ptr<DrivingfaceCard> pDrivingfaceCard = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes)){
		DrivingfaceCardMap::iterator it = mp_driving_face_card_list.find(pRow[0]);		
		if(it != mp_driving_face_card_list.end()){
			pDrivingfaceCard = it->second;
		}else{
			pDrivingfaceCard = std::make_shared<DrivingfaceCard>();
			mp_driving_face_card_list.insert(make_pair(pRow[0], pDrivingfaceCard));
			nRow++;
		}

		pDrivingfaceCard->drivingface_id = atoi(pRow[4]);
		pDrivingfaceCard->card_id = pRow[0];
		pDrivingfaceCard->x = atof(pRow[1]);
		pDrivingfaceCard->y = atof(pRow[2]);
		pDrivingfaceCard->z = atof(pRow[3]);
		pDrivingfaceCard->area_id = atoi(pRow[5]);
		pDrivingfaceCard->warning_threshold = atof(pRow[6]);
		pDrivingfaceCard->m_overcount = atoi(pRow[7]);
		pDrivingfaceCard->m_mapId = atoi(pRow[8]);
		CardMap::iterator it_card = mp_card_list_all.find(pRow[0]);
		if (it_card != mp_card_list_all.end())
		{
			MapInfoMap::iterator it_map = mp_map_list.find(atoi(pRow[8]));
			if (it_map != mp_map_list.end())
			{
				it_card->second->map_scale = it_map->second->map_scale;
			}
		}

	}
	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::load_drivingface_card_curshift_position()
{
	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);
	std::string cur_shift_time = CFunctions::time_t2string(start_time_t);

	std::shared_ptr<DrivingfaceCard> pDrivingfaceCard = nullptr;
	DrivingfaceCardMap::iterator it_card = mp_driving_face_card_list.begin();
	for(;it_card != mp_driving_face_card_list.end();it_card++)
	{
		//current shift history is exist
		sprintf_s(strsql, " SELECT drivingface_id,start_x,start_y,start_z,end_x,end_y,end_z,total_length,finish_length FROM his_drivingface_shift_finish_length\
						  where card_id = '%s'  and cur_time = '%s';", 
						  (it_card->first).c_str(),
							cur_shift_time.c_str());
		debug_print_syslog(0, "init driving face by current shift data: %s", strsql);
		pRes = getMysqlRes(strsql);
		if (NULL == pRes)
		{
			return ;
		}
		
		while(pRow = mysql_fetch_row(pRes))
		{
			CardMap::iterator it = mp_card_list_all.find(it_card->first);
			if(it != mp_card_list_all.end())
			{
				it->second->is_drivingface_Initialization = true;
				it->second->shift_id = shift_id;
				it->second->driving_face_id = atoi(pRow[0]);
				it->second->driving_face_cur_shift_start_x = atof(pRow[1]);
				it->second->driving_face_cur_shift_start_y = atof(pRow[2]);
				it->second->driving_face_cur_shift_start_z = atof(pRow[3]);
				it->second->driving_face_cur_shift_x = atof(pRow[4]);
				it->second->driving_face_cur_shift_y = atof(pRow[5]);
				it->second->driving_face_cur_shift_z = atof(pRow[6]);
				it->second->x = atof(pRow[4]);
				it->second->y =	atof(pRow[5]);
				it->second->z = atof(pRow[6]);
				it->second->drving_face_cur_shift_max_speed = 0;
				it->second->m_cur_total_finish_length = atof(pRow[7]) + atof(pRow[8]);
				it->second->m_curshift_finish_length = atof(pRow[8]);
			}
			nRow++;
		}

		if(0 == nRow)
		{
			sprintf_s(strsql, " SELECT drivingface_id,start_x,start_y,start_z,end_x,end_y,end_z,total_length,finish_length FROM his_drivingface_shift_finish_length\
							  where card_id = '%s'  and cur_time < '%s' order by cur_time desc limit 1;", 
							  (it_card->first).c_str(),
							  cur_shift_time.c_str());
			debug_print_syslog(0, "init cur shift driving face by last log: %s", strsql);
			pRes = getMysqlRes(strsql);
			if (NULL == pRes)
			{
				return ;
			}
			int nRow = 0;
			while(pRow = mysql_fetch_row(pRes))
			{
				CardMap::iterator it = mp_card_list_all.find(it_card->first);
				if(it != mp_card_list_all.end())
				{
					it->second->is_drivingface_Initialization = true;
					it->second->driving_face_id = atoi(pRow[0]);
					it->second->driving_face_cur_shift_start_x = atof(pRow[4]);
					it->second->driving_face_cur_shift_start_y = atof(pRow[5]);
					it->second->driving_face_cur_shift_start_z = atof(pRow[6]);
					it->second->driving_face_cur_shift_x = atof(pRow[4]);
					it->second->driving_face_cur_shift_y = atof(pRow[5]);
					it->second->driving_face_cur_shift_z = atof(pRow[6]);
					it->second->x = atof(pRow[4]);
					it->second->y = atof(pRow[5]);
					it->second->z = atof(pRow[6]);
					it->second->drving_face_cur_shift_max_speed = 0;
					it->second->m_cur_total_finish_length = atof(pRow[7]) + atof(pRow[8]);
					it->second->m_curshift_finish_length = atof(pRow[8]);
				}
				debug_print_syslog(0, "init driving face start point error.");
				nRow++;
			}
		}
	}
	return;
}

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

	pRes = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		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->area_id = atoi(pRow[3]);
		pLandmarkInfo->x = atof(pRow[4]);
		pLandmarkInfo->y = atof(pRow[5]);
		pLandmarkInfo->z = atof(pRow[6]);
	}
	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)
{
	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 = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		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 */)
{
	// 从数据库中读取
	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 = getMysqlRes(strsql);
	if (NULL == pRes)
	{
		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);

	init_antenna(reader_id);
	init_all_readers_coverage(reader_id);

	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*/ )
{
	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 = getMysqlRes(strsql);

	if (NULL == pRes)
	{
		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;
}

/*
 * 初始化天线信息
 *
 * param
 *		reader_id		分站id
 *
 * return
 *		执行成功返回0，失败返回1
 *
*/
int CYAServerDlg::init_antenna(int reader_id /* = 0 */)
{
	char strsql[LENGTH_SQL] = {0};	
	if(reader_id == 0){
		sprintf_s(strsql, "SELECT antenna_id, a.reader_id, 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, 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);
	}
	
	MYSQL_RES *pRes = NULL;
	pRes = getMysqlRes(strsql);

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

	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<Reader> pReader = nullptr;
			pReader = it->second;

			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;		
			
			pReader->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*/ )
{
	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 = getMysqlRes(strsql);

	if (NULL == pRes)
	{
		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)
{
	init_tof_all_readers_coverage(reader_id);
	init_tdoa_all_readers_coverage(reader_id);
	return 0;
}

/*
 * 初始化TOF分站的覆盖范围的信息
 *
 * param
 *		reader_id		分站id
 *
 * return
 *		初始化成功返回0，否则返回非零值
 *
*/
int CYAServerDlg::init_tof_all_readers_coverage(int reader_id /*= 0*/)
{
	char sql[LENGTH_SQL] = {0};
	if(reader_id == 0){
		sprintf_s(sql, "select p.same_config_reader, p.reader_id,p.break_point_idx,p.x,p.y,p.z,p.is_bezier from dat_reader_path_tof p ,dat_reader r where p.reader_id = r.reader_id;");
	}else{
		sprintf_s(sql, "select p.same_config_reader,p.reader_id,p.break_point_idx,p.x,p.y,p.z,p.is_bezier from dat_reader_path_tof p ,dat_reader r where p.reader_id = %d; ", reader_id);
	}

	MYSQL_RES* pRes = NULL;
	
	pRes = getMysqlRes(sql);

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

	MYSQL_ROW pRow;
	int err = 0;
	int nRow = 0;

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

		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_TOF_READER_PATH), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	//根据获得地图集将其赋给mp_reader_path_list
	for(ReaderMap::iterator it = mp_reader_list.begin();it!=mp_reader_list.end();it++){
		if(it->second->bIsInitCoverage){
			int nReaderId = it->second->reader_id;
			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_tof->find(nReaderId);
			if(prpIt != mp_reader_path_list_tof->end()){
				pReaderPath = prpIt->second;
			}else{
				pReaderPath = std::make_shared<ReaderPath>();
				mp_reader_path_list_tof->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)
{
	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,rpc.ncount \
					   from dat_reader_path_tdoa p ,dat_reader r, \
					   (select count(*) as ncount, start_reader_id, end_reader_id from dat_reader_path_tdoa group by start_reader_id, end_reader_id) rpc\
					   where p.start_reader_id = r.reader_id \
					   and p.start_reader_id = rpc.start_reader_id and p.end_reader_id = rpc.end_reader_id \
					   order by p.start_reader_id, p.end_reader_id, p.idx;"); 
	}else{
		sprintf_s(sql, "select p.start_reader_id,p.end_reader_id,p.idx,p.x,p.y,p.z,p.is_bezier,rpc.ncount \
					   from dat_reader_path_tdoa p ,dat_reader r, \
					   (select count(*) as ncount, start_reader_id, end_reader_id from dat_reader_path_tdoa group by start_reader_id, end_reader_id) rpc\
					   where p.start_reader_id = r.reader_id \
					   and p.start_reader_id = rpc.start_reader_id and p.end_reader_id = rpc.end_reader_id \
					   and (p.start_reader_id =%d or p.end_reader_id = %d) \
					   order by p.start_reader_id, p.end_reader_id, p.idx;", reader_id, reader_id);
	}

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

	//查询数据库
	pRes = getMysqlRes(sql);

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

	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 = atoi(pRow[7]);

		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 = 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 = 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_TDOA_READER_PATH), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);

	return 0;
}

/*
* 初始化硐室表
*
* param
*		无
*
* return
*		成功返回0，失败返回1
*
*/
int CYAServerDlg::init_chamber(int chamber_id)
{
	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 = getMysqlRes(sql);

	if (NULL == pRes)
	{
		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)
{
	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 = getMysqlRes(sql);

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

	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)
{
	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 = getMysqlRes(sql);
	if (NULL == pRes)
	{
		return 0;
	}

	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*/)
{
	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 = getMysqlRes(sql);
	if (NULL == pRes)
	{
		return 0;
	}

	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, m_nPort))
	{
		::LogServerStart(m_tcp_host, m_nPort);
		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, CONNID dwConnID )
{
	if(DataBuffer == NULL){
		return;
	}

	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_36);

	std::string strBuf = "";
	if(m_log_raw_data){
		formatByteArray(strBuf, DataBuffer, nLen);
		Log::write_log(FILE_TYPE::RAW_S, strBuf, false);
	}

	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){
			strBuf = "CRC校验不通过";
			Log::write_log(FILE_TYPE::RAW_S, strBuf, false);
		}
		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, "reader not registered: %d", 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, "reader not registered: %d", 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);
				}
			}
			else{
				debug_print_syslog(0, "reader not registered: %d", 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);
				}
			}
			else
			{
				debug_print_syslog(0, "reader not registered: %d", reader_id);
			}
			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);

		}
	case RECV_TOF_DATA_AND_INS:
		{
			// 接收tof协议中带惯导的数据
			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()){
				while(nCurPos < nLen - (int)sizeof(WORD)){ // 减去crc // 可能会有死循环
					if (parse_data_locate_card(DataBuffer, nCurPos, reader_id, wChr)){
						break;
					}
				}
			}
			else
			{
				debug_print_syslog(0, "reader not registered: %d\n", reader_id);
			}
			break;
		}
	default:
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_8);
		break;
	}
	strtime.ReleaseBuffer();
}

void CYAServerDlg::parse_data_locate_reader(BYTE * DataBuffer, int& nCurPos, int nLen, CONNID 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, CONNID 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);
	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);
			card->is_registered = false;
			card->set_reader_path(mp_reader_path_list_tof, mp_reader_path_list_tdoa);		
		}
#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->is_registered = false;
	}
	// 设置当前分站， 进入分站时间、进入区域时间，当前区域，当前地图
	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;
	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);
	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;

	/*CString strCardId = _T("");
	strCardId.Format(_T("%s"),CFunctions::c2wc(str_card_id.c_str()));
	TRACE(strCardId);*/

	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);
		card->is_registered = false;
		card->set_reader_path(mp_reader_path_list_tof, mp_reader_path_list_tdoa);
	}
	// 设置当前分站， 进入分站时间、进入区域时间，当前区域，当前地图
	std::shared_ptr<Reader> pReader(it->second);
	card->set_reader(pReader);
	card->reader_tickcount = pReader->tick_count;
	card->is_hist = false;

	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:
		{
			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 = 0;
	BYTE btInsStatus = 0;
	float fx = 0.0f;		//惯导上传的x坐标
	float fy = 0.0f;		//惯导上传的y坐标
	bool bHasIns = false;	//是否有惯导数据
	if (RECV_TOF_DATA_AND_INS == wChr)
	{
		BYTE btHelp = 0;
		btHelp = (btCallType>>4)&0x80;

		BYTE btResponse = 0;
		btResponse = btCallType&0x7F;

		//惯导校准状态
		BYTE btVal = 0;
		
		memcpy(&btVal, &DataBuffer[nCurPos], sizeof(BYTE));
		nCurPos += sizeof(BYTE);

		//惯导状态，0正常，1请求校准
		btInsStatus = (btVal >> 4)&0x80;

		//如果上传的数据格式是带惯导的tof数据
		bHasIns = true;
		//解析x坐标,测试数据：00 00 00 01
		DWORD dwx;
		CFunctions::getDWord(&DataBuffer[nCurPos],&dwx,nCurPos);
		fx = CFunctions::dword2Float(dwx);
		//fx = CFunctions::getFloat(&DataBuffer[nCurPos]);
		nCurPos += sizeof(float);
		//解析y坐标，测试数据：00 08 00 00
		DWORD dwy;
		CFunctions::getDWord(&DataBuffer[nCurPos],&dwy,nCurPos);
		fy = CFunctions::dword2Float(dwy);
		//fy = CFunctions::getFloat(&DataBuffer[nCurPos]);
		nCurPos += sizeof(float);
	}else{
		//加速度
		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, CFunctions::TOF);
		if(-1 == dldist)
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_71);
		}
	}else if (RECV_TOF_DATA_AND_INS == wChr)
	{
		//如果上传的数据格式是带惯导的tof数据
		bHasIns = true;
		//计算距离
		dldist = CFunctions::getDistance(lTime1, CFunctions::TOF);
		//保存惯导请求校准状态：0为正常，1为请求校准
		card->ins_request_check = btInsStatus;
		if (btInsStatus)
		{
			//如果请求校准，则保存此刻惯导坐标
			if (card->cur_ins_pos == nullptr)
			{
				card->cur_ins_pos = std::shared_ptr<POS>();
			}
			card->cur_ins_pos->posx = fx;
			card->cur_ins_pos->posy = fy;
		}
	}

	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_id = btCallType;
		if (btCallType!=0)
		{
			card->vt_deal_call_reader_id.push_back(card->reader_id);
			if (btCallType == 0x80)
			{
				if(PDT_DOWN == card->p_reader->pos_state)
				{
					if(card->status_help < 2)
					{
						card->status_help = STATUS_ERROR;
					}
				}
				else
				{
					card->status_help = STATUS_NORMAL;
				}
			}
		}
		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){ // 呼救
				if(card->status_help < 2)
				{
					card->status_help = STATUS_ERROR;
				}				
			}else if(btCmd & 0x02){ // 呼叫应答，即呼叫成功
				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(CONNID 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(CONNID 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);
			//删除之前，判断此连接是否为信号灯控制分站，如果是，则需要将此控制分站所控制的红绿灯的状态设置为不可用
			_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);
				//入井时间戳
				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);
				//入井时间戳
				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())
				{
					//入井时间戳
					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()
{
	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::parse_json_data_reader_pos_change(message::ptr const& data)
{
	init_reader();
	debug_print_syslog(0, "Init reader postion success.");
	init_drivingface_card();//lemon 2017/07/31
	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;
		}
		if (!need_display_verification(it_adhoc->second))
		{
			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;
		}
		if (!need_display_verification(it_person->second))
		{
			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]);
		//路段开始报警时间
		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]);

		//路段开始报警时间
		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]);

			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;
}

std::string CYAServerDlg::get_json_special_area_process(std::shared_ptr<Card> card /*Card* card*/ )
{
	//是否特殊区域
	AreaMap::iterator it_area_cur = mp_area_list.find(card->area_id);
	if(it_area_cur == mp_area_list.end())
	{
		return NULL;
	}

	//新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]);

	//x,y坐标
	val_card[JSON_KEY_CORDINATE_X] = CFunctions::round(card->x_offset_after(),2);
	val_cards.append(val_card[JSON_KEY_CORDINATE_X]);
	val_card[JSON_KEY_CORDINATE_Y] = CFunctions::round(card->y_offset_after(),2);
	val_cards.append(val_card[JSON_KEY_CORDINATE_Y]);

	//入井时间戳
	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_AREA_IS_SPECIAL] = it_area_cur->second->is_special();
	val_cards.append(val_card[JSON_KEY_AREA_IS_SPECIAL]);

	//部门编号
	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_down_vehicle.begin();it_card != mp_card_list_down_vehicle.end();++it_card)
	{
		Json::Value val_card;
		Json::Value val_cards;

		if (_isnan(it_card->second->x) || _isnan(it_card->second->y) || _isnan(it_card->second->get_speed()))
		{
			continue;
		}
		if (fabs(it_card->second->x) < 1E-4 && fabs(it_card->second->y) < 1E-4)
		{
			continue;
		}
		if(INVALID_COORDINATE == it_card->second->x || INVALID_COORDINATE == it_card->second->y)
		{
			continue;
		}

		if(0 == it_card->second->area_id)
		{
			continue; 
		}
		//lemon 2017/08/01
		if (!need_display_verification(it_card->second))
		{
			continue;
		}
		//卡号
		val_cards.append(it_card->second->card_id);

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

		//入井时间戳
		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 = 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;
}
/************************************************************************/
/* 如果返回true表明正常走需要推送
	如果返回false 表明这标识卡不允许推送到web*/
/************************************************************************/
bool CYAServerDlg::need_display_verification(std::shared_ptr<Card> card)
{
	RulesMap::iterator it = m_rules_list.find(NEED_DISPLAY_RULES);
	if (it != m_rules_list.end())
	{
		if (NEED_DISPLAY_VALID == it->second )
		{
			if (0 == card->need_display)
			{
				return false;
			}
			else
			{
				return true;
			}
		}
		else
		{
			return true;
		}
	}
	return true;
}
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_cards.append(card->card_id);

	//x,y坐标
	val_cards.append( CFunctions::round(card->x_offset_after(),2));
	val_cards.append(CFunctions::round(card->y_offset_after(),2));

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

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

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

	//地图编号
	val_cards.append(card->map_id);
	//区域编号
	val_cards.append(card->area_id);
	//部门编号
	val_cards.append(card->dept_id);

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

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

		//业务状态
		val_cards.append(card->StateBiz());

		//速度
		val_cards.append(CFunctions::round(card->get_speed(), 0));
	}else{
		//状态
		val_cards.append(0);

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

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

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

	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();
}

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

	shift_id = GetCurShiftId(current_time);

	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);

	shift_id = GetCurShiftId(current_time);

	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;
		current_time->tm_mday  = current_time->tm_mday - 1;
	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::GetCurShiftEndTime()
{
	time_t t = time(NULL);
	struct tm* current_time = localtime(&t);

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

	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);
	std::shared_ptr<DrivingfaceCard> pDrivingfaceCard = nullptr;
	DrivingfaceCardMap::iterator it = mp_driving_face_card_list.find(card->card_id);
	if(it == mp_driving_face_card_list.end()){
		return "";
	}
	else
	{
		pDrivingfaceCard = it->second;
  //     last_total_finsh_length = sqrt(pow(card->driving_face_cur_shift_x - pDrivingfaceCard->x, 2)
		//	+ pow(card->driving_face_cur_shift_y - pDrivingfaceCard->y, 2)
		//	+ pow(card->driving_face_cur_shift_z - pDrivingfaceCard->z, 2)) * card->map_scale;
		//
		//cur_total_finish_length = sqrt(pow(card->x - pDrivingfaceCard->x, 2)
		//	+ pow(card->y - pDrivingfaceCard->y, 2)
		//	+ pow(card->z - pDrivingfaceCard->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,pCardx:%.3f,PCatdy:%.3f.last_total_finsh_length:%.3f,cur_total_finish_length:%.3f,cur_shift_finish_length:%.3f", 
		//	card->x, 
		//	card->y,
		//	card->z,
		//	pDrivingfaceCard->x,
		//	pDrivingfaceCard->y,
		//	last_total_finsh_length,
		//	cur_total_finish_length,
		//	cur_shift_finish_length);
		//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_x, 2);
	pos_cards.append(pos_card[JSON_KEY_CORDINATE_X]);
	pos_card[JSON_KEY_CORDINATE_Y] = CFunctions::round(card->driving_face_cur_shift_y, 2);
	pos_cards.append(pos_card[JSON_KEY_CORDINATE_Y]);

	//入井时间戳
	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 = (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 = 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 = card->m_curshift_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, card->m_curshift_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(card->m_curshift_finish_length, 2);
	pos_cards.append(pos_card[JSON_KEY_DRIVINGFACE_DIS]);

	get_drivingface_warning_point_dis(card);
	double tmpdistance;
	int tmpid;
	if (card->m_minDistanceToWarningpoint == DBL_MAX)
	{
		tmpdistance = 0;
		tmpid =0;
		Log::write_log(SYS_S,"【lemon】dirvingface there is no warningPoint ....",true);
	}
	else
	{
		tmpdistance = card->m_minDistanceToWarningpoint;
		tmpid = card->m_warning_point_id;
	}

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

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

	//当前完成的长度
	pos_card[JSON_KEY_DRIVINGFACE_CURSHIFT_LENGTH] = CFunctions::round(card->m_cur_total_finish_length,2);
	pos_cards.append(pos_card[JSON_KEY_DRIVINGFACE_CURSHIFT_LENGTH]);

	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());
	Log::write_log(JSON_S,ret,true);
	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; 
}

/*
下面这个函数就是为了构造json的单条卡的定位信息，detail是多卡，但是下面是填写单卡，如下：
"detail":[
["0020000001037",3486.530,75.0,1499512539000.0,1499512530000.0,1499512559000.0,20000.0,5,1,1,0,2,0,0.0,0,0,0.0,0]
]
*/
int CYAServerDlg::get_json_node_position( std::shared_ptr<Card> card, Json::Value &detailNode )
{
	// 卡号
	detailNode.append(card->card_id); // 0
	//写数据库需要的相关变量
	char _time[STR_LEN_TIME], _time_ex[STR_LEN_TIME];
	char sql[LENGTH_SQL] = {0};
	//需要考虑 坐标为零的数据
	if (VT_DIGGINGCOAL_MACHINE == card->vehice_type_id || VT_DRIVINGFACE_MACHINE == card->vehice_type_id)
	{
		detailNode.append( CFunctions::round(card->x, 2)); // 1
		detailNode.append( CFunctions::round(card->y, 2)); // 2
	}
	else
	{
		detailNode.append( CFunctions::round(card->x_offset_after(), 2)); // 1
		detailNode.append( CFunctions::round(card->y_offset_after(), 2)); // 2
	}
	
	//入井时间戳
	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

	if(POS_DEVICE_TYPE::PDT_DOWN == card->PosState())
	{
		//工作时长
		t = difftime(time(NULL), card->down_time)*ms;
	}
	else
	{
		t = 0; // lihongzhen  2017/8/17 16:53 结束考勤不推送时长数据
	}
	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(card->get_speed()); // 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->level_id); //17
	// 升入井状态，测试用
	//detailNode.append(card->pos_state); // 18
	//json的所有数据准备完毕，下面函数返回，接下来的代码应该是发送
	//返回0 表示成功
	return 0;
}

// 构造车辆的json数据
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;
				}
				if(0 == it_card->second->area_id)
				{
					dept_sum--;
					continue; 
				}

				if(VT_DRIVINGFACE_MACHINE == it_card->second->vehice_type_id || VT_DIGGINGCOAL_MACHINE == it_card->second->vehice_type_id)
				{
					dept_sum--;
					continue;
				}

				//lemon 2017/08/01
				if (!need_display_verification(it_card->second))
				{
					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;
				}
				if(0 == it_card->second->area_id)
				{
					dept_sum--;
					continue; 
				}
				//lemon 2017/08/01 
				if (!need_display_verification(it_card->second))
				{
					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->level_id, &occLevelStatisticHeader);
				insert_data(0, it_card->second->area_id, &areaStatisticHeader);
				insert_data(0, it_card->second->level_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;
}

/*
//刘思平修订的代码Part 8/Sum 8:begin
刘思平修订的代码Part 7/Sum 7:begin
构造json的时候无须考虑人卡和车卡的区别，所以下面的代码变量虽然是veicle，其实暗含了人在内
by lsp on 2017.07.09 @山西长治
这个函数是构造整个json，如果此步完成，那么就json构造完成
这个json包括了车和人，构造成一个json，一次发送
*/
std::string CYAServerDlg::get_json_card_statistic()
{
	Json::Value root;
	Json::Value data;
	Json::Value v;
	Json::Value s;
	//构造veicle的json，如果返回值为1，那么意味着发生了异常，直接返回空串给上一级，表示未成功
	if(get_json_statistic_vehicle_data(v) == 1){
		return "";
	}

	//构造person的json，如果返回值为1，那么意味着发生了异常，直接返回空串给上一级，表示未成功
	if(get_json_statistic_staff_data(s) == 1){
		return "";
	}

	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; //返回包含json信息的字符串
}

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

	std::string meta_data = "";
	for (int i = 0;i < 4;i++)
	{
		meta_data = "";
		switch(i){
		case 0:
			meta_data = get_json_card_statistic();
			break;
		case 1:
			meta_data = get_json_event(true);
			break;
		case 2:
			meta_data = get_json_call_list();
			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();
	}

	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["name"] = JSON_VALUE_USERNAME;
	root[JSON_ROOT_KEY_CMD] =  JSON_CMD_VALUE_LOGOUT;
	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);
		}
		// 备用地址
		if(is_websocket_ok_ex){
			_io_ex->socket()->emit(cmd, utf8_data);
			is_websocket_login_ex = 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)
			{
				Log::write_log(FILE_TYPE::JSON_S, data, true);
			}
		}
		// 备用地址
		if(is_websocket_login_ex)
		{
			strlog.Format(_T("%s: %s"), _T(LOG_SEND_JSON_DATA), _T("常规数据"));
			_io_ex->socket()->emit(cmd, utf8_data);
		}
	}
	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++;
		//	}
		//	deal_area_over_speed(it_card_vehicle->second);
		//	//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 = it_Area->second->area_card_list_person;
		//it_Area->second->count_vehicle =  it_Area->second->area_card_list_vehicle;
		//it_Area->second->count_area_over_time_person = over_time_person;
		//it_Area->second->count_area_over_time_vehicle = 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(it_Area->second->over_count_person != 0)
		{
			count_person = it_Area->second->area_card_list_person->size();
			it_Area->second->count_person = count_person;
			if( count_person > it_Area->second->over_count_person )
			{ // 区域人员超员
				string s ;
				for (CardMap::iterator it_card_i = it_Area->second->area_card_list_person->begin();it_card_i != it_Area->second->area_card_list_person->end();it_card_i++)
				{
					s += it_card_i->second->card_id;
					s += "&";
				}
				debug_print_syslog(0,"[lemon area_card_over_person.%d]:%s",it_Area->second->area_id,s.c_str());

				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,0);
				}
				else
				{
					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->limit_value = it_Area->second->over_count_person;
							it_ev->second->cur_value = count_person;
							it_ev->second->is_sent = false;
						}
					}
					//如果继续超员
					//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(it_Area->second->over_count_vehicle != 0 )
		{
			count_vehicle = it_Area->second->area_card_list_vehicle->size();
			it_Area->second->count_vehicle = count_vehicle;
			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
				{
					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->limit_value = it_Area->second->over_count_person;
							it_ev->second->cur_value = count_vehicle;
							it_ev->second->cur_time = time(NULL);
							it_ev->second->is_sent = false;
						}
					}
				}
			}
			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 && sls_setting.over_time_person != 0){
					deal_alarm_card(card, mp_card_list_over_time_person, true,  AF_CARD_OVER_TIME);
				}
				else 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, false,  AF_CARD_OVER_TIME);
				}
				//井下超员

			}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 && sls_setting.over_time_vehicle != 0){
					deal_alarm_card(card, mp_card_list_over_time_vehicle, true, AF_CARD_OVER_TIME);
				}
				else 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, false, 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 == card->card_type) // 车辆不推送升入井消息
	{
		//lemon 2017/08/01
		if (need_display_verification(card))
		{
			send_json_data(JSON_CMD_VALUE_PUSH, get_json_down_and_up(card));
		}
		
	}
	if(PDT_DOWN == pdt)
	{ // 入井
		card_down_mine(card);
		if( PATROL_LEVEL_ID == card->level_id){
			init_patrol_info(card->card_id);
		}
	}
	else if(PDT_UP ==pdt)
	{
		// 升井，补全离开区域时间
		store_data_card(card, HIS_AREA_LOCATION_LEAVE);
		if(PATROL_LEVEL_ID == card->level_id){
			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;
	}
	time_t current_time(time(NULL));
	if(card->b_pos_change){
		bool b_in_area = false;
		_point p1, p2;
		double r, scale;
		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)) { 
				bool is_true = false;
				std::shared_ptr<CardMap> destlist = nullptr;
				// 卡所在区域没有变化  判断是否超时
				if (card->card_type == CT_PERSON)
				{
					is_true = difftime(current_time, CFunctions::systime_to_timet(card->enter_area_time)) > it_area_cur->second->over_time_person;
					destlist = mp_card_list_area_over_time_person;
					if (!is_true && card->is_area_over_time)
					{
						deal_alarm_card(card,destlist,false,AF_CARD_AREA_OVER_TIME);
					}
					if (it_area_cur->second->over_time_person == 0)
					{
						is_true = false;
					}
				}
				else if (card->card_type == CT_VEHICLE)
				{
					is_true = difftime(current_time, CFunctions::systime_to_timet(card->enter_area_time)) > it_area_cur->second->over_time_vehicle;
					destlist = mp_card_list_area_over_time_vehicle;
					if (!is_true && card->is_area_over_time)
					{
						deal_alarm_card(card,destlist,false,AF_CARD_AREA_OVER_TIME);
					}
					//////////////////////////////////////////////////////////////////////////
					//断是否超速
					deal_area_over_speed(card);
					if (it_area_cur->second->over_time_vehicle == 0)
					{
						is_true = false;
					}
				}
				if(is_true)
				{
					if(!card->is_area_over_time)
					{
						card->is_area_over_time = true;
						card->time_area_over_time = current_time;
						deal_alarm_card(card, destlist, is_true, AF_CARD_AREA_OVER_TIME);
						if (card->card_type == CT_PERSON)
						{
							it_area_cur->second->count_area_over_time_person++;
						}
						else if (card->card_type == CT_VEHICLE)
						{
							it_area_cur->second->count_area_over_time_vehicle++;
						}
					}
				}
				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;
					//处理区域超速告警
					if (card->card_type == CT_VEHICLE)
					{
						deal_area_over_speed(card);
					}

					set_card_pos_state(card);

					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
			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;
			}

			AreaMap::iterator it_area_exists = mp_area_list.find(card->area_id);
			if(it_area_exists != mp_area_list.end()){ 
				store_data_card(card, HIS_AREA_LOCATION_LEAVE);
				card_leave_area(card, it_area_exists->second);
			}
			card->area_id = it_area_reader->second->area_id;
			card->enter_area_time = card->deal_time;
			//区域超速告警
			if (card->card_type == CT_VEHICLE)
			{
				deal_area_over_speed(card);
			}

			set_card_pos_state(card);

			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);
				}
			}
		}
	}
	else
	{
		if(PDT_UP ==  card->p_reader->pos_state || LOCATE_TYPE::LT_READER == theApp.locate_type) // 井上按照分站所属区域划分
		{
			// 找不到区域，使用分站所属区域
			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;
			}

			AreaMap::iterator it_area_exists = mp_area_list.find(card->area_id);
			if(it_area_exists != mp_area_list.end()){ 
				store_data_card(card, HIS_AREA_LOCATION_LEAVE);
				card_leave_area(card, it_area_exists->second);
			}
			card->area_id = it_area_reader->second->area_id;
			card->enter_area_time = card->deal_time;
			set_card_pos_state(card);
			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);
				}
			}
		}
		else
		{
			return ;
		}
	}

	// 保存区域信息
	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;
	set_card_pos_state(card);

	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);

	// 保存区域信息
	store_data_card(card, HIS_AREA_LOCATION_ENTER);
	store_data_card(card,HIS_LOCATION);
}

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;
	}
	//lemon 2017/08/06 这个地方是离开区域进入新区域
	//这里不应该判断吧，而且并没有对is_area_over_time进行赋值
	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);
			if (CT_PERSON == card->call_type_id)
			{
				area->count_area_over_time_person --;
			}
			else if (CT_VEHICLE == card->card_type)
			{
				area->count_area_over_time_vehicle --;
			}
		}
		// 先处理，后删除-
		deal_alarm_card(card, alarm_forbidden_map, false, AF_CARD_AREA_FORBIDDEN);
		deal_alarm_card(card,area->area_card_list_over_speed,false,AF_CARD_AREA_OVER_SPEED);
		card->m_indexCardSpeed  = 0;
		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;
}

//1秒周期中调用了本函数，先构造json，然后发送之
void CYAServerDlg::package_data()
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_223);

	string strJson = get_json_card_statistic();
	// 定位数据
	if(strJson == ""){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_224);
		return ;
	}
	send_json_data(JSON_CMD_VALUE_PUSH, strJson);
}

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 )
{
	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";
		}
	}
}

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;
	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;
}

void CYAServerDlg::OnFailed()
{
	is_websocket_login = false;
	is_websocket_ok = false;
	_io->close();
}

void CYAServerDlg::ws_open()
{
	_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()
{
}

void CYAServerDlg::store_data_card(std::shared_ptr<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:
		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 RPT_ATTEND_DOWN:
		localtime_s(&local_time, &card->down_time);
		strftime(_time, 30, "%Y-%m-%d %H:%M:%S", &local_time);
		break;
	case RPT_ATTEND_UP:
		localtime_s(&local_time, &card->up_time);
		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;
				switch (card->card_type)
				{
				case CT_PERSON:
					sprintf_s(sql, LENGTH_SQL, 
						"INSERT IGNORE INTO his_location_staff(card_id, staff_id, cur_time, x, y, z, map_id, area_id, state,speed,mileage, landmark_id, direction_mapper_id, landmark_dist) VALUES(%s, %d, '%s', %.3f, %.3f, %.3f, %d, %d, %d,%.3f,%.4f, %d, %d, %.4f);",  
						card->card_id.c_str(), card->id, _time, card->x_offset_after(), card->y_offset_after(), card->z_offset_after(), card->map_id, card->area_id, card->state,card->get_speed(),card->mileage, card->landmark_id, card->landmark_direction, card->landmark_dis);
					break;
				case CT_VEHICLE:
	 				sprintf_s(sql, LENGTH_SQL, 
						"INSERT IGNORE INTO his_location_vehicle(card_id, vehicle_id, cur_time, x, y, z, map_id, area_id, state,speed,mileage, landmark_id, direction_mapper_id, landmark_dist) VALUES(%s, %d, '%s', %.3f, %.3f, %.3f, %d, %d, %d,%.3f,%.4f, %d, %d, %.4f);",  
						card->card_id.c_str(), card->id, _time, card->x_offset_after(), card->y_offset_after(), card->z_offset_after(), card->map_id, card->area_id, card->state,card->get_speed(),card->mileage, card->landmark_id, card->landmark_direction, card->landmark_dis);
					break;
				}				
			}
			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;
				switch (card->card_type)
				{
				case CT_PERSON:
					sprintf_s(sql, LENGTH_SQL,
						"call add_area_staff(%s, %d, %d, %d, '%s','%s');",
						card->card_id.c_str(), card->id, card->area_id, card->map_id, _time, _time);
					break;
				case CT_VEHICLE:
					sprintf_s(sql, LENGTH_SQL,
						"call add_area_vehicle(%s, %d, %d, %d, '%s','%s');",
						card->card_id.c_str(), card->id, card->area_id, card->map_id, _time, _time);
					break;
				}
			}
			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);

				switch (card->card_type)
				{
				case CT_PERSON:
					sprintf_s(sql, LENGTH_SQL,
						"call add_area_staff(%s, %d, %d, %d, '%s','%s');",
						card->card_id.c_str(), card->id, card->area_id, card->map_id, _time_ex, _time);
					break;
				case CT_VEHICLE:
					sprintf_s(sql, LENGTH_SQL,
						"call add_area_vehicle(%s, %d, %d, %d, '%s','%s');",
						card->card_id.c_str(), card->id, card->area_id, card->map_id, _time_ex, _time);
					break;
				}
			}
			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, %d, '%s', '%s', %d, %d, %.3f);",
						card->card_id.c_str(), card->id, _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, %d, '%s', '%s', %d, %d, %.3f);",
						card->card_id.c_str(), card->id, _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, %d, '%s', '%s', %d, %d, %.3f);",
						card->card_id.c_str(), card->id, 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, %d, '%s', '%s', %d, %d, %.3f);",
						card->card_id.c_str(), card->id, str_down_time.c_str(), _time, card->landmark_id, card->landmark_direction, card->landmark_dis);
					break;
				}
			}
			break;
		}
	default:
		return;
	}

	if(b_exec){
		execute_sql(sql);
	}
}

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

	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_bk.host = theApp.dbhost_bk;
	m_db_setting_bk.user = theApp.dbuser_bk;
	m_db_setting_bk.password = theApp.dbpwd_bk;
	m_db_setting_bk.dbname = theApp.dbname_bk;
	m_db_setting_bk.encoding = theApp.dbencoding_bk;
	m_db_setting_bk.port = theApp.dbport_bk;
	//	break;
	//}
	if((theApp.dbhost_bk.length() >0 && theApp.dbhost_bk != theApp.dbhost) || (theApp.dbname.length()>0 && theApp.dbname_bk != theApp.dbname))
	{
		g_StoreMultDatabase = true;
	}
}

int CYAServerDlg::init_dept()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	pRes = getMysqlRes("select dept_id, name from dat_dept order by rank;");
	if(NULL == pRes)
	{
		return 1;
	}

	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()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;

	pRes = getMysqlRes("select occupation_level_id from dat_occupation_level;");

	if(NULL == pRes)
	{
		return 1;
	}
	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()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	pRes = getMysqlRes("select setting_id, name, type, value from dat_setting;");

	if (NULL == pRes)
	{
		return 1;
	}
	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());
		}else if("att_starttime_offset_staff" == name){
			sls_setting.att_starttime_offset_staff = atoi(val.c_str()) * 60;
		}else if("att_endtime_offset_staff" == name){
			sls_setting.att_endtime_offset_staff = atoi(val.c_str()) * 60;
		}else if("att_starttime_offset_vehicle" == name){
			sls_setting.att_starttime_offset_vehicle = atoi(val.c_str()) * 60;
		}else if("att_starttime_offset_vehicle" == name){
			sls_setting.att_endtime_offset_vehicle = atoi(val.c_str()) * 60;
		}
	}
	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(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;
				//card->m_CardHasBeenInDrivingfaceAlarm = is_alarm;//lemon 
				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->is_area_over_time = is_alarm;
				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;
			}
		case AF_CARD_NEAR_WARNING_POINT://lemon 2017/07/30 
			{
				et = ET_CARD_DRIVINGFACE_WARNING_AREA;
				limit_val = card->m_warning_threshold;
				cur_val = card->m_minDistanceToWarningpoint;

				card->m_isWarning = is_alarm;
				break;
			}
		case AF_CARD_NEAR_DRRIVINGFACE_VEHICLE:
			{
				et = ET_CARD_NEAR_DRIVINGFACE_VEHICLE;
				limit_val = card->getDrivingfaceLimitValue();
				cur_val = card->getDrivingfaceCulValue();

				card->time_area_forbidden = is_alarm ? time(NULL) : 0;
				card->status_area_forbidden = is_alarm ? 1 : 0;
				card->m_CardHasBeenInDrivingfaceAlarm = is_alarm;//lemon 
				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_offset_after();
					it_ev->second->y = card->y_offset_after();
					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;
				if (tag == AF_CARD_NEAR_WARNING_POINT)
				{
					ev->obj_type = OT_DRIVINGFACE_AREA;
					int id = (mp_driving_face_card_list.find(card->card_id))->second->drivingface_id;
					char buf[15] = { 0 };
					ev->obj_id = itoa(id,buf,10);
				}
				else
				{
					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_offset_after();
				ev->y = card->y_offset_after();
				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);
			}
		}
	}
}
/*
	掘进机进入危险范围告警 lemon 
*/
void CYAServerDlg::deal_drivingface_alarm_all()
{
	DrivingfaceCardMap::iterator it_drivingface = mp_driving_face_card_list.begin();
	string card_id;
	for(;it_drivingface != mp_driving_face_card_list.end();++it_drivingface)
	{
		card_id = it_drivingface->first;
		CardMap::iterator it = mp_card_list_all.find(card_id);
		shared_ptr<Card> card = nullptr;
		if (it != mp_card_list_all.end())
		{
			card = it->second;
			get_drivingface_warning_point_dis(card);
			if(card->card_type == CT_VEHICLE)
			{
				if (card->m_minDistanceToWarningpoint < card->m_warning_threshold)
				{
					if(!card->m_isWarning)
					{
						deal_alarm_card(card,mp_card_warning_point_alarm,true,AF_CARD_NEAR_WARNING_POINT);
					}
				}
				else
				{
					if (card->m_isWarning)
					{
						deal_alarm_card(card,mp_card_warning_point_alarm,false,AF_CARD_NEAR_WARNING_POINT);
					}
				}

			}
			
		}
	}
}
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_offset_after();
    	ev->y = card->y_offset_after();
    	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_offset_after();
    	ev->y = card->y_offset_after();
		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,int type )
{
	if(is_alarm)
	{
		dest_area_list->insert(make_pair(area->area_id, area));
	}
	else
	{
		AreaMap::iterator it_area = dest_area_list->find(area->area_id);
		if(it_area != dest_area_list->end())
		{
			dest_area_list->erase(it_area);
		}
		else
		{
			return;
		}
	}
}

/*
* 根据车卡位置来实行红绿灯策略
*
* 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 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 (INIT_STREAM == card->m_nStream)
		{
			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){
							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_id > it_card->second->level_id)
							{
								bRet = true;
							}
							else if (card->level_id == it_card->second->level_id 
								&& (isInMainTunel(card)&&!isInMainTunel(it_card->second)))
							{
								bRet = true;
							}else if (card->level_id == it_card->second->level_id 
								&& (getTunelProperty(card)==getTunelProperty(it_card->second)&&(getTunelProperty(card)!=0))
								&& (card->m_nStream == UP_STREAM && it_card->second->m_nStream == 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:
						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:
						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)
		{
			card->m_indexCardSpeed++;
			if (card->m_indexCardSpeed >= SUSTAINEDOVERSPEED)
			{
				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 
		{
			card->m_indexCardSpeed = 0;
			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;
				}
			}
		}
	}

	return 0;
}

/*
* 从数据库的dat_alarm_type表初始化告警类型和名称
*
* param
*		无
*
* return
*		无
*/
int CYAServerDlg::init_alarm_type()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;
	int err = 0;
	pRes = getMysqlRes("select event_type_id, name from dat_event_type;");

	if(NULL == pRes)
	{
		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("通信分站"));
}

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();

	g_pConnPool->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 = g_pConnPool->InitAllConn();

	g_pConnPool_Bk->Init(m_db_setting_bk.encoding.c_str(), m_db_setting_bk.host.c_str(), m_db_setting_bk.user.c_str(), 
		m_db_setting_bk.password.c_str(), m_db_setting_bk.dbname.c_str(), m_db_setting_bk.port, NULL, 0);
	int nConn_bk = g_pConnPool_Bk->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();

		debug_print_syslog(0, "receive web cmd: %s", cmd.c_str());
		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);
			debug_print_syslog(0, "receive meta_data_changed: %s", name.c_str());
			if(JSON_KEY_NAME_VEHICLE == name || JSON_KEY_NAME_VEHICLE_EXTEND == 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 || JSON_KEY_NAME_STAFF_EXTEND == 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_KEY_NAME_RULES == name){
				int id = atoi(data_map[JSON_KEY_ID]->get_string().c_str());
				deal_call_edit_rules(id,edit_type_id);
			}else if(JSON_KEY_NAME_SETTING == name){
				//阈值限制接口
				init_setting();
			}else if (JSON_KEY_NAME_DRIVINGFACE == name)
			{
				init_drivingface_card();
			}else if (JSON_KEY_NAME_DRIVINGFACE_WARNING_POINT == name)
			{
				init_drivingface_warning_point();
			}
		}else if(JSON_CMD_VALUE_REQUEST_ALL_POSTION == cmd){
			//请求全部位置信息
			send_json_data(JSON_CMD_VALUE_REQUEST_ALL_POSTION, get_json_card_statistic());
			// 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(data);
		} 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);
		}
		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)
		{
			std::string sd = "";
			sd = get_json_all_data();
			send_json_data(JSON_CMD_VALUE_PUSH, sd);
		}
		else if(JSON_KEY_EVENT_READER_POS_CHANGE == cmd)
		{
			parse_json_data_reader_pos_change(data);
		}else if (JSON_CMD_DRIVING_FACE_STATE == cmd)
		{
			send_drivingface_card_position_json(true);
		}
	}
}

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 user_name = "", call_time = "";
	string cardid = "", readerid = "";
	int call_type_id = 0;
	int call_time_out = 0, reader_count = 0, card_count = 0, call_level_id = 0;
	long long call_time_interval = 0;

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

	call_type_id	= data_map[JSON_KEY_CALL_CARD_CALL_TYPE]->get_int();
	call_time_out	= data_map[JSON_KEY_CALL_CARD_CALL_TIME_OUT]->get_int();
	call_level_id	= data_map[JSON_KEY_CALL_CARD_CALL_LEVEL]->get_int();
	user_name		= data_map[JSON_KEY_CALL_CARD_USER_NAME]->get_string();
	call_time_interval = data_map[JSON_KEY_CALL_CARD_CALL_TIME]->get_int();

	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;

	EnterCriticalSection(&m_csCallInfo);

	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_card = card_vec.begin();
	std::string strCardId = "";
	int cardId = 0;
	int readerId = 0;
	// 全员
	if(CALL_CARD_TYPE::CCT_CALL_ALL == call_type_id)
	{
		// 删除指定用户的所有呼叫信息
		clear_call_card_by_user(user_name);
		// 重置全员呼叫信息
		call_reader = std::make_shared<_call_info_reader>();
		call_reader->call_level = call_level_id;
		call_reader->cards_count = 0;
		call_reader->is_call_all = true;
		call_reader->is_start_call = true;
		call_reader->start_time = time(NULL);
		call_reader->time_out = call_time_out;
		call_user->mpReader.insert(make_pair(reader_id, call_reader));
	}
	else // 定员
	{
		int nCounts = 0;
		int card_id = 0;
		BYTE card_type = 0;	
		string s_card_id = "";
		string s_card_type = "";
		// 如果有全员，定员不生效
		CallInfoReaderMap::iterator it_call_reader = call_user->mpReader.find(reader_id);
		if (it_call_reader == call_user->mpReader.end())
		{
			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_level_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_level > call_level_id){
						call_reader->call_level = call_level_id;
					}
				}else{
					call_reader = std::make_shared<_call_info_reader>();
					call_reader->call_level = call_level_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_level < call_level_id){ // 原呼叫优先级低
						call_card->card_type = card_type;
						call_card->call_level = call_level_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_level = call_level_id;
					call_card->str_card_id = s_card_id;
					call_reader->mpCard.insert(make_pair(s_card_id, call_card));
				}
			}
		}
	}

	LeaveCriticalSection(&m_csCallInfo);
	////呼叫发起有两种，
	////一种通过分站发起呼叫即为对此分站下的所有自组网卡全员呼叫
	////一种是对单卡发起的呼叫
	//vector<message::ptr>::const_iterator it_reader = reader_vec.begin();
	//for(; it_reader != reader_vec.end(); ++it_reader){
	//	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));
	//	}

	//	//当对某一个分站，不输入任何卡号，需要判断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 || "0" == str_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;

	//			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.substr(3, s_card_id.length()).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_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_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->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;

	//收到呼叫信息，即直接返回
	if (0 == call_type_id )
	{
		Json::Value callinfo;
		callinfo.append(user_name);
		callinfo.append(0);
		callinfo.append(0);
		callinfo.append((double)call_time_interval);
		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);
	}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((int)((*it_reader)->get_map()[JSON_KEY_CALL_CARD_STATION_ID]->get_int()));
						callinfo.append((double)call_time_interval);
						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);
					}
				}else{
					Json::Value callinfo;
					callinfo.append(user_name);
					callinfo.append(0);
					callinfo.append((int)((*it_reader)->get_map()[JSON_KEY_CALL_CARD_STATION_ID]->get_int()));
					callinfo.append((double)call_time_interval);
					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);
				}			
			}
		} 
		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((double)call_time_interval);
				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);
}


void CYAServerDlg::parse_json_data_clear_card(message::ptr const& data)
{

	//map<string,message::ptr> data_map = data->get_map()[JSON_ROOT_KEY_DATA]->get_map();
	//vector<message::ptr> card_vec = data_map[JSON_KEY_CALL_CARD_CARDS]->get_vector();

	vector<message::ptr> card_vec = data->get_map()[JSON_ROOT_KEY_DATA]->get_vector();

	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()){
		return ;
	}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();
			card_type = (*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID]->get_int();

			CardMap::iterator itt_card = mp_card_list_all.find(s_card_id);
			if(itt_card != mp_card_list_all.end()){
				if(STATUS_LOST == itt_card->second->status_lost)
				{
					// 升井
					itt_card->second->up_time = time(NULL);
					itt_card->second->PosState(PDT_UP);
					card_enter_mine(itt_card->second, POS_DEVICE_TYPE::PDT_UP);
				}
			}	
		}
	}
}

void CYAServerDlg::parse_json_data_deal_help( message::ptr const& data )
{
	map<string, message::ptr> data_map = data->get_map()[JSON_ROOT_KEY_DATA]->get_map();

	INT64 ev_id;
	string cardid = data_map[JSON_KEY_ID]->get_string();
	ev_id = data_map[JSON_KEY_EVENT_EVENT_ID]->get_int();

	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;
	}
	EventMap::iterator it_ev = mp_event_list->find(ev_id);
	if(it_ev != mp_event_list->end())
	{
		it_ev->second->status = ES_DEAL_HELP;
	}
	CString strlog;
	strlog.Format(_T("%s%s"), _T(LOG_DEAL_HELP), _T(LOG_SUCCESS));
	show_log(strlog);
}

/*
* 处理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;
}

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);
			break;
		}
	case ET_UPDATE:
		{
			init_reader(id);
			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 == atoi(id.c_str())){
					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 == atoi(id.c_str())){
					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 == atoi(id.c_str())){
					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;
}
void CYAServerDlg::deal_call_edit_rules(int id,EDIT_TYPE_ID edit_type_id)
{
	CString strlog;
	switch (edit_type_id)
	{
	case ET_INSERT:
		{
			 init_rules(id);
			break;
		}
	case ET_UPDATE:
		{
			init_rules(id);
			break;
		}
	case ET_DELETE:
		{
			RulesMap::iterator it_rules = m_rules_list.find(id);
			if(it_rules != m_rules_list.end())
				m_rules_list.erase(it_rules);
			break;
		}
	default:
		break;
	}
	strlog.Format(_T("%s%s"), _T(LOG_EDIT_STAFFER), _T(LOG_SUCCESS));
	show_log(strlog);
}

/*
 * 获得所有卡的惯导校准数据的列表，按分站归置
 *
 * param
 *		无
 *
 * return
 *		成功返回0，失败返回非零值
 *
*/
int CYAServerDlg::get_ins_cal_list()
{
	//mp_ins_cal_data_list->clear();
	for (CardMap::iterator it_card = mp_card_list_all.begin();it_card != mp_card_list_all.end();++it_card)
	{
		if (CAL_REQUEST == it_card->second->ins_request_check)
		{
			//it_card->second->deal_ins_cal_data();
			//如果校准，构造数据存入map中
			int nReaderId = -1;
			nReaderId = it_card->second->reader_id_algo;
			map<int,std::shared_ptr<CardCalData>>::iterator it_reader_cal_data = mp_ins_cal_data_list->find(nReaderId);
				
			if (it_reader_cal_data == mp_ins_cal_data_list->end())
			{
				//如果分站对应的map中不存在需要校准的卡数据map，构造此map
				std::shared_ptr<CardCalData> pCardCalData = nullptr;
				pCardCalData = std::make_shared<CardCalData>();
				mp_ins_cal_data_list->insert(std::make_pair(nReaderId,pCardCalData));
			}
			//如果分站对应的map中存在需要校准的卡数据
			CardCalData::iterator it_card_cal_data = it_reader_cal_data->second->find(it_card->second->card_id);
			if (it_card_cal_data == it_reader_cal_data->second->end())
			{
				std::shared_ptr<CAL_DATA> pCalData = nullptr;
				pCalData = std::make_shared<CAL_DATA>();
				it_reader_cal_data->second->insert(std::make_pair(it_card->second->card_id,pCalData));

			}
			it_card_cal_data->second->x = it_card->second->ins_gyp_pos->posx;
			it_card_cal_data->second->y = it_card->second->ins_gyp_pos->posy;
			it_card_cal_data->second->angle = it_card->second->ins_gyp_angle;
			it_card_cal_data->second->status = it_card->second->ins_cal_type;
		}else{

		}
	}

	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, occ_id = 0, level_id = 0;
	map_id = it_card->second->map_id;
	area_id = it_card->second->area_id;
	dept_id = it_card->second->dept_id;
	occ_id = it_card->second->occ_id;
	level_id = it_card->second->level_id;

	clear_card_from_list(it_card->second);

	// 避免状态重置
	mp_card_list_all.erase(it_card);
}

void CYAServerDlg::calculate_card_postion_by_tof(std::shared_ptr<Card> card) // 计算card坐标
{
	g_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::string drivingface_start_time = CFunctions::time_t2string(time(NULL));
	//掘进机启动时间
	card->m_drivingface_start_time = drivingface_start_time;

	std::shared_ptr<DrivingfaceCard> pDrivingfacecard = nullptr;
	DrivingfaceCardMap::iterator it = mp_driving_face_card_list.find(card->card_id);

	if(it == mp_driving_face_card_list.end()){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_237);
		return;
	}
	else
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_238);
		pDrivingfacecard = it->second;
		int drivingface_id = pDrivingfacecard->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 - pDrivingfacecard->x, 2)
			+ pow(card->driving_face_cur_shift_y - pDrivingfacecard->y, 2)
			+ pow(card->driving_face_cur_shift_z - pDrivingfacecard->z, 2)) * card->map_scale;
		
		cur_total_finish_length = sqrt(pow(card->x - pDrivingfacecard->x, 2)
			+ pow(card->y - pDrivingfacecard->y, 2)
			+ pow(card->z - pDrivingfacecard->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;
		}


		char buf[LENGTH_SQL] = {0};
		sprintf_s(buf,LENGTH_SQL,"process_driving_face_start_service[lemon]:card->x:%f,card->y:%f,card->driving_face_cur_shift_start_x:%f,card->driving_face_cur_shift_start_y:%f,card->driving_face_cur_shift_x:%f,card->driving_face_cur_shift_y:%f,last_total_finsh_length:%f,cur_total_finish_length:%f",
			card->x,card->y,card->driving_face_cur_shift_start_x,card->driving_face_cur_shift_start_y,card->driving_face_cur_shift_x,card->driving_face_cur_shift_y,last_total_finsh_length,cur_total_finish_length);
		Log::write_log(FILE_TYPE::SQL_S,buf,true);

		//掘进机启动坐标
		card->m_drivingface_start_x = card->driving_face_cur_shift_x;
		card->m_drivingface_start_y = card->driving_face_cur_shift_y;
		card->m_drivingface_start_z = card->driving_face_cur_shift_z;

		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,shift_id) \
			VALUES(%d, %s, %.3f, %.3f, '%s','%s', %.3f, %.3f, %.3f, %.3f, %.3f, %.3f,%d);",  
			drivingface_id, 
			card->card_id.c_str(), 
			cur_total_finish_length, 
			0.0,
			drivingface_start_time.c_str(), 
			drivingface_start_time.c_str(), 
			card->driving_face_cur_shift_x, 
			card->driving_face_cur_shift_y, 
			card->driving_face_cur_shift_z,
			card->driving_face_cur_shift_x, 
			card->driving_face_cur_shift_y, 
			card->driving_face_cur_shift_z,
			shift_id);

		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(card);
	}
	return;
}


void CYAServerDlg::send_drivingface_card_position_json(bool approve /*= false*/)
{
	DrivingfaceCardMap::iterator it_card = mp_driving_face_card_list.begin();
	for(;it_card!=mp_driving_face_card_list.end();it_card++)
	{
		string card_id = it_card->first;
	
		CardMap::iterator it_vehicle = mp_card_list_all.find(card_id);
		if(it_vehicle != mp_card_list_all.end())
		{
			if (((!it_vehicle->second->is_drivingface_Initialization) || (0 == it_vehicle->second->is_driving_face_start)) && !approve )
			{
				continue;
			}
			//begin here lemon 2017/08/01
			if (need_display_verification(it_vehicle->second))
			{
				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());
			}
			else
			{
				debug_print_syslog(0, "find drivingface card: %s.[do not display]", it_vehicle->second->card_id.c_str());
			}
			//update_driving_face_data(it_vehicle->second);
		}
		//debug_print_syslog(0, "period send drivingface card stat.%s", card_id.c_str());
	}
}

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<DrivingfaceCard> pDrivingfaceCard = nullptr;
	DrivingfaceCardMap::iterator it_card = mp_driving_face_card_list.find(card->card_id);
	if(it_card == mp_driving_face_card_list.end())
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_250);
		return;
	}
	else
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_251);
		pDrivingfaceCard = it_card->second;
		int drivingface_id = pDrivingfaceCard->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 - pDrivingfaceCard->x, 2)
			+ pow(card->driving_face_cur_shift_start_y - pDrivingfaceCard->y, 2)
			+ pow(card->driving_face_cur_shift_start_z - pDrivingfaceCard->z, 2)) * card->map_scale;;
		
		cur_total_finish_length = sqrt(pow(card->x - pDrivingfaceCard->x, 2)
			+ pow(card->y - pDrivingfaceCard->y, 2)
			+ pow(card->z - pDrivingfaceCard->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;

#ifdef _DEBUG
		char buf[LENGTH_SQL] = {0};
		sprintf_s(buf,"write_drivingface_shift_start_data[lemon]:card->x:%f,card->y:%f,card->driving_face_cur_shift_start_x:%f,card->driving_face_cur_shift_start_y:%f,card->driving_face_cur_shift_x:%f,card->driving_face_cur_shift_y:%f,last_total_finsh_length:%f,cur_total_finish_length:%f",
			card->x,card->y,card->driving_face_cur_shift_start_x,card->driving_face_cur_shift_start_y,card->driving_face_cur_shift_x,card->driving_face_cur_shift_y,last_total_finsh_length,cur_total_finish_length);
		Log::write_log(FILE_TYPE::SQL_S,buf,true);
#endif
#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()
{
	DrivingfaceCardMap::iterator it = mp_driving_face_card_list.begin();
	string card_id;
	for(;it != mp_driving_face_card_list.end();it++)
	{
	
		card_id = it->first;
		CardMap::iterator it_vehicle = mp_card_list_all.find(card_id);

		std::shared_ptr<Card> card = nullptr;
		if(it_vehicle != mp_card_list_all.end())
		{
			card = it_vehicle->second;
			if (!card->is_drivingface_Initialization)
			{
				continue;
			}
			if(card)
			{
				int shift_id = 0;
				GetCurShiftStartTime(shift_id);
				if (card->shift_id != shift_id)
				{
					card->shift_id = shift_id;
					cur_shift_id = shift_id;
					//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(card);
				}
				
			}
		}

	}
	return; 
}

void CYAServerDlg::process_driving_face_end_service(std::shared_ptr<Card> card)
{

	if(0 == card->is_driving_face_start)
	{
		return ;
	}
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_241);
	DrivingfaceCardMap::iterator it = mp_driving_face_card_list.find(card->card_id);

	if(it == mp_driving_face_card_list.end())
	{
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_242);
		return;
	}
	else
	{
		//跟新一下结束时间。1保证其结束时间的准确性2.确保
		std::string end_time = CFunctions::time_t2string(time(NULL));
		char sql[LENGTH_SQL] = { 0 };
		sprintf_s(sql,LENGTH_SQL,"update his_drivingface_his set end_time = '%s' where card_id = %s and start_time = '%s' ;",
			end_time.c_str(),
			card->card_id.c_str(),
			card->m_drivingface_start_time.c_str());

		Log::write_log(SYS_S,sql,true);
		execute_sql(sql);

		card->is_driving_face_start = 0;
		card->m_drivingface_start_time.clear();
		card->m_drivingface_start_x = 0.0;
		card->m_drivingface_start_y = 0.0;
		card->m_drivingface_start_z = 0.0;
	}
}

void CYAServerDlg::store_driving_face_data(std::shared_ptr<Card> card)
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_259);
	char sql[LENGTH_SQL] = {'\0'};
	int shift_id = 0;
	string str_card_id = card->card_id;
	//string str_card_id = CFunctions::getstrwithzero(2, 3) + CFunctions::getstrwithzero(1014, 10);
	std::string s = CFunctions::time_t2string(this->GetCurShiftStartTime(shift_id));

	if(card)
	{
		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<DrivingfaceCard> pDrivingfaceCard = nullptr;
		DrivingfaceCardMap::iterator it_card = mp_driving_face_card_list.find(str_card_id);
    	if(it_card == mp_driving_face_card_list.end())
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_261);
    		return;
    	}
    	else
    	{
    	    LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_262);
			pDrivingfaceCard = it_card->second;
			
            last_total_finsh_length = sqrt(pow(card->driving_face_cur_shift_x - pDrivingfaceCard->x, 2)
    			+ pow(card->driving_face_cur_shift_y - pDrivingfaceCard->y, 2)
    			+ pow(card->driving_face_cur_shift_z - pDrivingfaceCard->z, 2)) * card->map_scale;
    		
    		cur_total_finish_length = sqrt(pow(card->x - pDrivingfaceCard->x, 2)
    			+ pow(card->y - pDrivingfaceCard->y, 2)
    			+ pow(card->z - pDrivingfaceCard->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;
    		}
    	}

		char buf[LENGTH_SQL] = {0};
		sprintf_s(buf,LENGTH_SQL,"store_driving_face_data[lemon]:card->x:%f,card->y:%f,card->driving_face_cur_shift_start_x:%f,card->driving_face_cur_shift_start_y:%f,card->driving_face_cur_shift_x:%f,card->driving_face_cur_shift_y:%f,last_total_finsh_length:%f,cur_total_finish_length:%f",
			card->x,card->y,card->driving_face_cur_shift_start_x,card->driving_face_cur_shift_start_y,card->driving_face_cur_shift_x,card->driving_face_cur_shift_y,last_total_finsh_length,cur_total_finish_length);
		Log::write_log(FILE_TYPE::SQL_S,buf,true);
		//产生一条当前班次的一条记录，记录了当前班次的开始的距离，以及当前班次的距离，以及当前班次的开始坐标。
		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,start_x,start_y,start_z,end_x,end_y,end_z) values(%d, %s, %.3f, %d, %.3f,'%s',%.3f,%.3f,%.3f,%.3f,%.3f,%.3f);",
        it_card->second->drivingface_id,
		card->card_id.c_str(),
		last_total_finsh_length,
		card->shift_id,
		0.0,
		s.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_start_x,
		card->driving_face_cur_shift_start_y,
		card->driving_face_cur_shift_start_z);
		debug_print_syslog(0, "store driving face data sql: %s", sql);
		execute_sql(sql);
	}
	return;
}

void CYAServerDlg::update_driving_face_data(std::shared_ptr<Card> card)
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_263);
	char sql[LENGTH_SQL] = {'\0'};
	int shift_id = 0;
	bool is_true = false;
	std::string cur_shift_start_time = CFunctions::time_t2string(this->GetCurShiftStartTime(shift_id));
	if(card)
	{
		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::string drivingface_end_time = CFunctions::time_t2string(time(NULL));
		std::shared_ptr<DrivingfaceCard> pDrivingfacecard  = nullptr;
		DrivingfaceCardMap::iterator it_card = mp_driving_face_card_list.find(card->card_id);

    	if(it_card == mp_driving_face_card_list.end())
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_265);
    		return;
    	}
    	else
    	{
    	    LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_266);
			pDrivingfacecard = it_card->second;
    	  //  pDrivingfaceRender = it_render->second;
            last_total_finsh_length = sqrt(pow(card->driving_face_cur_shift_x - pDrivingfacecard->x, 2)
    			+ pow(card->driving_face_cur_shift_y - pDrivingfacecard->y, 2)
    			+ pow(card->driving_face_cur_shift_z - pDrivingfacecard->z, 2)) * card->map_scale;
    		//here get the total_finish_length?????--lemon
    		cur_total_finish_length = sqrt(pow(card->x - pDrivingfacecard->x, 2)
    			+ pow(card->y - pDrivingfacecard->y, 2)
    			+ pow(card->z - pDrivingfacecard->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)
    		{
				is_true = true;
    			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;
    		}
    	}
		//这里更新数据。
		card->m_cur_total_finish_length = cur_total_finish_length;
		card->m_curshift_finish_length = cur_shift_finish_length;

		char buf[LENGTH_SQL] = {0};
		sprintf_s(buf,LENGTH_SQL,"update_driving_face_data[lemon]:card->x:%f,card->y:%f,card->driving_face_cur_shift_start_x:%f,card->driving_face_cur_shift_start_y:%f,card->driving_face_cur_shift_x:%f,card->driving_face_cur_shift_y:%f,last_total_finsh_length:%f,cur_total_finish_length:%f",
			card->x,card->y,card->driving_face_cur_shift_start_x,card->driving_face_cur_shift_start_y,card->driving_face_cur_shift_x,card->driving_face_cur_shift_y,last_total_finsh_length,cur_total_finish_length);
		Log::write_log(FILE_TYPE::SQL_S,buf,true);

		sprintf_s(
		sql, 
		LENGTH_SQL,
		"update his_drivingface_shift_finish_length set  finish_length=%.3f,end_x=%.3f,end_y=%.3f,end_z = %.3f \
		where card_id = %s and cur_time = '%s';",
		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());
		if (is_true)
		{
			debug_print_syslog(0, "update driving face shift data sql real: %s", sql);
			execute_sql(sql);
			//如果掘进机启动则更新数据。
			if (1 == card->is_driving_face_start)
			{
				cur_shift_finish_length = sqrt(pow(card->driving_face_cur_shift_x - card->m_drivingface_start_x, 2)
					+ pow(card->driving_face_cur_shift_y - card->m_drivingface_start_y, 2)
					+ pow(card->driving_face_cur_shift_z - card->m_drivingface_start_z, 2)) * card->map_scale;
				sprintf_s(
					sql, 
					LENGTH_SQL,
					"UPDATE his_drivingface_his SET end_time = '%s' ,cur_finish_length = %.3f,end_x=%.3f,end_y=%.3f,end_z=%.3f WHERE card_id = %s AND start_time = '%s';",
					drivingface_end_time.c_str(),
					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(),
					card->m_drivingface_start_time.c_str());
				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<DrivingfaceCard> pDrivingfaceCard = nullptr;
	DrivingfaceCardMap::iterator it = mp_driving_face_card_list.find(card->card_id);		
	if(it == mp_driving_face_card_list.end()){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_246);
		return;
	}
	else
	{
		//mark lemon 2017/08/16
		if (!card->is_drivingface_Initialization)
		{
			card->is_drivingface_Initialization = true;
			card->driving_face_cur_shift_start_x = card->driving_face_cur_shift_x = card->x;
			card->driving_face_cur_shift_start_y = card->driving_face_cur_shift_y = card->y;
			card->driving_face_cur_shift_start_z = card->driving_face_cur_shift_z = card->z;
		}
		//here 
		
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_247);
		pDrivingfaceCard = it->second;
		int drivingface_id = pDrivingfaceCard->drivingface_id;
		float  finsh_length = 0;
		float cur_finish_length = 0;
		finsh_length = sqrt(pow(card->x - pDrivingfaceCard->x, 2)
			+ pow(card->y - pDrivingfaceCard->y, 2)
			+ pow(card->z - pDrivingfaceCard->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());
		DWORD cur_time = ::GetTickCount();
		if(cur_time - card->drive_face_location_write_time > WRITE_DRIVINGFACE_REAL_PER_TIME) //last time for write database...
		{
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_240);
			execute_sql(sql);
			card->drive_face_location_write_time = cur_time;

			//lemon 2017/08/16
			update_driving_face_data(card);
		}
	}
	return;
}

void CYAServerDlg::save_card_postion(std::shared_ptr<Card> card /* Card* card*/ )
{
	if (abs(card->x - INVALID_COORDINATE) < 1E-4 && abs(card->y - INVALID_COORDINATE) <1E-4)
	{
		//如果回到错误点
		return;
	}
	// 位置发生变化
	double moved_dist = sqrt(pow(card->x_offset_after() - card->stored_x, 2) + pow(card->y_offset_after() - 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;
	}

	card->stored_x = card->x_offset_after();
	card->stored_y = card->y_offset_after();
	card->stored_z = card->z_offset_after();

	//landmark ID
	GetLandmarkInfo(card);
	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 )
{
#ifdef _DEBUG
	return;
#endif // _DEBUG
	m_qsmSQL->AddString(sql);
	Log::write_log(FILE_TYPE::SQL_S, sql, true);
}

/*
* 日志菜单设置
*		将日志菜单设置内容同步更新到主对话框中的相应变量
*
* param
*		无
*
* return
*		无
*/
void CYAServerDlg::OnMenuLog()
{
	CLogSetting dlg;
	dlg.DoModal();

	//m_log_sys_status = theApp.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;
}

void CYAServerDlg::OnMenuParam()
{
	CSysSetting dlg;
	dlg.DoModal();
}

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::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 = 0;// it_call_reader->second->mpCard.size(); // it_call_reader->second->cards_count;
			memcpy(&buf[npos], &card_count, sizeof(BYTE));
			npos += sizeof(BYTE);
			//呼叫类型
			memcpy(&buf[npos], &it_call_reader->second->call_level, 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++){
					card_count++;
					//呼叫类型
					memcpy(&buf[npos], &it_call_card->second->call_level, 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();)
	{
		time_t current_time = time(NULL);
		CallInfoReaderMap::iterator it_call_reader = it_call_user->second->mpReader.begin();
		for( ;it_call_reader != it_call_user->second->mpReader.end();)
		{
			if(!it_call_reader->second->is_call_all)
			{
				if(difftime(current_time, it_call_reader->second->start_time) > it_call_reader->second->time_out * 60)
				{
					it_call_reader = it_call_user->second->mpReader.erase(it_call_reader);
					continue;
				}
			}
			else
			{
				CallInfoCardMap::iterator it_call_card = it_call_reader->second->mpCard.begin();
				for(; 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;
					}
				}
			}
			if(0 == it_call_reader->second->mpCard.size())
			{
				it_call_reader = it_call_user->second->mpReader.erase(it_call_reader);
			}
			else
			{
				++it_call_reader;
			}			
		}

		if(0 == it_call_user->second->mpReader.size())
		{
			it_call_user = mp_user_call_info.erase(it_call_user);
		}
		else
		{
			++it_call_user;
		}
	}
	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);

		//判断一下当前时间与卡的上一次接收时间的间隔时间是否小于阈值
		//如果小于阈值，则重置状态
		//如果大于阈值，则继续循环，不发送卡信息
		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 || it->second->acce_cur_state == STATE_ACCE_IDLING)//interval > val || 
		{
			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;
}

/*
 * 发送惯导数据
 *
 * param
 *		无
 * return
 *		成功执行返回0
 * 
*/
int CYAServerDlg::send_ins_data(const std::shared_ptr<Card> pCard)
{
	int nTotals = 0;
	BYTE SendBuffer[MSG_LENGTH_MAX] = {0};
	
	for (CalDataMap::iterator it = mp_ins_cal_data_list->begin();it != mp_ins_cal_data_list->end();++it)
	{
		int nReaderId = 0;
		nReaderId = it->first;
		int len = 0;
		for (CardCalData::iterator it_card = it->second->begin();it_card != it->second->end();++it_card)
		{
			if (it_card->second->status == -1)
			{
				continue;
			}
			nTotals++;
			//构造下发校准数据的消息
			int len = 1;
			//卡类型
			memcpy(&SendBuffer[len], &pCard->card_type, sizeof(BYTE));
			len += sizeof(BYTE);
			//卡id长度
			BYTE id_len = (BYTE)get_card_id_len(pCard->card_type);
			memcpy(&SendBuffer[len], &id_len, sizeof(BYTE));
			len += sizeof(BYTE);
			//卡id
			if(id_len > 1){ 
				std::string str_card_id = "";
				str_card_id = pCard->card_id;
				string new_card_id = str_card_id.substr(3, pCard->card_id.length());
				int card_id = atoi(new_card_id.c_str());
				CFunctions::memcpyDWord(&SendBuffer[len],(DWORD)card_id, len);
			}else{
				memcpy(&SendBuffer[len], &pCard->card_id, id_len);
			}
			len += id_len;
			//校准类型
			BYTE bType = it_card->second->status;
			memcpy(&SendBuffer[len], &bType, sizeof(BYTE));
			len += sizeof(BYTE);
			switch (bType)
			{
			case CAL_DATA_ALL:
				//校准x坐标
				//float x = 4727.08;		//0x4593B8A3
				//CFunctions::memcpyFloat(&SendBuffer[len],x,sizeof(float));
				CFunctions::memcpyFloat(&SendBuffer[len],it_card->second->x,sizeof(float));
				len += sizeof(float);
				//校准y坐标
				//float y = 73.2;			//42926666
				//CFunctions::memcpyFloat(&SendBuffer[len],y,sizeof(float));
				CFunctions::memcpyFloat(&SendBuffer[len],it_card->second->y,sizeof(float));
				len += sizeof(float);
				//校准角度
				//float z = -312.5;		//C39C4000
				//CFunctions::memcpyFloat(&SendBuffer[len],z,sizeof(float));
				CFunctions::memcpyFloat(&SendBuffer[len],it_card->second->angle,sizeof(float));
				len += sizeof(float);
				break;
			case CAL_DATA_POS:
				//校准x坐标
				//float x = 4727.08;		//0x4593B8A3
				//CFunctions::memcpyFloat(&SendBuffer[len],x,sizeof(float));
				CFunctions::memcpyFloat(&SendBuffer[len],it_card->second->x,sizeof(float));
				len += sizeof(float);
				//校准y坐标
				//float y = 73.2;			//42926666
				//CFunctions::memcpyFloat(&SendBuffer[len],y,sizeof(float));
				CFunctions::memcpyFloat(&SendBuffer[len],it_card->second->y,sizeof(float));
				len += sizeof(float);
				break;
			case CAL_DATA_ANGLE:
				//校准角度
				//float z = -312.5;		//C39C4000
				//CFunctions::memcpyFloat(&SendBuffer[len],z,sizeof(float));
				CFunctions::memcpyFloat(&SendBuffer[len],it_card->second->angle,sizeof(float));
				len += sizeof(float);
				break;
			}
		}
		//找到此卡的最近接收分站，
		SocketMap::iterator it_sock = mp_socket_list.end();
		for (it_sock = mp_socket_list.begin();it_sock != mp_socket_list.end();++it_sock)
		{
			if (it_sock->second->reader_id == nReaderId)
			{
				break;
			}
		}

		//如果找到连接socket，则下发消息；如果未找到，则不发数据
		if (it_sock != mp_socket_list.end())
		{
			SendBuffer[0] = nTotals;
			SendData(it_sock->second->dwConnID, SEND_CHECK_INS_DATA, len, SendBuffer);
		}
	}

	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_LEVEL] = 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_level();
	init_map();
	init_area();
	init_special_area_entry();
	
	init_reader();
	init_dev_adhoc();
	init_antenna_sync();

	init_card();
	init_staffer();
	init_vehicle();
	init_adhoc();
	init_rules();//lemon 2017/08/01
	init_chamber();
	init_ctrl_reader();
	init_traffic_lights();
	init_section();
	init_light_group();

	//init_patrol_info();
	init_landmark();
	init_map_direction();
	init_cell_path_map();
	init_drivingface_warning_point();

	init_leader_arrange();
	init_att_area();
	init_drivingface_card();
	debug_print_syslog(0, "Base data init success.");
}

void CYAServerDlg::load_his_data()
{
	
	load_his_card_postion_vehicle(); // 标识卡所在位置
	load_his_card_postion_staff();
	load_his_card_state();
	deal_hist_card_postion();
	load_his_event_data(); // 分站状态
    load_drivingface_card_curshift_position();

}

void CYAServerDlg::load_his_area()
{
	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 = getMysqlRes(buf);

	if(NULL == pRes)
	{
		return;
	}
	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()
{
	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_extend 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_id=0;");

	pRes = getMysqlRes(buf);

	if(NULL == pRes)
	{
		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()
{
	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_extend 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_id=0;");

	pRes = getMysqlRes(buf);

	if(NULL == pRes)
	{
		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()
{
	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 = getMysqlRes(buf);
	if(NULL == pRes)
	{
		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]);

			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()
{
	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	
	int nRow = 0;
	DrivingfaceCardMap::iterator it = mp_driving_face_card_list.begin();
	for(;it!=mp_driving_face_card_list.end();it++)
	{
		sprintf_s(buf, "select * from his_drivingface_his where card_id = '%s' order by end_time desc limit 1;",it->first.c_str());
		pRes = getMysqlRes(buf);

		if(NULL == pRes)
		{
			return;
		}
		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]);
				nRow++;
			}
		}
	}
	CString strlog;
	strlog.Format(_T("%s%d%s"), _T(LOG_LOAD_HIS_DRVING_FACE_STATE), nRow, _T(LOG_RECORD_COUNT));
	show_log(strlog);
	


	/*
	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()
{
	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 = getMysqlRes(buf);

	if(NULL == pRes)
	{
		return ;
	}

	int nRow = 0;
	std::string enter_time;
	std::shared_ptr<DrivingfaceWarningPoint> pDrivingfaceWarningPoint = nullptr;
	std::vector<shared_ptr<DrivingfaceWarningPoint>> DrivingfaceWaringPointList;
	while(pRow = mysql_fetch_row(pRes)){
		int flag = 0;
		DrivingfaceWarningPointMapAll::iterator it = mp_drivingface_warning_point_list_all.find(atoi(pRow[2]));
		if(it != mp_drivingface_warning_point_list_all.end())
		{
			
			DrivingfaceWaringPointList = it->second;
			//pDrivingfaceWarningPoint = it->second;
			//查找vector是否存在该指针，如果存在则复制出来
			for(int i =0;i<DrivingfaceWaringPointList.size();i++)
			{
				if(DrivingfaceWaringPointList[i]->warning_point_id == atoi(pRow[0]))
				{
					flag = 1;
					pDrivingfaceWarningPoint = DrivingfaceWaringPointList[i];
				}
			}//如果不存在，vector插入该指针
			if(flag == 0)
			{
				pDrivingfaceWarningPoint = std::make_shared<DrivingfaceWarningPoint>();
				DrivingfaceWaringPointList.push_back(pDrivingfaceWarningPoint);
			}
		}else{
			pDrivingfaceWarningPoint = std::make_shared<DrivingfaceWarningPoint>();
			DrivingfaceWaringPointList.push_back(pDrivingfaceWarningPoint);
			//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]);
		if(flag == 0)
		{
			mp_drivingface_warning_point_list_all.insert(make_pair(atoi(pRow[2]),DrivingfaceWaringPointList));
		}
	}
	mysql_free_result(pRes);
}

float CYAServerDlg::get_drivingface_warning_point_dis(std::shared_ptr<Card> card)
{
    if(NULL == card)
    {
        return -1;
    }
	double distance = DBL_MAX;//the flag for most bigger...
	double warning_threshold = DBL_MAX;
	DrivingfaceCardMap::iterator it_card = mp_driving_face_card_list.find(card->card_id);
	if(it_card == mp_driving_face_card_list.end())
		return -1;
	int drivingfaceId = it_card->second->drivingface_id;
	DrivingfaceWarningPointMapAll::iterator it = mp_drivingface_warning_point_list_all.find(drivingfaceId);
    //DrivingfaceWarningPointMap::iterator it = mp_drivingface_warning_point_list.find(3305);
    if(it != mp_drivingface_warning_point_list_all.end())
    {
		vector<shared_ptr<DrivingfaceWarningPoint>> vDrivingfaceWarninglist = it->second;
		vector<shared_ptr<DrivingfaceWarningPoint>>::iterator vit = vDrivingfaceWarninglist.begin();
		for(;vit != vDrivingfaceWarninglist.end();vit++)
		{
			_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 = (*vit)->point_x;
			warning_point_position.y = (*vit)->point_y;
			warning_point_position.z = (*vit)->point_z;
			double tmpdistance = GetDistance(card_position, warning_point_position);

			tmpdistance = tmpdistance * card->map_scale;
			double lengthcardpoint  = sqrt(pow(card->x - it_card->second->x, 2)
				+ pow(card->y - it_card->second->y, 2)
				+ pow(card->z - it_card->second->z, 2)) * card->map_scale;
			double lengthwarningpoint = sqrt(pow((*vit)->point_x - it_card->second->x, 2)
				+ pow((*vit)->point_y - it_card->second->y, 2)
				+ pow((*vit)->point_z - it_card->second->z, 2)) * card->map_scale;
			if(lengthcardpoint < lengthwarningpoint)
			{
				if(tmpdistance < distance)
				{
					distance = tmpdistance;
					warning_threshold = (*vit)->warning_threshold;
					card->m_warning_point_id = (*vit)->warning_point_id;
				}
			}
			
		}
	}

	card->m_warning_threshold = warning_threshold;
	card->m_minDistanceToWarningpoint = distance;
	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 /*= ""*/ )
{
	char buf[LENGTH_SQL] = {0};

	if(card_id.length() == 0){
		sprintf_s(buf, "select card_id, card_type_id, state_id, ident from dat_card where state_id = 0;");
	}else{
		sprintf_s(buf, "select card_id, card_type_id, state_id, ident from dat_card where state_id = 0 and card_id='%s';", card_id.c_str());
	}

	MYSQL_RES* pRes = NULL;
	pRes = getMysqlRes(buf);

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

	MYSQL_ROW pRow;
	int err = 0;
	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);
			pCard->set_reader_path(mp_reader_path_list_tof, mp_reader_path_list_tdoa);
			mp_card_list_all.insert(make_pair(pCard->card_id, pCard));
			nRow++;

			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;
}
//lemon 2017/08/08
void CYAServerDlg::card_up_mine(std::shared_ptr<Card> card /*Card* card*/)
{
	//if(CT_VEHICLE == card->card_type)
	//{
	//	time_t att_end_time = CFunctions::systime_to_timet(card->deal_time);
	//	if(card->att_start_time_latest > card->down_time)
	//	{
	//		// lihongzhen  2017/8/19 只在考勤区域内的记录,重置att_start_time_latest,不做升井
	//		return ;
	//	}
	//	else 
	//	{
	//		// 从非考勤区域进入考勤区域时间小于入井时间，并且升井时间小于考勤开始时间，需要升井处理
	//		if(difftime(att_end_time, card->att_end_time_latest) > sls_setting.att_endtime_offset_vehicle)
	//		{
	//			card->up_time = card->att_end_time_latest + sls_setting.att_endtime_offset_vehicle;
	//		}
	//		else{
	//			card->up_time = att_end_time;
	//		}
	//	}
	//}
	//else
	{
		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++ )
	{
		if (i == EVENT_TYPE::ET_CARD_LOW_POWER_SERIOUS)
		{
			continue;
		}
		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())
			{
				//如果是卡报警这里统一处理
				if (it_ev->second->obj_type == OT_CARD)
				{
					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;
			}
		}
	}
	if(CT_PERSON == card->card_type)
	{
		clear_card_from_list(card);
	}
}

void CYAServerDlg::card_down_mine(std::shared_ptr<Card> card /*Card* card*/ )
{
	// lihongzhen  2017/8/18 使用首次接收到信号的时间作为入井时间
	//int offset_start_time = sls_setting.att_starttime_offset_vehicle;
	//time_t deal_time = CFunctions::systime_to_timet(card->deal_time);
	//if(CT_PERSON == card->card_type)
	//{
	//	offset_start_time = sls_setting.att_starttime_offset_staff;
	//}
	//if(difftime(deal_time, card->att_start_time_latest) > offset_start_time)
	//{
	//	card->down_time = deal_time - offset_start_time; 
	//}
	//else
	//{
	//	card->down_time = card->att_start_time_latest;
	//}

	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 && sls_setting.over_count_person != 0){

				string s;
				for (it_card = mp_card_list_down_person.begin();it_card != mp_card_list_down_person.end();it_card++)
				{
					s += it_card->second->card_id;
					s += "&";
				}
				debug_print_syslog(0,"[lemon mp_card_list_down_person:]:%s",s.c_str());

				et = ET_OVER_COUNT_PERSON;
				limit_val = sls_setting.over_count_person;
				cur_val = mp_card_list_down_person.size();
				//deal_alarm_card(card,mp_card_list_over_count_person,true,AF_CARD_OVER_COUNT);
			}
		}

	}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 && sls_setting.over_count_vehicle != 0){
				et = ET_OVER_COUNT_VEHICLE;
				limit_val = sls_setting.over_count_vehicle;
				cur_val = mp_card_list_down_vehicle.size();
				//deal_alarm_card(card,mp_card_list_over_count_vehicle,true,AF_CARD_OVER_COUNT);
			}
		}	
	}

	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->cur_value= cur_val;
			ev->limit_value = limit_val;
			ev->obj_id = "0";
			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());

		CONNID 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){
	}
}

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->level_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_event_data()
{
	
	MYSQL_RES* pRes;
	MYSQL_ROW pRow;
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "SELECT event_id,event_type_id,obj_type_id,obj_id,map_id,area_id,limit_value,cur_value,X,Y,cur_time FROM his_event_data \
				   WHERE event_id IN (SELECT MAX(event_id) FROM his_event_data \
				   WHERE cur_time > (CASE obj_type_id \
				   WHEN 1 THEN DATE_SUB(NOW(),INTERVAL 2 DAY) \
				   WHEN 2 THEN DATE_SUB(NOW(),INTERVAL 2 DAY)\
				   WHEN 4 THEN DATE_SUB(NOW(),INTERVAL 1 MONTH)\
				   WHEN 9 THEN DATE_SUB(NOW(),INTERVAL 2 DAY) \
				   WHEN 10 THEN DATE_SUB(NOW(),INTERVAL 2 DAY) \
				   END) \
				   AND cur_time < NOW()\
				   GROUP BY event_type_id, obj_id) \
				   AND  event_id NOT IN ( SELECT event_id FROM (SELECT * FROM his_event_data WHERE  stat=100) s);");

	pRes = getMysqlRes(buf);
	if(NULL == pRes)
	{
		return ;
	}
	int nRow = 0;
	INT64 ev_id = 0;
	double cur_value = 0;
	double limit_value = 0;
	double x,y=0;
	int obj_type_id ,event_type_id ,map_id , area_id = 0;
	EVENT_TYPE et;
	std::string rec_time, lost_time,obj_id;
	//event_id 0,event_type_id 1,obj_type_id  2,obj_id 3,map_id 4,area_id 5,limit_value 6,cur_value 7,X 8,Y 9,cur_time 10       
	while(pRow = mysql_fetch_row(pRes))
	{
		ev_id = _atoi64(pRow[0]);
		event_type_id = atoi(pRow[1]);
		obj_type_id = atoi(pRow[2]);
		obj_id = pRow[3];
		map_id = atoi(pRow[4]);
		area_id = atoi(pRow[5]);
		limit_value = atof(pRow[6]);
		cur_value = atof(pRow[7]);
		x = atof(pRow[8]);
		y = atof(pRow[9]);
		lost_time = pRow[10];
		rec_time = pRow[10];
		switch (obj_type_id)
		{
		case OT_MINE:
			{
				std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
				ev->status = ES_START;	
				et =  EVENT_TYPE(event_type_id);
				ev->ev_type = et;
				ev->obj_type = OT_MINE;
				API_StringToTime(lost_time, ev->cur_time);
				//ev->cur_time = time(NULL);
				ev->cur_value= cur_value;
				ev->limit_value = limit_value;
				ev->obj_id = obj_id;
				ev->is_sent = false;

				ev->map_id = map_id;
				ev->area_id = area_id;
				m_event_list[et] = ev_id;
				add_event(ev);
				break;
			}
		case  OT_AREA:
			{
				AreaMap::iterator it_Area = mp_area_list.find(area_id);
				if(it_Area != mp_area_list.end())
				{
					it_Area->second->count_area_over_count_person = cur_value - limit_value;
					API_StringToTime(lost_time,it_Area->second->time_over_count_person);

					std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
					ev->status = ES_START;
					API_StringToTime(lost_time, ev->cur_time);
					switch (event_type_id)
					{
					case ET_AREA_OVER_COUNT_VEHICLE:
						it_Area->second->is_area_over_count_vehicle = true;
						break;
					case ET_AREA_OVER_COUNT_PERSON:
						it_Area->second->is_area_over_count_person = true;
						break;
					default:
						break;
					}
					et = EVENT_TYPE(event_type_id);
					ev->ev_type = et;
					ev->obj_type = OT_AREA;
					ev->obj_id = CFunctions::int2string(atoi(obj_id.c_str()));
					ev->map_id = map_id;
					ev->area_id = area_id;
					ev->limit_value = limit_value;
					ev->cur_value = cur_value;
					ev->is_sent = false;

					it_Area->second->m_event_list[et] = ev_id;
					add_event(ev);
				}
				break;
			}
		case OT_DEVICE_READER:
			{
				ReaderMap::iterator it = mp_reader_list.find(atoi(pRow[3]));
				if(it != mp_reader_list.end())
				{
					std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
					ev->status = ES_START;
					et = EVENT_TYPE(event_type_id);
					ev->ev_type = et;
					ev->obj_type = OT_DEVICE_READER;
					
					ev->obj_id = CFunctions::int2string(atoi(obj_id.c_str()));
					API_StringToTime(lost_time, ev->cur_time);

					ev->map_id = map_id;
					ev->area_id = area_id;
					ev->x = x;
					ev->y = y;

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

					API_StringToTime(rec_time, it->second->rec_time);
					API_StringToTime(lost_time, it->second->lost_time);
					it->second->reader_state = STATUS_DEVICE_ERROR;
					it->second->m_event_list[et] = ev_id;
					add_event(ev);
				}
				break;
			}
		case  OT_CARD:
			{
				CardMap::iterator it_card = mp_card_list_all.find(obj_id);
				et = EVENT_TYPE(event_type_id);
				if (it_card != mp_card_list_all.end())
				{
					std::shared_ptr<Card> card = it_card->second;
					switch (et)
					{
					case ET_UNKNOWN:
						break;
					case ET_OVER_COUNT_PERSON:
						break;
					case ET_OVER_COUNT_VEHICLE:
						break;
					case ET_AREA_OVER_COUNT_PERSON:
						break;
					case ET_AREA_OVER_COUNT_VEHICLE:
						break;
					case ET_SECTION_OVER_COUNT:
						break;
					case ET_READER_ERROR:
						break;
					case ET_ctrl_reader_ERROR:
						break;
					case ET_LIGHT_ERROR:
						break;
					case ET_READER_CALL:
						break;
					case ET_READER_CALL_CANCEL:
						break;
					case ET_CARD_LOW_POWER:
						break;
					case ET_CARD_LOW_POWER_SERIOUS:
						break;
					case ET_CARD_OVER_TIME_PERSON:
						card->is_mine_over_time = true;
						API_StringToTime(lost_time,it_card->second->time_over_time);
						card->status_over_time = 1;
						mp_card_list_over_time_person->insert(make_pair(obj_id,card));
						break;
					case ET_CARD_OVER_TIME_VEHICLE:
						card->is_mine_over_time = true;
						API_StringToTime(lost_time,it_card->second->time_over_time);
						card->status_over_time = 1;
						mp_card_list_over_time_vehicle->insert(make_pair(obj_id,card));
						break;
					case ET_CARD_AREA_OVER_TIME_PERSON:
						API_StringToTime(lost_time,card->time_area_over_time);
						card->status_area_over_time = 1;
						card->is_area_over_time = true;
						mp_card_list_area_over_time_person->insert(make_pair(obj_id,card));
						break;
					case ET_CARD_AREA_OVER_TIME_VEHICLE:
						API_StringToTime(lost_time,card->time_area_over_time);
						card->status_area_over_time = 1;
						card->is_area_over_time = true;
						mp_card_list_area_over_time_vehicle->insert(make_pair(obj_id,card));
						break;
					case ET_CARD_AREA_LIMIT_PERSON:
						break;
					case ET_CARD_AREA_LIMIT_VEHICLE:
						break;
					case ET_CARD_AREA_FORBIDDEN_PERSON:
						card->time_area_forbidden = true;
						card->status_area_forbidden = 1;
						mp_card_list_forbidden_person->insert(make_pair(obj_id,card));
						break;
					case ET_CARD_AREA_FORBIDDEN_VEHICLE:
						card->time_area_forbidden = true;
						card->status_area_forbidden = 1;
						mp_card_list_forbidden_vehicle->insert(make_pair(obj_id,card));
						break;
					case ET_CARD_OVER_SPEED:
						break;
					case ET_CARD_AREA_OVER_SPEED:
						{
							card->is_area_over_speed = true;
							API_StringToTime(lost_time,card->time_area_over_speed );
							card->status_area_over_speed = 1;
							AreaMap::iterator it_area = mp_area_list.find(area_id);
							if (it_area != mp_area_list.end())
							{
								it_area->second->area_card_list_over_speed->insert(make_pair(obj_id,card));
							}
							
						}
						break;
					case ET_CARD_RUN_THE_RED_LIGHT:
						break;
					case ET_CARD_HELP:
						break;
					case ET_CARD_CALLED:
						break;
					case ET_CARD_PATROL_ERROR:
						break;
					case ET_CARD_LOST:
						break;
					case ET_CARD_DRIVINGFACE_WARNING_AREA:
						break;
					case ET_CARD_NEAR_DRIVINGFACE_VEHICLE:
						break;
					case ET_CARD_NEAR_DRIVINGFACE_OVERCOUNT:
						break;
					case CARD_EVENT_COUNT_MAX:
						break;
					default:
						break;
					}
	
					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 = obj_id;

					API_StringToTime(lost_time,ev->cur_time);
					ev->cur_value = cur_value;
					ev->limit_value = limit_value;

					ev->map_id = map_id;
					ev->area_id = area_id;
					ev->x = x;
					ev->y = y;

					ev->is_sent = false;
					card->m_event_list[et] = ev_id;
					add_event(ev);
				}
				break;
			}
		case OT_DRIVINGFACE_AREA:
			{
				string card_id;
				card_id.clear();
				et = EVENT_TYPE(event_type_id);
				DrivingfaceCardMap::iterator it_df = mp_driving_face_card_list.begin();
				for (;it_df != mp_driving_face_card_list.end();it_df++)
				{
					if (atoi(pRow[3]) == it_df->second->drivingface_id)
					{
						card_id = it_df->first;
						break;
					}
				}
				if (card_id.empty())
				{
					break;
				}
				CardMap::iterator it_card = mp_card_list_all.find(card_id);
				if (it_card != mp_card_list_all.end())
				{
					switch (et)
					{
					case ET_CARD_DRIVINGFACE_WARNING_AREA:
						it_card->second->m_isWarning = true;
						mp_card_warning_point_alarm->insert(make_pair(card_id,it_card->second));
						break;
					case ET_CARD_NEAR_DRIVINGFACE_VEHICLE:
						break;
					case ET_CARD_NEAR_DRIVINGFACE_OVERCOUNT:
						it_card->second->m_CardHasBeenInDrivingfaceAlarm = true;
						break;
					default:
						break;
					}

					std::shared_ptr<YaEvent> ev = std::make_shared<YaEvent>(ev_id);
					ev->status = ES_START;	
					ev->ev_type = et;

					ev->obj_type = OT_DRIVINGFACE_AREA;
					ev->obj_id = CFunctions::int2string(atoi(obj_id.c_str()));

					API_StringToTime(lost_time,ev->cur_time);
					ev->cur_value = cur_value;
					ev->limit_value = limit_value;

					ev->map_id = map_id;
					ev->area_id = area_id;
					ev->x = x;
					ev->y = y;

					ev->is_sent = false;
					it_card->second->m_event_list[et] = ev_id;
					add_event(ev);
				}
				break;
			}
		default:
			break;
		}
		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);
}
/************************************************************************/
/*    查看是否有权限，工种权限
		如果没有则
			1,查看掘进机是否启动中
				2.判断其eare_id是否相同且和掘进机的area_id相同。   
				lemon 2017/07/31*/
/*distance = GetDistance(card_point, landmark_point) *card->map_scale;
/*_point card_point(card->x, card->y, card->z);
/************************************************************************/
void CYAServerDlg::deal_card_drivingface_permission(std::shared_ptr<Card> card)
{
	WorkTypePermissionMap::iterator it_worktype = mp_worktype_permission_list.find(card->vehice_type_id);
	//查看是否在权限工种内
	if (it_worktype == mp_worktype_permission_list.end())
	{
		DrivingfaceCardMap::iterator it_drivingfaceId ;
		//查看是否是掘进机设备
		it_drivingfaceId = mp_driving_face_card_list.find(card->card_id);
		if (it_drivingfaceId != mp_driving_face_card_list.end())
		{
			return ;
		}
		for (it_drivingfaceId = mp_driving_face_card_list.begin();it_drivingfaceId != mp_driving_face_card_list.end();++it_drivingfaceId)
		{
			CardMap::iterator it_card = mp_card_list_all.find(it_drivingfaceId->first);
			if (it_card != mp_card_list_all.end())
			{
				//如果卡进入到了掘进机区域
				if (it_card->second->area_id == card->area_id)
				{
					_point p_drivingface_card(it_card->second->x,it_card->second->y,it_card->second->z);
					_point p_card (card->x,card->y,card->z);
					double dis = GetDistance(p_drivingface_card,p_card)*(it_card->second->map_scale);
					card->setDrivingfaceCulValue(dis);
					card->setDrivingfaceLimitValue(it_drivingfaceId->second->warning_threshold);

					if (dis < it_drivingfaceId->second->warning_threshold)
					{
						if (it_card->second->is_driving_face_start)
						{
							if (!card->m_CardHasBeenInDrivingfaceAlarm)
							{
								card->m_DrivingfaceAlarmFlag = it_drivingfaceId->second->drivingface_id;
								deal_alarm_card(card,mp_card_drivingface_eara_alarm,true,AF_CARD_NEAR_DRRIVINGFACE_VEHICLE);
							}
						}
						else
						{
							if (card->m_CardHasBeenInDrivingfaceAlarm)
							{
								card->m_DrivingfaceAlarmFlag = -1;
								deal_alarm_card(card,mp_card_drivingface_eara_alarm,false,AF_CARD_NEAR_DRRIVINGFACE_VEHICLE);
							}
						}
					}
					else
					{
						//首先判断是否是刚从限制距离出来。
						if (card->m_DrivingfaceAlarmFlag == it_drivingfaceId->second->drivingface_id && card->m_CardHasBeenInDrivingfaceAlarm )
						{
							card->m_DrivingfaceAlarmFlag = -1;
							deal_alarm_card(card,mp_card_drivingface_eara_alarm,false,AF_CARD_NEAR_DRRIVINGFACE_VEHICLE);
						}
					}
					break;		
				}
				else
				{
					//对于不在同一区域的情况下，比如掘进机离区域边界很近的情况  处理。。。
				}
				
			}
			else
			{
				return ;
			}
		}
	}

}

void CYAServerDlg::deal_card_drivingface_permission(std::shared_ptr<Card> card,int id)
{
	EVENT_TYPE et = ET_UNKNOWN;
	int limit_val = 0, cur_val = 0;
	
	DrivingfaceCardMap::iterator it_drivingfaceId ;
	//查看是否是掘进机设备
	it_drivingfaceId = mp_driving_face_card_list.find(card->card_id);
	if (it_drivingfaceId != mp_driving_face_card_list.end())
	{
		return ;
	}
	for (it_drivingfaceId = mp_driving_face_card_list.begin();it_drivingfaceId != mp_driving_face_card_list.end();++it_drivingfaceId)
	{
		CardMap::iterator it_card = mp_card_list_all.find(it_drivingfaceId->first);
		if (it_card != mp_card_list_all.end())
		{
			//如果卡进入到了掘进机区域
			if (it_card->second->area_id == card->area_id)
			{
				_point p_drivingface_card(it_card->second->x,it_card->second->y,it_card->second->z);
				_point p_card (card->x,card->y,card->z);
				double dis = GetDistance(p_drivingface_card,p_card)*(it_card->second->map_scale);
				card->setDrivingfaceCulValue(dis);
				card->setDrivingfaceLimitValue(it_drivingfaceId->second->warning_threshold);
				//limit_val 人员超员阈值。
				limit_val = it_drivingfaceId->second->m_overcount;

				if (dis < it_drivingfaceId->second->warning_threshold)
				{
					if (it_card->second->is_driving_face_start)
					{
						it_card->second->mp_list_over_count.insert(make_pair(card->card_id,card));

						int cv = it_card->second->mp_list_over_count.size();
						char buf[LENGTH_SQL] = { 0 };
						sprintf_s(buf,LENGTH_SQL,"[deal_card_drivingface_permission]drivingface_id:%s,card_id:%s,dis:%.3f,warning_threshold:%.3f,limit_val:%d,cur_value:%d --insert",
							it_drivingfaceId->first.c_str(),
							card->card_id.c_str(),
							dis,
							it_drivingfaceId->second->warning_threshold,
							limit_val,
							cv);
						Log::write_log(SYS_S,buf,true);
						//如果
						if (!it_card->second->m_CardHasBeenInDrivingfaceAlarm && cv >= limit_val) //later modify 
						{
							et = ET_CARD_NEAR_DRIVINGFACE_OVERCOUNT;
							cur_val = cv;
							it_card->second->m_CardHasBeenInDrivingfaceAlarm = true;
						}
						else if(it_card->second->m_CardHasBeenInDrivingfaceAlarm && cv < limit_val)
						{
							it_card->second->m_CardHasBeenInDrivingfaceAlarm = false;
							et = ET_CARD_NEAR_DRIVINGFACE_OVERCOUNT;
							cur_val = cv;
						}
					}
					else
					{
						it_card->second->mp_list_over_count.clear();
						if (it_card->second->m_CardHasBeenInDrivingfaceAlarm)
						{
							et = ET_CARD_NEAR_DRIVINGFACE_OVERCOUNT;
							cur_val = 0;
							it_card->second->m_CardHasBeenInDrivingfaceAlarm = false;
						}
					}
				}
				else
				{
					CardMap::iterator it_overcount = it_card->second->mp_list_over_count.find(card->card_id);
					if (it_overcount != it_card->second->mp_list_over_count.end())
					{
						it_card->second->mp_list_over_count.erase(it_overcount);
					}
					int cv = it_card->second->mp_list_over_count.size();
					if (it_card->second->m_CardHasBeenInDrivingfaceAlarm && cv < limit_val)
					{
						it_card->second->m_CardHasBeenInDrivingfaceAlarm = false;
						et = ET_CARD_NEAR_DRIVINGFACE_OVERCOUNT;
						cur_val = cv;
					}
				}
				
				//do it

				if (ET_UNKNOWN != et)
				{
					INT64 ev_id = it_card->second->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 = 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;
							if(it_card->second->m_CardHasBeenInDrivingfaceAlarm)
							{
								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);

								it_card->second->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_DRIVINGFACE_AREA;
						ev->obj_id = CFunctions::int2string(it_drivingfaceId->second->drivingface_id);
						ev->cur_time = time(NULL);
						ev->cur_value = cur_val;
						ev->limit_value = limit_val;

						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] = ev_id;

						store_data_event(ev);
						add_event(ev);

					}
				}
				break;

			}
			else
			{
				//对于不在同一区域的情况下，比如掘进机离区域边界很近的情况  处理。。。
			}

		}
		else
		{
			return ;
		}
	}
}

void CYAServerDlg::deal_card_state(std::shared_ptr<Card> card /*Card* card */)
{
	card->get_state_text();

	// 电量
	EVENT_TYPE et = ET_UNKNOWN;
	double limit_val = 0, cur_val = 0;
	bool is_alarm = false;

	if(card->power_state <2  && card->power_state_last >=2 ){
		card->status_power = STATUS_NORMAL;

		et = ET_CARD_LOW_POWER_SERIOUS;
		limit_val = 0.2;
		cur_val = 1;
	}	
	//如果低电量告警出现多条，说明创建了多条记录（1.并行执行此函数 2.重启采集系统服务器）
	if(card->power_state_last <  2 && card->power_state >= 2 ){
		card->low_power_time = CFunctions::systime_to_timet(card->deal_time);

		et = ET_CARD_LOW_POWER_SERIOUS;
		limit_val = 0.2;
		cur_val = 0.2;
		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_offset_after();
				it_ev->second->y = card->y_offset_after();
				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_offset_after();
				ev->y = card->y_offset_after();
				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_offset_after();
				it_ev->second->y = card->y_offset_after();
				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_offset_after();
				ev->y = card->y_offset_after();
				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);
			}
		}
	}
}
//lemon 2017/08/02
void CYAServerDlg::load_his_card_state()
{
	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 = getMysqlRes(buf);
	if(NULL == pRes)
	{
		return;
	}
	int nRow = 0;
	std::string start_time;
	string card_id = "";
	CardMap::iterator it;
	while(pRow = mysql_fetch_row(pRes)){
		if (card_id != pRow[0])
		{
			card_id = pRow[0];
			it = mp_card_list_all.find(pRow[0]);
			if(it != mp_card_list_all.end()){
				(it->second->m_event_list)[atoi(pRow[1])] = atoi(pRow[2]);
			}
			nRow++;
		}
		else
		{
			(it->second->m_event_list)[atoi(pRow[1])] = atoi(pRow[2]);
			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 )
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_269);
	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 )
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_270);
	::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( CONNID 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);

		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, CFunctions::TOF);
				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:
			{				
				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 = "";

	//存储数据到数据库中
	DWORD 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_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::TestReadFile()
{
	ifstream in;
	in.open("D:/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, theApp.z_offset);
	card->SetCellPathMap(mpCellPath);
	card->set_reader_path(mp_reader_path_list_tof, mp_reader_path_list_tdoa);
	card->m_nFilterType = FILTER_KALMAN;
	card->EnableFilter(FILTER_KALMAN);
	card->map_scale = dMapScale;
	card->ranging_type = LOCATEDATATYPE::LDT_TDOA;
	card->accelerate_state = 1;
	card->card_type = CT_VEHICLE;

	while (!in.eof())
	{
		in.getline(pch,200);
		string data = pch;
		stringstream sout;

		std::vector<std::string> metaDatas = CFunctions::split(data,",",true);
		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->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);

			//memset(chlog, 0, MAX_LOG_LENGTH);
			//sprintf_s(chlog, "sn:%d, ox: %f, oy: %f, x: %f, y: %f, z: %f, iw: %f, uw: %f, as: %d, asl: %d, ct: %d, ov: %f, cv: %f, av: %f, lsn: %d, cardid: %s, rx: %.4f, ry:%.4f", 
			//	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(),
			//	card->x_offset_after(), card->y_offset_after()
			//	);
			//strlog = chlog;
			//Log::write_log(FILE_TYPE::KALMAN_S,strlog,true);

			card->last_x = card->x;
			card->last_y = card->y;
			card->last_z = card->z;
		}
	}
	in.close();

	while(card->_dists.size() > 0)
	{
		card->get_coordinate();
		card->remove_dist_head();
		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;
		}
	}
}

int CYAServerDlg::ReadTofDistFile()
{
	//ifstream in;
	//in.open("D:/6.log");

	//if (!in.is_open())
	//{
	//	return 1;
	//}

	//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, theApp.z_offset);
	//card->set_reader_path(mp_reader_path_list_tof, mp_reader_path_list_tdoa);

	//card->m_nFilterType = FILTER_KALMAN;
	//card->EnableFilter(FILTER_KALMAN);
	//card->map_scale = dMapScale;

	//card->ranging_type = LOCATEDATATYPE::LDT_TOF;

	//while (!in.eof())
	//{
	//	in.getline(pch,200);
	//	string data = pch;
	//	stringstream sout;

	//	std::vector<std::string> metaDatas = CFunctions::split(data,",",true);
	//	std::shared_ptr<_coordinate> dist = std::make_shared<_coordinate>();
	//	std::string card_id = "";
	//	for (int i = 0;i < metaDatas.size();i++)
	//	{	
	//		std::string meta = metaDatas[i];

	//		std::vector<std::string> vtMeta = CFunctions::split(meta,":",true);
	//		switch(i){
	//		case 0:
	//			dist->reader_id = atoi(vtMeta[1].c_str());
	//			break;
	//		case 1:
	//			dist->antenna_id = atoi(vtMeta[1].c_str());
	//			break;
	//		case 2:
	//			dist->t = atoi(vtMeta[1].c_str());
	//			break;
	//		case 3:
	//			dist->d = atof(vtMeta[1].c_str());
	//			break;
	//		case 4:
	//			dist->x = atof(vtMeta[1].c_str());
	//		case 5:
	//			dist->y = atof(vtMeta[1].c_str());
	//			break;
	//		case 6:
	//			dist->z = atof(vtMeta[1].c_str());
	//			break;
	//		case 7:
	//			//card_id = vtMeta[1];
	//			break;
	//		case 8:
	//			card_id = vtMeta[1];
	//			break;
	//		}
	//	}
	//	card->time_stamp_cal = dist->t;
	//	card->card_id = card_id;
	//	card->rec_time = time(NULL);
	//	card->add_dist(dist);
	//}
	//in.close();

	ifstream in;
	in.open("D:/new_6.log");

	if (!in.is_open())
	{
		return 1;
	}

	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, theApp.z_offset);
	card->set_reader_path(mp_reader_path_list_tof, mp_reader_path_list_tdoa);
	card->m_nFilterType = FILTER_KALMAN;
	card->EnableFilter(FILTER_KALMAN);
	card->map_scale = dMapScale;
	card->ranging_type = LOCATEDATATYPE::LDT_TOF;

	while (!in.eof())
	{
		in.getline(pch,200);
		string data = pch;
		stringstream sout;

		std::vector<std::string> metaDatas = CFunctions::split(data,",",true);
		std::shared_ptr<_coordinate> dist = std::make_shared<_coordinate>();
		std::string card_id = "";
		for (int i = 0;i < metaDatas.size();i++)
		{	
			std::string meta = metaDatas[i];

			std::vector<std::string> vtMeta;
			if(i>0){
				vtMeta = CFunctions::split(meta,":",true);
			}
			switch(i){
			case 0:
				//card->rec_time = CFunctions::string2time_t(meta);
				dist->cur_time =  CFunctions::string2time_t(meta);
				break;
			case 1:
				break;
			case 2:
				dist->reader_id = atoi(vtMeta[1].c_str());
				break;
			case 3:
				dist->antenna_id = atoi(vtMeta[1].c_str());
				break;
			case 4:
				dist->t = atoi(vtMeta[1].c_str());
				break;
			case 5:
				dist->d = atof(vtMeta[1].c_str());
				break;
			case 6:
				dist->x = atof(vtMeta[1].c_str());
			case 7:
				dist->y = atof(vtMeta[1].c_str());
				break;
			case 8:
				dist->z = atof(vtMeta[1].c_str());
				break;
			case 9:
				//card_id = vtMeta[1];
				break;
			case 10:
				card_id = vtMeta[1];
				break;
			}
		}
		card->time_stamp_cal = dist->t;
		card->card_id = card_id;
		card->add_dist(dist);
	}
	in.close();

	return 0;
}

/*
* 生成当用户登陆时，返回给前端所有的模拟数据
*
* param
*		无
*
* return
*		0正常，非0失败
*
*/
int CYAServerDlg::TestGenerateAllDataJson()
{
	//所有卡的坐标以及特殊区域升井

	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);
	}

	return 0;
}

<<<<<<< HEAD
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;
}

/*
* 功能：在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->deal_time;
		//检查处理时间的有效性
		if (!CFunctions::CheckSystemTimeValid(lastTime))
		{
			continue;
		}

		SYSTEMTIME curTime;
		::GetLocalTime(&curTime);

		//加500ms
		//it->second->ChangeSystemTime(lastTime);
		//加1s
		it->second->ChangeSystemTimeBySecond(lastTime);
		int ret = CFunctions::CompareSystemTime(curTime,lastTime);
		if (ret <= 0)
		{
			continue;
		}

		::GetLocalTime(&it->second->last_cell->deal_time);

		int nStep = it->second->last_cell->nStep*2/3;
		/*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;

		//根据两次处理时间来决定前进格数
		cell->dataSource = 2;
		it->second->curCellId = cell->id;
		it->second->originCellId = 0;
		it->second->originCellReaderName = "";

		if(cell->id == 0) 
		{
			continue; //cellid如果为0,那么此卡放弃push进格子列表，continue下一个card
		}
		it->second->origin_locate.x = it->second->origin_locate.y = 0;

		cell->interval_time = it->second->last_cell->interval_time;
		it->second->ChangeSystemTime(cell->interval_time);
		if (cell)
		{
			*(it->second->last_cell) = *cell;
		}
		it->second->x = it->second->last_cell->getX()/it->second->map_scale;
		it->second->y = it->second->last_cell->getY()/it->second->map_scale;
		it->second->locate_cells.push_back(it->second->last_cell);

		nCounts++;

		if (it->second->curCellReaderName == "" && it->second->originCellReaderName == "")
		{
			continue;
		}
		
		/*std::string flag1 = it->second->is_fit_pos?"Y":"N";
		int nSource1 = 2;	
		char chLog1[300] = {0};
		sprintf_s(chLog1,"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",
			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,
			it->second->curCellReaderName.c_str(),
			it->second->curCellId,
			it->second->originCellId,
			it->second->originCellReaderName.c_str(),
			it->second->origin_locate.v,
			it->second->get_speed(),
			flag1.c_str(),
			nSource1);*/

		//std::string strLog1 = "";
		//strLog1 = chLog1;
		//Log::write_log(FILE_TYPE::KALMAN_S,strLog1,true);

		it->second->locateCounts++;
	}

	return nCounts;
}

void CYAServerDlg::parse_data_server( const BYTE * pData, int nLen, DWORD dwConnId )
=======
void CYAServerDlg::parse_data_server( const BYTE * pData, int nLen, CONNID dwConnId )
>>>>>>> newprotocal
{
	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);
					}

					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*/ )
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_109);
	if(!card->is_registered)
	{
		debug_print_syslog(0, "card not registered: %s", card->card_id.c_str());
		return ;
	}

	DWORD dw;
	if(!is_hist){
		cal_card_position_by_msg(card);
	}

	//处理惯导数据校准,将所有卡的校准数据按分站归类
	//get_ins_cal_list();
	////下发校准数据
	//send_ins_data(card);

	::GetLocalTime(&card->deal_time);
	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 ;
		}
	}

	// 掘进机
	DrivingfaceCardMap::iterator it_driving = mp_driving_face_card_list.find(card->card_id);
	if(it_driving != mp_driving_face_card_list.end())
	{
		if(m_log_raw_data)
		{
			save_raw_data_card_tof(card);
		}

		deal_card_drivingface_real(card);
		return ;
	}


	if(CFunctions::TOF == card->ranging_type)
	{
		debug_print_syslog(0, "tof location: %s, %d, %.4f, %.4f, %d, %d",
			card->card_id.c_str(), card->time_stamp, card->x, card->y,
			card->b_pos_change ? 1 : 0, card->p_reader->pos_state);
	}

	//判断井下和区域是否超时
	if(card->b_pos_change || PDT_UP == card->p_reader->pos_state) // 坐标不变化，不走业务
	{ 
		save_card_postion(card);
		card_enter_map(card); // 切换地图
		card_enter_area(card);//
		card_enter_mine(card);
		deal_card_state(card);
		//查看是否进入掘进机警戒区
		//这里话是不是要考虑用户配置展示数据的功能
		//lemon 2017/07/31
		deal_card_drivingface_permission(card,true);
		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)
{
	CONNID dwConnID = (CONNID)lParam;
	remove_socket(dwConnID);
	return 0;
}

void CYAServerDlg::init_queuestring()
{
	m_qsmSQL = new QueueStrManager(SQL_EXECUTE_SENTENCE_COUNT_MAX,
		SQL_SENTENCE_LENGTH_MAX, _exec_sql);//50,7500
}

BOOL CYAServerDlg::SendData( CONNID 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);

	BOOL ret = _server.Send(dwConnID, &SendBuffer[0], nPos);

	Sleep(5);
	debug_print_syslog(0, "send_call_info: %d, %.2X, %d", dwConnID, wCharacterWord, wLength);
	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;
	}
}

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, CFunctions::TOF);

			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));
			break;
		}
	default:
		{
			break;
		}						
	}

	if (b_exec)
	{
		execute_sql(sql);
	}
}

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:
	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;

			//保留
			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;
		}
	default:
		{
			break;
		}						
	}

	if (b_exec)
	{
		execute_sql(sql);
	}
}

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);

	execute_sql(sql);
}

void CYAServerDlg::OnEnUpdateEditReaderid()
{
	// TODO:  在此添加控件通知处理程序代码
	UpdateData(TRUE);
}

void CYAServerDlg::parse_json_data_call_card_cancel(message::ptr const& data )
{
	CString strlog;
	string user_name;
	string cardid, readerid;
	int call_time_out, reader_count, card_count, call_type_id;
    int64_t call_time;

	map<string,message::ptr> data_map = data->get_map()[JSON_ROOT_KEY_DATA]->get_map();
	// 呼叫类型，0全员，1定员
	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_int();

	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())
	{
		return ;
	}
	EnterCriticalSection(&m_csCallInfo);

	// 取消全员呼叫
	if(CALL_CARD_TYPE::CCT_CALL_ALL == call_type_id)
	{
		// 删除该用户所有呼叫信息
		clear_call_card_by_user(user_name);
	}
	// 取消定员呼叫
	else
	{
		// 遍历删除指定呼叫信息
		vector<message::ptr>::const_iterator it_card = card_vec.begin();
		BYTE card_type = 0;
		CallInfoCardMap::iterator it_call_card;
		for(; it_card != card_vec.end(); ++it_card){
			string 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();

			CallInfoReaderMap::iterator it_reader = it_call_user->second->mpReader.begin();
			for(; it_reader != it_call_user->second->mpReader.end();)
			{
				// 删除分站内的卡
				it_call_card = it_reader->second->mpCard.find(s_card_id);
				if(it_call_card != it_reader->second->mpCard.end())
				{
					it_reader->second->mpCard.erase(it_call_card);
				}

				if(it_reader->second->mpCard.size() > 0)
				{
					++it_reader;
				}
				else
				{
					// 如果分站中卡为空，删除分站
					it_reader = it_call_user->second->mpReader.erase(it_reader);
				}
			}
		}
	}

	// 没有呼叫信息，删除该用户记录
	if(0 == it_call_user->second->mpReader.size())
	{
		mp_user_call_info.erase(it_call_user);
	}

	LeaveCriticalSection(&m_csCallInfo);
	//取消呼叫
	Json::Value root;
	Json::Value resp_data;
	Json::Value callinfo;
	Json::Value stations;
	Json::Value cards;

	callinfo[JSON_KEY_CALL_CARD_CALL_TYPE]   = call_type_id;
	callinfo[JSON_KEY_CALL_CARD_CALL_TIME] =(double)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;
		reader_id = (*it_reader)->get_map()[JSON_KEY_CALL_CARD_STATION_ID]->get_int();
		station[JSON_KEY_CALL_CARD_STATION_ID] = 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] = (int)(*it_card)->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID]->get_int();
		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);
	}

	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)
{
	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_extend s\
					   where pt.patrol_path_id = ppd.patrol_path_id and ppd.patrol_point_id = ps.patrol_point_id\
					   and pt.staff_id = s.staff_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, 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_extend s\
					   where s.card_id = %s and pt.patrol_path_id = ppd.patrol_path_id and ppd.patrol_point_id = ps.patrol_point_id\
					   and pt.staff_id = s.staff_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 = getMysqlRes(buf);

	if (NULL == pRes)
	{
		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:
	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.c_str());
	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_offset_after();
				ev->y = it_card->second->y_offset_after();
				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_offset_after();
					it_ev->second->y = it_card->second->y_offset_after();
					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_offset_after();
					it_ev->second->y = it_card->second->y_offset_after();
					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;
	double diff_rec = 0;
	// lihongzhen  2017/8/22 使用send_json_postion 目的是为了web前端动画流畅
	int read_cache_interval = min(theApp.send_json_postion/1000, CARD_LOST_TIME_CAL);

	CardMap::iterator it_staff = mp_card_list_down_person.begin();
	for (; it_staff != mp_card_list_down_person.end();)
	{
		diff_rec = difftime(time_current, it_staff->second->rec_time);
		// lihongzhen  2017/8/22 将缓存的数据读出来
		if(diff_rec > read_cache_interval && it_staff->second->dist_cache_size() > 0)
		{
			it_staff->second->cal_pos_by_cache();
			//deal_card_msg(it_staff->second, true); // 多个线程处理业务，可能会有冲突
			++it_staff;
			continue;
		}

		nLost = diff_rec < 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();
		}
	}

	nLost = STATUS_NORMAL;
	card = nullptr;
	CardMap::iterator it_vehicle = mp_card_list_down_vehicle.begin();
	for(; it_vehicle != mp_card_list_down_vehicle.end(); )
	{
		diff_rec = difftime(time_current, it_vehicle->second->rec_time);
		if(diff_rec > read_cache_interval && it_vehicle->second->dist_cache_size() > 0)
		{
			it_vehicle->second->cal_pos_by_cache();
			//deal_card_msg(it_vehicle->second, true);
			++it_vehicle;
			continue;
		}
		nLost =  diff_rec < CARD_LOST_TIME_OUT ? STATUS_NORMAL :STATUS_LOST;

		card = it_vehicle->second;
		++it_vehicle;

		// 丢失数据
		if(card->status_lost != nLost)
		{
			if(STATUS_LOST == nLost)
			{
				::GetLocalTime(&card->deal_time);

				AreaMap::iterator it_area_cur = mp_area_list.find(card->area_id);
				if(it_area_cur != mp_area_list.end())
				{
					int vid = card->id;
					// 处理非特殊区域的卡
					if(!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->idle_count = IDLE_CONFIRM_TIME; // 置为怠速，即进入盲区速度置为0

							card_leave_area(card, it_area_cur->second);
							store_data_card(card, HIS_AREA_LOCATION_LEAVE);

							// 进入特殊区域，生成一条轨迹记录
							card_enter_special_area(card, special_area_id);
							if (need_display_verification(card))// lemon 2017/08/01
							{
								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
							{
								debug_print_syslog(0, "[need_display_no]lost state, moving: %s", get_json_special_area_process(card).c_str());
							}
							//card_enter_mine(card,POS_DEVICE_TYPE::PDT_UP);  // 信号丢失不再统计考勤
						}
						else
						{
							// 非特殊区域超过CARD_LOST_TIME_OUT秒，未接收到数据，升井处理
							if(difftime(time_current, card->rec_time) > CARD_LOST_TIME_OUT_SPECIAL_AREA)
							{
								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);
							}
						}
					}	
				}

				if (VT_DIGGINGCOAL_MACHINE == card->vehice_type_id || VT_DRIVINGFACE_MACHINE == card->vehice_type_id)
				{
					card->status_lost = nLost;
					card_enter_mine(card, POS_DEVICE_TYPE::PDT_UP);
				}

			}
			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, landmark_id, landmark_dist,direction_mapper_id )\
		VALUES(%lld, %d, %d, %d, %s, %d, %d, %.2f, %.2f, %f, %f, '%s', '%s', %d, %d, %.3f);",
		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(),
		ev->landmarkid, ev->landmarkdirect, ev->landmarkdist);
	execute_sql(sql);
}

void CYAServerDlg::add_event( std::shared_ptr<YaEvent> ev )
{
	/*if(m_log_sys_status)
	{
		char buf[LENGTH_SQL] = {0};
		sprintf_s(buf,"add_event:status=%d,ev_type=%d,obj_type=%d,obj_id=%s,map_id = %d,area_id = %d,x=%f,y=%f,limit_value=%f,cur_value=%f,is_sent=%d",
			ev->status,ev->ev_type,ev->obj_type,ev->obj_id.c_str(),ev->map_id,ev->area_id,ev->x,ev->y,ev->limit_value,ev->cur_value,ev->is_sent);
		Log::write_log(FILE_TYPE::SYS_S, buf, true);
	}*/

	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(bool bAll /*= false*/)
{
	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();){
		// lihongzhen  2017/8/19 已处理呼救不再发送
		if(it_ev->second->status != ES_START && it_ev->second->status != ES_END){
			it_ev++;
			continue;
		}
		if(!it_ev->second->is_sent || bAll){
			//lemon 2017/08/01
			if(OBJECT_TYPE::OT_CARD == it_ev->second->obj_type)
			{
				CardMap::iterator it_card = mp_card_list_all.find(it_ev->second->obj_id);
				if(it_card != mp_card_list_all.end())
				{
					if (!need_display_verification(it_card->second))
					{
						++it_ev;
						continue;
					}
				}
			}
			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;

			double t = *((int64_t*)&it_ev->second->cur_time)*ms;
			ev[JSON_KEY_EVENT_CUR_TIME] = t;

			data.append(ev);

			it_ev->second->is_sent = true;

			++it_ev;
		}
		else if(it_ev->second->is_sent)
		{
			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();
	}

	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);
			//入井时间戳
			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())
			{
				//入井时间戳
				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;
}

void CYAServerDlg::parse_data_lights_state( BYTE* DataBuffer, int& nCurPos, int reader_id, unsigned short wChr )
{
	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 = 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);
			}
		}
		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)
					{
						//lemon 2017/08/01
						if (!need_display_verification(it_card->second))
						{
							continue;
						}
						if (it_card->second->call_type_id != 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)*ms;
							callinfo.append(t);
							callinfo.append(it_call_reader->second->call_level);
							callinfo.append(1);

							data.append(callinfo);
						}
					}
				}
			}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)
				{
					//lemon 2017/08/01
					CardMap::iterator it_card = mp_card_list_all.find(it_call_card->second->str_card_id);
					if(it_card != mp_card_list_all.end())
					{
						if (!need_display_verification(it_card->second))
						{
							continue;
						}
					}

					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)*ms;
					callinfo.append(t);
					callinfo.append(it_call_reader->second->call_level);
					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::OnBnTest()
{
<<<<<<< HEAD
	TestReadFile();
	//ReadTofDistFile();
}

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->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);
						}
					} 
				} 
				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;
}

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;
=======
	//TestReadFile();
	//测试TOF定位数据
	ReadTofDistFile();
	//TestParseCallCard();
	//string id = "0020000001091";
	//process_driving_face_end_service((mp_card_list_all.find(id))->second);
	//hex_convert();
	//测试惯导校准数据
	/*std::shared_ptr<Card> pCard = std::make_shared<Card>();
	pCard->card_type = 1;
	pCard->card_id = "0010000001234";
	pCard->reader_id = 702;
	send_ins_data(pCard);*/
>>>>>>> newprotocal
}

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(std::shared_ptr<Card> card)
{
	int minLandmarkID = -1;
	double minDistance = 100000;
	std::shared_ptr<LandmarkInfo> pLandmarkInfo = nullptr;
	int nRow = 0;
	_point card_position (card->x, 
		card->y, 
		card->z);
	LandmarkInfoMap::iterator it = mp_landmark_list.begin();		
	while(it != mp_landmark_list.end())
	{
		if(it->second->area_id == card->area_id)
		{
			pLandmarkInfo = it->second;
			_point landmark_position (pLandmarkInfo->x, 
				pLandmarkInfo->y, 
				pLandmarkInfo->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;
	}

	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);

	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);

	execute_sql(sql);
}

int CYAServerDlg::init_shift()
{
	MYSQL_ROW pRow;
	MYSQL_RES *pRes = NULL;

	pRes = getMysqlRes("select shift_id, start_time, end_time, shift_type_id from dat_shift;");
	
	if( NULL == pRes)
	{
		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], atoi(pRow[3]));
			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;
}

int CYAServerDlg::GetCurShiftId( struct tm* current_time, int shift_type /* = 1*/ )
{
	char ch[64];
	strftime(ch, sizeof(ch), "%H-%M-00", current_time);
	std::string curtime = ch;

	int shift_id = 1;
	BanShiftMap::iterator it_shift = mp_banshift_list.begin();
	for(; it_shift != mp_banshift_list.end(); ++it_shift)
	{
		if(it_shift->second->shift_type_id == shift_type)
		{		
			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;
				}
			}
			else
			{
				if(curtime >= it_shift->second->start_time && curtime < it_shift->second->end_time)
				{
					shift_id = it_shift->first;
				}
			}
		}
	}
	return shift_id;
}

void CYAServerDlg::TestCallCard()
{
	BYTE buf[LENGTH_SEND_BUF] = {0};
	memset(buf, 0, LENGTH_SEND_BUF);
	int npos = 0, card_count = 0, call_type = 1,card_type = 1, card_id = 100;
	//卡数
	card_count = 1;
	memcpy(&buf[npos], &card_count, sizeof(BYTE));
	npos += sizeof(BYTE);
	//呼叫类型
	memcpy(&buf[npos], &call_type, sizeof(BYTE));
	npos += sizeof(BYTE);

	//呼叫类型
	memcpy(&buf[npos], &call_type, sizeof(BYTE));
	npos += sizeof(BYTE);
	//卡类型
	memcpy(&buf[npos], &card_type, sizeof(BYTE));
	npos += sizeof(BYTE);
	//卡ID长度
	BYTE id_len = (BYTE)get_card_id_len(card_type);
	memcpy(&buf[npos], &id_len, sizeof(BYTE));
	npos += sizeof(BYTE);
	//卡ID
	if(id_len > 1){ // 标准卡id为4个字节，自组网卡为1个字节
		CFunctions::memcpyDWord(buf,(DWORD)card_id, npos);
	}else{
		memcpy(&buf[npos], &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(it_sock->second->reader_id == 101 && it_sock->second->reader_type == DEVICE_TYPE::DT_CARD_READER)
		{
			SendData(it_sock->second->dwConnID,CHAR_CALL, npos, buf);
			break;
		}
	}
}

void CYAServerDlg::TestParseCallCard()
{
	//{
	//    "cmd": "call_card_req",
	//    "data":{
	//	    "call_id":1,
	//		"call_time_out":5,
	//		"call_type_id": 0,
	//		"user_name": "xuying",
	//		"call_time":1501117298828,
	//		"stations": [{stationid: "0"}],
	//		"cards":[
	//		 {
	//			 "cardid":"0010000000002",
	//		     "cardtype":1
	//		 },
	//		 {
	//			 "cardid":"0010000000004",
	//			 "cardtype":1
	//		 },
	//		 {
	//			 "cardid":"0010000000005",
	//		     "cardtype":1
	//		 }
	//	     ]
	//	}
	//}	

	// 定员呼叫
	message::ptr root = object_message::create();
	static_cast<object_message*>(root.get())->get_map()[JSON_ROOT_KEY_CMD] = string_message::create(JSON_CMD_VALUE_CALL_CARD_REQUEST);
	
	message::ptr data = object_message::create();
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_TYPE] = int_message::create(1);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_TIME_OUT] = int_message::create(5);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_LEVEL] = int_message::create(0);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_USER_NAME] = string_message::create("lihz");
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_TIME] = int_message::create(time(NULL));
	
	message::ptr stations = array_message::create();
	message::ptr station = object_message::create();	
	static_cast<object_message*>(station.get())->get_map()[JSON_KEY_CALL_CARD_STATION_ID] = int_message::create(0);
	static_cast<array_message*>(stations.get())->get_vector().push_back(station);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_STATIONS] = stations;

	message::ptr cards = array_message::create();
	message::ptr card = object_message::create();
	static_cast<object_message*>(card.get())->get_map()[JSON_KEY_CALL_CARD_CARD_ID] = string_message::create("0010000000046");
	static_cast<object_message*>(card.get())->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID] = int_message::create(1);
	static_cast<array_message*>(cards.get())->get_vector().push_back(card);
	card = object_message::create();
	static_cast<object_message*>(card.get())->get_map()[JSON_KEY_CALL_CARD_CARD_ID] = string_message::create("0010000000004");
	static_cast<object_message*>(card.get())->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID] = int_message::create(1);
	static_cast<array_message*>(cards.get())->get_vector().push_back(card);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CARDS] = cards;

	static_cast<object_message*>(root.get())->get_map()[JSON_ROOT_KEY_DATA] = data;

	parse_json_data_call_card(root);

	// 全员呼叫
	root = object_message::create();
	static_cast<object_message*>(root.get())->get_map()[JSON_ROOT_KEY_CMD] = string_message::create(JSON_CMD_VALUE_CALL_CARD_REQUEST);

	data = object_message::create();
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_TYPE] = int_message::create(0);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_TIME_OUT] = int_message::create(5);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_LEVEL] = int_message::create(0);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_USER_NAME] = string_message::create("lihz");
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_TIME] = int_message::create(time(NULL));

	stations = array_message::create();
	station = object_message::create();	
	static_cast<object_message*>(station.get())->get_map()[JSON_KEY_CALL_CARD_STATION_ID] = int_message::create(0);
	static_cast<array_message*>(stations.get())->get_vector().push_back(station);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_STATIONS] = stations;

	cards = array_message::create();
	card = object_message::create();
	static_cast<object_message*>(card.get())->get_map()[JSON_KEY_CALL_CARD_CARD_ID] = string_message::create("0");
	static_cast<object_message*>(card.get())->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID] = int_message::create(1);
	static_cast<array_message*>(cards.get())->get_vector().push_back(card);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CARDS] = cards;
	static_cast<object_message*>(root.get())->get_map()[JSON_ROOT_KEY_DATA] = data;

	parse_json_data_call_card(root);
	
	// 取消全员呼叫
	root = object_message::create();
	static_cast<object_message*>(root.get())->get_map()[JSON_ROOT_KEY_CMD] = string_message::create(JSON_CMD_VALUE_CALL_CARD_CANCEL_REQUEST);

	data = object_message::create();
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_TYPE] = int_message::create(0);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_USER_NAME] = string_message::create("lihz");
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_TIME] = int_message::create(time(NULL));

	stations = array_message::create();
	station = object_message::create();	
	static_cast<object_message*>(station.get())->get_map()[JSON_KEY_CALL_CARD_STATION_ID] = int_message::create(0);
	static_cast<array_message*>(stations.get())->get_vector().push_back(station);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_STATIONS] = stations;

	cards = array_message::create();
	card = object_message::create();
	static_cast<object_message*>(card.get())->get_map()[JSON_KEY_CALL_CARD_CARD_ID] = string_message::create("0");
	static_cast<object_message*>(card.get())->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID] = int_message::create(1);
	static_cast<array_message*>(cards.get())->get_vector().push_back(card);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CARDS] = cards;
	static_cast<object_message*>(root.get())->get_map()[JSON_ROOT_KEY_DATA] = data;

	//parse_json_data_call_card_cancel(root);
	// 取消定员呼叫
	root = object_message::create();
	static_cast<object_message*>(root.get())->get_map()[JSON_ROOT_KEY_CMD] = string_message::create(JSON_CMD_VALUE_CALL_CARD_CANCEL_REQUEST);

	data = object_message::create();
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_TYPE] = int_message::create(1);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_USER_NAME] = string_message::create("lihz");
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CALL_TIME] = int_message::create(time(NULL));

	stations = array_message::create();
	station = object_message::create();	
	static_cast<object_message*>(station.get())->get_map()[JSON_KEY_CALL_CARD_STATION_ID] = int_message::create(0);
	static_cast<array_message*>(stations.get())->get_vector().push_back(station);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_STATIONS] = stations;

	cards = array_message::create();
	card = object_message::create();
	static_cast<object_message*>(card.get())->get_map()[JSON_KEY_CALL_CARD_CARD_ID] = string_message::create("0010000000004");
	static_cast<object_message*>(card.get())->get_map()[JSON_KEY_CALL_CARD_CARD_TYPE_ID] = int_message::create(1);
	static_cast<array_message*>(cards.get())->get_vector().push_back(card);
	static_cast<object_message*>(data.get())->get_map()[JSON_KEY_CALL_CARD_CARDS] = cards;
	static_cast<object_message*>(root.get())->get_map()[JSON_ROOT_KEY_DATA] = data;

	parse_json_data_call_card_cancel(root);
}

void CYAServerDlg::OnLoginEx(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: // 用户未登录
		{
			is_websocket_login_ex = false;
			break;
		}
	case 0:
		{
			if("" == data->get_map()["code"]->get_string()){ // 登录成功
				is_websocket_login_ex = true;
			}else{ // 退出登录
				is_websocket_login_ex = false;
			}
			break;
		}
	default:
		break;
	}
}

void CYAServerDlg::OnConnectedEx()
{
	is_websocket_ok = true;
	time_ws_connect_ex = ::GetTickCount();
}

void CYAServerDlg::OnClosedEx(client::close_reason const& reason)
{
	int i = -1;
	if(reason == client::close_reason_drop){
		i = (int) reason;
	}else{
		i = (int) reason;
	}
	is_websocket_login_ex = false;
	is_websocket_ok_ex = false;
}

void CYAServerDlg::OnFailedEx()
{
	is_websocket_login_ex = false;
	is_websocket_ok_ex = false;
	_io_ex->close();
}

void CYAServerDlg::ws_init_ex()
{
	is_websocket_ok_ex = false;
	is_websocket_login_ex = false;

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

	sock->on(JSON_CMD_VALUE_USER, sio::socket::event_listener_aux(std::bind(&CYAServerDlg::OnLoginEx, 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)));
	//default socket opened, also we have "set_open_listener" for monitoring physical connection opened.
	_io_ex->set_socket_open_listener(std::bind(&CYAServerDlg::OnConnectedEx, this));
	//physical connection closed or drop.
	_io_ex->set_close_listener(std::bind(&CYAServerDlg::OnClosedEx,this, std::placeholders::_1));
	//physical connection fail to establish.
	_io_ex->set_fail_listener(std::bind(&CYAServerDlg::OnFailedEx,this));
}

void CYAServerDlg::ws_open_ex()
{
	// 地址相同或者备用地址为空，不走数据
	if(m_ws_url_ex == m_ws_url || 0 == m_ws_url_ex.length())
	{
		return ;
	}

	_io_ex->connect(m_ws_url_ex);

	CString strlog = _T("");

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

	show_log(strlog);
}

void CYAServerDlg::ws_login_ex()
{
	USES_CONVERSION;
	CC2UTF8 conv = (char*)get_json_login().c_str();
	string szlogin = conv.c_str();
	_io_ex->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_ex = (0 == n) ? true : false;
		CString strlog;
		wchar_t* p_url = CFunctions::c2wc(m_ws_url_ex.c_str());
		if(is_websocket_login_ex){
			strlog.Format(_T("%s: %s"), _T(LOG_LOGIN_WEB_SERVER), p_url);
		}else{
			p_url = CFunctions::c2wc(m_ws_url_ex.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_ex()
{
	USES_CONVERSION;
	CC2UTF8 conv = (char*)get_json_logout().c_str();
	string szlogout = conv.c_str();
	_io_ex->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_ex.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_ex.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::TestFitData()
{
	//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);
	//}
}

int CYAServerDlg::init_leader_arrange()
{
	clear_leader_arrange();
	// 载入带班领导信息
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "select la.staff_id, s.card_id, la.shift_id, s.shift_type_id, la.duty_date,\
		sht.start_time, sht.end_time, \
		case when start_time > end_time then CONCAT(date_add(duty_date, INTERVAL -1 DAY), ' ', start_time) else \
		CONCAT(duty_date,' ', start_time) end as stime, CONCAT( duty_date, ' ', end_time) as etime \
		from dat_leader_arrange la, dat_shift sht, dat_staff_extend s \
		where la.staff_id = s.staff_id and la.shift_id = sht.shift_id \
		and la.duty_date >= date_add(curdate(), INTERVAL -1 DAY) and la.duty_date < date_add(curdate(), INTERVAL 1 DAY);");

	MYSQL_RES *pRes = getMysqlRes(buf);
	MYSQL_ROW pRow;
	
	if (NULL == pRes)
	{
		return 1;
	}

	std::shared_ptr<LeaderArrange> pLeader = nullptr;
	int nRow = 0;
	while(pRow = mysql_fetch_row(pRes))	{
		LeaderArrangeMap::iterator it = mp_leaderarrange_list.find(pRow[1]);
		if(it != mp_leaderarrange_list.end()){
			pLeader = it->second;
		}else{
			pLeader = std::make_shared<LeaderArrange>(pRow[1]);
			mp_leaderarrange_list.insert(make_pair(pRow[1], pLeader));
		}
		pLeader->staff_id = atoi(pRow[0]);
		pLeader->shift_id = atoi(pRow[2]);
		pLeader->shift_type_id = atoi(pRow[3]);
		string strTime = pRow[7];
		API_StringToTime(strTime, pLeader->starttime);
		strTime = pRow[8];
		API_StringToTime(strTime, pLeader->endtime);

		nRow++;
	}
	mysql_free_result(pRes);

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

	return 0;
}

std::string CYAServerDlg::get_json_leader_arrange()
{
	Json::Value root;
	Json::Value data;
	LeaderArrangeMap::iterator it_leader = mp_leaderarrange_list.begin();
	for(; it_leader != mp_leaderarrange_list.end(); ++it_leader)
	{
		CardMap::iterator it_card = mp_card_list_down_person.find(it_leader->first);
		if(it_card != mp_card_list_down_person.end())
		{
			if( it_card->second->down_time >= it_leader->second->starttime && 
				it_card->second->down_time < it_leader->second->endtime)
			{
				Json::Value card;
				card[JSON_KEY_CARD_ID] = it_card->first;
				card[JSON_KEY_CARD_TYPE_ID] = it_card->second->card_type;
				data.append(card);
			}
		}
	}

	string ret = "";
	if(!data.isNull()) // 没有带班领导推送null
	{
		root[JSON_ROOT_KEY_CMD] = JSON_CMD_VALUE_LEADER_ARRANGE;
		root[JSON_ROOT_KEY_DATA] = data;
		root[JSON_ROOT_KEY_VERSION] = INTERFACE_VERSION_1_1;
		ret = root.toFastString();
	}

	return ret;
}

void CYAServerDlg::clear_leader_arrange()
{
	LeaderArrangeMap::iterator it_leader = mp_leaderarrange_list.begin();
	for(; it_leader != mp_leaderarrange_list.end();)
	{
		it_leader = mp_leaderarrange_list.erase(it_leader);
	}
}

void CYAServerDlg::cal_card_position_by_msg(std::shared_ptr<Card> card)
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_129);
	if(CT_ADHOC == card->card_type){ // 此处不需处理，已经在解析时计算了坐标位置		
		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;
		dist->cur_time = time(NULL);
		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;
		dist->rangingtype = card->ranging_type;

		bool bUseAlgo = false;
		unsigned long long rootId = dist->syncRootId;
		unsigned short root_sync_num = 0;
		if( LOCATEDATATYPE::LDT_TDOA == card->ranging_type)
		{
			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->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 = LONGLONG_MAX;
						LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_123);
						TRACE(_T("calc error!\r\n"));
					}
				}
#endif // TRACE_MEMORY_TAGMSG
			}else{
				LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_220);
			}

		}
		else if(LOCATEDATATYPE::LDT_TOF == card->ranging_type)
		{
			bUseAlgo = true;
		}

		if(bUseAlgo)
		{
			card->is_deal_by_algo = false;
			// 井上分站的数据，不进算法
			if(PDT_DOWN ==  card->p_reader->pos_state)
			{
				card->add_dist(dist);
			}
			else
			{
				card->b_pos_change = false; //井上分站重置状态
			}
		}
		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);
			char chlog[MAX_LOG_LENGTH] = {0};
			std::string strlog = "";

			if (card->ranging_type == LOCATEDATATYPE::LDT_TDOA)
			{
				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);

				//此处和save_card_msg消息存在不一致
				if(card->x != card->last_x || card->y != card->last_y){
					LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_126);
					memset(chlog, 0, MAX_LOG_LENGTH);
					sprintf_s(chlog, "cardid:%s, ct: %d, cx: %f, cy: %f,  clx: %f, cly: %f, v: %f,as: %d",
						card->card_id.c_str(), card->time_stamp_cal, card->x, card->y, card->last_x, card->last_y, card->get_speed(), card->accelerate_state);
					strlog = chlog;
					Log::write_log(FILE_TYPE::DISTEX_S, strlog, true);

					memset(chlog, 0, MAX_LOG_LENGTH);
					sprintf_s(chlog, "sn:%d, ox: %f, oy: %f, x: %f, y: %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->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);

					card->last_x = card->x;
					card->last_y = card->y;
					card->last_z = card->z;

					card->last_offset_x = card->x_offset_after();
					card->last_offset_y = card->y_offset_after();
				}else{		
					if(card->is_deal_by_algo){
						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);
					}
				}
			} 
			else if(card->ranging_type == LOCATEDATATYPE::LDT_TOF)
			{
				if (card->is_deal_by_algo)
				{
					if(card->x != card->last_x || card->y != card->last_y){
						std::string ltslog = "";
						memset(chlog,0,MAX_LOG_LENGTH*sizeof(char));
						std::string strReaderTime = "";
						std::string strAlgoTime = "";
						if (card->p_reader)
						{
							strReaderTime = CFunctions::time_t2string(card->p_reader->reader_time);
							strAlgoTime = CFunctions::time_t2string(card->time_last_tof);
						}
<<<<<<< HEAD
						sprintf_s(chlog,"card_id: %s,ct: %d, cx: %.2f, cy: %.2f, cz: %.2f, clx: %.2f,fly: %.2f,cv: %f,as: %d, reader_time: %s",card->card_id.c_str(),card->time_stamp_cal,card->x, card->y, card->z,card->last_x,card->last_y,card->get_speed(),card->accelerate_state,strReaderTime.c_str());
=======
						sprintf_s(chlog,"card_id: %s,ct: %d, cx: %.2f, cy: %.2f, cz: %.2f, clx: %.2f,fly: %.2f,cv: %f, reader_time: %s,algo_time: %s",card->card_id.c_str(),card->time_stamp_cal,card->x, card->y, card->z,card->last_x,card->last_y,card->get_speed(),strReaderTime.c_str(),strAlgoTime.c_str());
>>>>>>> newprotocal
						ltslog = chlog;
						Log::write_log(FILE_TYPE::LOCATE_TOF_S,ltslog,true);

						card->last_x = card->x;
						card->last_y = card->y;
						card->last_z = card->z;
					}
				}

				std::string dtslog = "";
				std::string strRecTime = "";
				int tick_count = -1;
				if (card->p_reader)
				{
					strRecTime = CFunctions::time_t2string(card->p_reader->rec_time);
					tick_count = card->p_reader->tick_count;
				}else{
					strRecTime = CFunctions::time_t2string(time(NULL));
				}
				
				memset(chlog,0,MAX_LOG_LENGTH*sizeof(char));
				sprintf_s(chlog,"r: %d, ant: %d, ct: %d, d: %f, x: %f, y: %f, z: %f,card_id: %s,rtc: %d,rt: %s",
					dist->reader_id,
					dist->antenna_id, 
					dist->t, 
					dist->d, 
					dist->x, 
					dist->y, 
					dist->z,
					card->card_id.c_str(),
					tick_count,
					strRecTime.c_str()
					);
				dtslog = chlog;
				Log::write_log(FILE_TYPE::DIST_TOF_S,dtslog,true);
			}
		}
	}
}

MYSQL_RES* CYAServerDlg::getMysqlRes(const char* sql)
{
	if (g_pConnPool->m_needConnect)
	{
		return NULL;
	}
	Log::write_log(SQL_S,sql,true);
	CMysqlConn* pConn = NULL;
	CDBConnGuard pDbGuard(pConn, g_pConnPool);

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

	int err = 0;
	MYSQL_RES *pRes = pConn->Execute(sql, err);
	switch (err)
	{
	case CR_COMMANDS_OUT_OF_SYNC:
		break;
	case CR_SERVER_GONE_ERROR:
	case CR_SERVER_LOST:
		{		
			pDbGuard.isVaild();
		}
		break;
	case CR_UNKNOWN_ERROR:
	default:
		break;
	}
	return pRes;
}

void CYAServerDlg::TestMultSql()
{
	string strsql = "CALL add_att_vehicle(0020000001025, 1025, '2017-08-06 08:35:50', '2017-08-06 08:35:50', 9, 1, 51.100);";
	m_qsmSQL->AddString(strsql.c_str());
	strsql = "CALL add_att_vehicle(0020000001025, 1025, '2017-08-06 08:35:50', '2017-08-06 18:35:51', 10, 3, 39.049);";
	m_qsmSQL->AddString(strsql.c_str());
	strsql = "call add_area_vehicle(0020000001049, 1049, 5, 5, '2017-08-06 08:35:51','2017-08-06 08:35:51');";
	m_qsmSQL->AddString(strsql.c_str());
	strsql = "call add_area_vehicle(0020000001049, 1049, 5, 5, '2017-08-06 08:35:51','2017-08-06 18:35:51');";
	m_qsmSQL->AddString(strsql.c_str());
	strsql = "INSERT IGNORE INTO his_location_vehicle(card_id, vehicle_id, cur_time, x, y, z, map_id, area_id, \
			 state,speed,mileage, landmark_id, direction_mapper_id, landmark_dist) VALUES(0020000001016, 1016, \
			 '2017-8-6 8:35:50.559', 4727.000, -16.219, 0.000, 5, 1, 0,0.000,0.0000, 9, 3, 59.3290);";
	m_qsmSQL->AddString(strsql.c_str());

	m_qsmSQL->Execute();
}

void CYAServerDlg::TestCardPosition()
{
	std::shared_ptr<Card> pCard = std::make_shared<Card>("", 0, 0);
	pCard->x = 10, pCard->y = 10;
	pCard->last_locate.x = 10, pCard->last_locate.y = 5;
	pCard->algo_calc_offset();
	
	double x = pCard->x_offset_after();
	double y = pCard->y_offset_after();
	TRACE(_T("offset position: %.2f, %.2f, %.2f, %.2f, %.2f, %.2f\r\n"),
		pCard->last_locate.x, pCard->last_locate.y, pCard->x, pCard->y, x, y);

	pCard->x = 10, pCard->y = 10;
	pCard->last_locate.x = 10, pCard->last_locate.y = 15;
	pCard->algo_calc_offset();
	
	x = pCard->x_offset_after();
	y = pCard->y_offset_after();
	TRACE(_T("offset position: %.2f, %.2f, %.2f, %.2f, %.2f, %.2f\r\n"),
		pCard->last_locate.x, pCard->last_locate.y, pCard->x, pCard->y, x, y);

	pCard->x = 5, pCard->y = 10;
	pCard->last_locate.x = 10, pCard->last_locate.y = 10;
	pCard->algo_calc_offset();

	x = pCard->x_offset_after();
	y = pCard->y_offset_after();
	TRACE(_T("offset position: %.2f, %.2f, %.2f, %.2f, %.2f, %.2f\r\n"),
		pCard->last_locate.x, pCard->last_locate.y, pCard->x, pCard->y, x, y);

	pCard->x = 15, pCard->y = 10;
	pCard->last_locate.x = 10, pCard->last_locate.y = 10;
	pCard->algo_calc_offset();

	x = pCard->x_offset_after();
	y = pCard->y_offset_after();
	TRACE(_T("offset position: %.2f, %.2f, %.2f, %.2f, %.2f, %.2f\r\n"),
		pCard->last_locate.x, pCard->last_locate.y, pCard->x, pCard->y, x, y);

	pCard->x = 10, pCard->y = 10;
	pCard->last_locate.x = 5, pCard->last_locate.y = 5;
	pCard->algo_calc_offset();

	x = pCard->x_offset_after();
	y = pCard->y_offset_after();
	TRACE(_T("offset position: %.2f, %.2f, %.2f, %.2f, %.2f, %.2f\r\n"),
		pCard->last_locate.x, pCard->last_locate.y, pCard->x, pCard->y, x, y);

	pCard->x = 10, pCard->y = 10;
	pCard->last_locate.x = 5, pCard->last_locate.y = 15;
	pCard->algo_calc_offset();

	x = pCard->x_offset_after();
	y = pCard->y_offset_after();
	TRACE(_T("offset position: %.2f, %.2f, %.2f, %.2f, %.2f, %.2f\r\n"),
		pCard->last_locate.x, pCard->last_locate.y, pCard->x, pCard->y, x, y);

	pCard->x = 10, pCard->y = 10;
	pCard->last_locate.x = 15, pCard->last_locate.y = 15;
	pCard->algo_calc_offset();

	x = pCard->x_offset_after();
	y = pCard->y_offset_after();
	TRACE(_T("offset position: %.2f, %.2f, %.2f, %.2f, %.2f, %.2f\r\n"),
		pCard->last_locate.x, pCard->last_locate.y, pCard->x, pCard->y, x, y);

	pCard->x = 10, pCard->y = 10;
	pCard->last_locate.x = 15, pCard->last_locate.y = 5;
	pCard->algo_calc_offset();

	x = pCard->x_offset_after();
	y = pCard->y_offset_after();
	TRACE(_T("offset position: %.2f, %.2f, %.2f, %.2f, %.2f, %.2f\r\n"),
		pCard->last_locate.x, pCard->last_locate.y, pCard->x, pCard->y, x, y);
}

int CYAServerDlg::init_att_area()
{
	clear_att_area();
	// 载入考勤区域信息
	int err = 0;
	char buf[LENGTH_SQL] = {0};
	sprintf_s(buf, "select vt.vehicle_type_id, aa.area_id, ar.offset_pre, ar.offset_back \
				   from dat_att_rule_vehicle_type vt \
				   left join dat_att_rule_area aa on vt.att_rule_id = aa.att_rule_id \
				   left join dat_att_rule ar on vt.att_rule_id = ar.att_rule_id \
				   where area_id is not null;");

	MYSQL_RES *pRes = getMysqlRes(buf);
	MYSQL_ROW pRow;

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

	std::shared_ptr<VehicleTypeAttRule> pAttArea = nullptr;
	int nRow = 0;
	int vehicle_type_id = 0, area_id = 0, offset_pre = 0, offset_back = 0;
	while(pRow = mysql_fetch_row(pRes))	{

		vehicle_type_id = atoi(pRow[0]), area_id = atoi(pRow[1]);
		offset_pre = (pRow[2] == NULL)? 0 :atoi(pRow[2]), offset_back = (pRow[3] == NULL)? 0 : atoi(pRow[3]);
		VehicleTypeAttRuleMap::iterator it_att_area = mp_att_area_list.find(vehicle_type_id);
		if(it_att_area != mp_att_area_list.end()){
			pAttArea = it_att_area->second;
		}else{
			pAttArea = std::make_shared<VehicleTypeAttRule>(vehicle_type_id, offset_pre, offset_back);
			mp_att_area_list.insert(make_pair(vehicle_type_id, pAttArea));
		}

		pAttArea->AddArea(area_id);
		nRow++;
	}
	mysql_free_result(pRes);

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

	return 0;
}

void CYAServerDlg::clear_att_area()
{
	VehicleTypeAttRuleMap::iterator it_att_area = mp_att_area_list.begin();
	for(; it_att_area != mp_att_area_list.end();)
	{
		it_att_area->second->vecArea.clear();
		it_att_area = mp_att_area_list.erase(it_att_area);
	}
}

void CYAServerDlg::set_card_pos_state(std::shared_ptr<Card> 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)
		{
			card->PosState((0 == it_area->second->area_type_id) ? PDT_UP :PDT_DOWN);
		}
		else if(CT_VEHICLE == card->card_type)
		{
			// 根据车辆类型判断是否在考勤区域
			card->PosState(GetPosDownAndUp(card->vehice_type_id, card->area_id));
		}
	}
}

void CYAServerDlg::deal_card_drivingface_real(std::shared_ptr<Card> card)
{
	LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_257);
	//calculate_card_postion_by_tof(card); // 计算位置

	card_enter_map(card); // 切换地图
	card_enter_area(card);
	save_card_postion(card);
	//写入实时库表，然后判断是否更新当前班次表，如果当前位置有更新则更新。
	write_his_drivingface_real(card);
	//如果掘进机第一次有数据，表示启动了，则insert一条数据
	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);
	card->isdealed = true;

	if(LT_READER != theApp.locate_type){
		card->issent = false;
	}
}

POS_DEVICE_TYPE CYAServerDlg::GetPosDownAndUp(int vehicle_type_id, int area_id)
{
	POS_DEVICE_TYPE ret = POS_DEVICE_TYPE::PDT_DOWN;
	VehicleTypeAttRuleMap::iterator it_rule = mp_att_area_list.find(vehicle_type_id);
	if(it_rule != mp_att_area_list.end())
	{
		std::vector<int>::iterator it_area = 
			std::find(it_rule->second->vecArea.begin(), it_rule->second->vecArea.end(), area_id);
		if(it_area != it_rule->second->vecArea.end())
		{
			ret = POS_DEVICE_TYPE::PDT_UP;
		}
	}

	return ret;
}

void CYAServerDlg::clear_card_from_list(std::shared_ptr<Card> card)
{
	CardMap::iterator it_card;
	
	MapInfoMap::iterator it_map = mp_map_list.find(card->map_id);
	if(it_map != mp_map_list.end()){
		if(CT_VEHICLE == card->card_type){
			// lihongzhen  2017/8/22 车辆不从列表中清除
			//CardMap::iterator it_map_card = it_map->second->map_card_list_vehicle.find(card->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->card_type){
			CardMap::iterator it_map_card = it_map->second->map_card_list_person.find(card->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(card->area_id);
	if(it_area != mp_area_list.end()){
		if(CT_VEHICLE == card->card_type){
			// lihongzhen  2017/8/22 车辆不从列表中清除
			//CardMap::iterator it_area_card = it_area->second->area_card_list_vehicle->find(card->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->card_type){
			CardMap::iterator it_area_card = it_area->second->area_card_list_person->find(card->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(card->dept_id);
	if(it_dept != mp_dept_list.end()){
		if(CT_VEHICLE == card->card_type){
			// lihongzhen  2017/8/22 车辆不从列表中清除
			//CardMap::iterator it_dept_card = it_dept->second->dept_card_list_vehicle.find(card->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->card_type){
			CardMap::iterator it_dept_card = it_dept->second->dept_card_list_person.find(card->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->card_type){
		// lihongzhen  2017/8/22 车辆不从列表中清除
		//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);			
		//}
		it_card = mp_card_list_forbidden_vehicle->find(card->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->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->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->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->card_type) {
		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);
		}
		it_card = mp_card_list_over_time_person->find(card->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->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->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->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->card_id);
		if (it_card != mp_card_list_over_count_person->end())
		{
			mp_card_list_over_count_person->erase(it_card);
		}
		it_card = mp_card_list_over_count_vehicle->find(card->card_id);
		if (it_card != mp_card_list_over_count_vehicle->end())
		{
			mp_card_list_over_count_vehicle->erase(it_card);
		}
		OccLevelMap::iterator it_level = mp_occlevel_list.find(card->level_id);
		if(it_level != mp_occlevel_list.end())
		{
			CardMap::iterator it_level_card = it_level->second->level_card_list_person.find(card->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);
			}
		}
	}

	it_card = mp_card_list_all.find(card->card_id);
	if(it_card != mp_card_list_all.end())
	{
		it_card->second->reset();
		it_card->second->resetAllBaseInfo();
	}
}

void CYAServerDlg::clear_call_card_by_user(std::string user_name)
{
	// 只删除该用户的所有呼叫信息，不从呼叫列表中删除该用户记录
	CallInfoUserMap::iterator it_user_call = mp_user_call_info.find(user_name);
	if(it_user_call != mp_user_call_info.end())
	{
		CallInfoReaderMap::iterator it_call_reader = it_user_call->second->mpReader.begin();
		for( ;it_call_reader != it_user_call->second->mpReader.end();){
			it_call_reader->second->mpCard.erase(it_call_reader->second->mpCard.begin(), it_call_reader->second->mpCard.end());
			it_call_reader = it_user_call->second->mpReader.erase(it_call_reader);
		}
	}
}

void CYAServerDlg::GetLandmarkInfo(std::shared_ptr<Card> card)
{
	_point card_point(card->x, card->y, card->z);
	int landmark_id = GetLandmarkID(card);

	if(-1 == landmark_id)
	{
		return ;
	}

	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;
}