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

#include "stdafx.h"
#include "VCDemo.h"
#include "RecordSearch.h"
#include "VCDemoDlg.h"


// CRecordSearch 对话框

IMPLEMENT_DYNAMIC(CRecordSearch, CDialog)

CRecordSearch::CRecordSearch(CWnd* pParent /*=NULL*/)
	: CDialog(CRecordSearch::IDD, pParent)
{
	m_parent=NULL;
}

CRecordSearch::~CRecordSearch()
{
}

void CRecordSearch::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_DEVLIST, m_DevTree);
	DDX_Control(pDX, IDC_DEVID, m_DevId);
	DDX_Control(pDX, IDC_COMBO2, m_VideoSrc);
	DDX_Control(pDX, IDC_COMBO4, m_RecordType);
	DDX_Control(pDX, IDC_COMBO1, m_MediaType);
	DDX_Control(pDX, IDC_COMBO3, m_StreamType);
	DDX_Control(pDX, IDC_DATETIMEPICKER2, m_starttime);
	DDX_Control(pDX, IDC_DATETIMEPICKER1, m_endtime);
	DDX_Control(pDX, IDC_SEARTRESULT, m_recordList);
	DDX_Control(pDX, IDC_REALTIMEPLAYERATL1, m_Player);
}


BEGIN_MESSAGE_MAP(CRecordSearch, CDialog)

	ON_WM_DESTROY()
	ON_NOTIFY(TVN_SELCHANGED, IDC_DEVLIST, &CRecordSearch::OnTvnSelchangedDevlist)
	ON_CBN_SELCHANGE(IDC_COMBO2, &CRecordSearch::OnCbnSelchangeCombo2)
	ON_BN_CLICKED(IDC_SEARCH, &CRecordSearch::OnBnClickedSearch)
	ON_BN_CLICKED(IDC_NEXT, &CRecordSearch::OnBnClickedNext)
	ON_BN_CLICKED(IDC_PREV, &CRecordSearch::OnBnClickedPrev)
	ON_NOTIFY(NM_DBLCLK, IDC_SEARTRESULT, &CRecordSearch::OnNMDblclkSeartresult)
END_MESSAGE_MAP()


// CRecordSearch 消息处理程序





int CRecordSearch::OnRecaLoginXml(int nCode,BSTR & xml)
{
	if(!nIsRunning)
	{
		return -1;
	}
	m_recordList.DeleteAllItems();
	::TiXmlDocument doc;
	doc.LoadFromString(_bstr_t(xml));
	if(doc.Error())
	{
		MessageBox(_T("无法解释XML"));
		return -2;
	}
	switch(nCode)
	{
	case 141:
		{//<Response Code="141" DevId="86002S1289896254" TotalNum="0" RecordNum="0" Result ="0">
			TiXmlElement * root=doc.FirstChildElement();
			const char * Ret=root->Attribute("RecordNum");
			int ret=atol(Ret);
			if(ret<=0)
			{
				MessageBox(_T("返回记录为空"));
				return -3;
			}
			playtype=141;
			TiXmlElement * item=root->FirstChildElement();
			while(item)
			{//<Item FilePath="/mnt/vr/pri/860000652/sched/20101117/161500_000300.dat" startTime="2010/11/17 16:15:00" endTime="2010/11/17 16:20:00" />
				const char * file=item->Attribute("FilePath");
				const char * startTime=item->Attribute("startTime");
				const char * endTime=item->Attribute("endTime");
				int idx=m_recordList.InsertItem(m_recordList.GetItemCount(),_bstr_t(file));
				m_recordList.SetItemText(idx,1,_bstr_t(startTime));
				m_recordList.SetItemText(idx,2,_bstr_t(endTime));
				item=item->NextSiblingElement();
			}
		}
		break;
	case 145:
		{//<Response Code="141" DevId="86002S1289896254" TotalNum="0" RecordNum="0" Result ="0">
			TiXmlElement * root=doc.FirstChildElement();
			const char * Ret=root->Attribute("RecordNum");
			int ret=atol(Ret);
			if(ret<=0)
			{
				MessageBox(_T("返回记录为空"));
				return -3;
			}
			playtype=145;
			TiXmlElement * item=root->FirstChildElement();
			while(item)
			{
				//int idx=m_recordList.InsertItem(m_recordList.GetItemCount(),);
				//m_recordList.SetItemText(idx,1,);
				item=item->NextSiblingElement();
			}
		}
		break;
	case 149:
		{//<Response Code="141" DevId="86002S1289896254" TotalNum="0" RecordNum="0" Result ="0">
			TiXmlElement * root=doc.FirstChildElement();
			const char * Ret=root->Attribute("RecordNum");
			int ret=atol(Ret);
			if(ret<=0)
			{
				MessageBox(_T("返回记录为空"));
				return -3;
			}
			playtype=149;
			TiXmlElement * item=root->FirstChildElement();
			while(item)
			{
				//int idx=m_recordList.InsertItem(m_recordList.GetItemCount(),);
				//m_recordList.SetItemText(idx,1,);
				item=item->NextSiblingElement();
			}
		}
		break;
	}
	return 0;
}


BOOL CRecordSearch::OnInitDialog()
{
	CDialog::OnInitDialog();
	nIsRunning=1;

	m_DevTree.SetImageList(m_parent->m_pImgList,TVSIL_NORMAL);
	ReloadDeviceList(m_parent->m_devListDoc);

	int idx=m_VideoSrc.InsertString(0,_T("平台录像"));
	m_VideoSrc.SetItemData(idx,0);
	idx=m_VideoSrc.InsertString(1,_T("前端录像"));
	m_VideoSrc.SetItemData(idx,2);
	idx=m_VideoSrc.InsertString(2,_T("前端录像上传"));
	m_VideoSrc.SetItemData(idx,1);


	m_VideoSrc.SetCurSel(0);


	idx=m_StreamType.InsertString(0,_T("全部"));
	m_StreamType.SetItemData(idx,3);
	idx=m_StreamType.InsertString(1,_T("D1"));
	m_StreamType.SetItemData(idx,2);
	idx=m_StreamType.InsertString(2,_T("CIF"));
	m_StreamType.SetItemData(idx,1);
	m_StreamType.SetCurSel(0);
	OnCbnSelchangeCombo2();


	m_starttime.SetFormat(_T("yyyy/MM/dd HH:mm:ss"));
	m_endtime.SetFormat(_T("yyyy/MM/dd HH:mm:ss"));

	m_recordList.InsertColumn(0,_T("文件路径"),0,300);
	m_recordList.InsertColumn(1,_T("开始时间"),0,120);
	m_recordList.InsertColumn(2,_T("结束时间"),0,120);
	m_recordList.ModifyStyleEx(0,LVS_EX_GRIDLINES);
	//m_recordList.ModifyStyleEx(0,LVS_EX_FULLROWSELECT);
	//m_recordList.ModifyStyleEx(0,LVS_EX_CHECKBOXES);
	m_recordList.SetExtendedStyle(m_recordList.GetExStyle() | LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT | LVS_EX_CHECKBOXES);


	return TRUE;  // return TRUE unless you set the focus to a control
	// 异常: OCX 属性页应返回 FALSE
}

void CRecordSearch::OnDestroy()
{
	m_Player.Stop();
	nIsRunning=0;
	CDialog::OnDestroy();
}











int CRecordSearch::ReloadDeviceList(TiXmlDocument & m_devListDoc)
{
	int count=0;
	if(!m_devListDoc.Error())
	{//可以解释  
		m_DevTree.DeleteAllItems();
		TiXmlNode * groupnode=m_devListDoc.RootElement()->FirstChild();//.SelectNode("DevGroup");
		while(groupnode)
		{//<DevGroup Id="860021289896099" Name="第二组高清（355）设备"  DomainId="86002"  >
			const char * groupname=groupnode->ToElement()->Attribute("Name");
			HTREEITEM hGroupItem=m_DevTree.InsertItem(_bstr_t(groupname),NULL,NULL);
			m_DevTree.SetItemData(hGroupItem,(DWORD_PTR)groupnode);
			TiXmlNode * mastrenode=groupnode->FirstChild();
			while(mastrenode)
			{//<Master Id="86002M1289896122" Name="高清88195"  Type="3" GroupId="860021289896099" 
				//DomainId="86002" DevCount="1"  DeviceState="0"  IpAddr="0"  CommPort="1024"  
				//LoginName="admin"  LoginPassword="123456"  PTZRight="1"  SURVEILRight="1"  VideoReplayRight="0" 
				//AudioControlRight="1"  BCControlRight="1"  AlarmMngRight="0"  >
				TiXmlNode * cameranode=mastrenode->FirstChild();
				if(cameranode!=NULL)
				{
					const char * mastername=cameranode->ToElement()->Attribute("Name");
					HTREEITEM hParent=m_DevTree.InsertItem(_bstr_t(mastername),hGroupItem,NULL);
					m_DevTree.SetItemImage(hParent,1,1);
					m_DevTree.SetItemData(hParent,(DWORD_PTR)mastrenode);
					while(cameranode)
					{//<Camera Id="86002S1289896136" Name="IPC88195"  MasterId="86002M1289896122" Type="1"  IsDoubleStream="1"
						//WithPTZ="1"  WithAudioIn="1" WithAudioOut="1"  VSSId="3" ConnType="2"  MFSCmdIP="0" MFSCmdPort="0" 
						//VSSCmdIP="-2074564416" VSSCmdPort="554"  VisitStreamOption="0"  IpAddr="0"  CommPort="1024" 
						//LoginName="admin"  LoginPassword="123456" />
						const char * szCameraName=cameranode->ToElement()->Attribute("Name");
						HTREEITEM hCamearItem=m_DevTree.InsertItem(_bstr_t(szCameraName),hParent,NULL);
						m_DevTree.SetItemData(hCamearItem,(DWORD_PTR)cameranode);
						cameranode=cameranode->NextSibling();
						m_DevTree.SetItemImage(hCamearItem,6,6);
						count++;
					}
				}
				mastrenode=mastrenode->NextSibling();
			}
			groupnode=groupnode->NextSibling();
		}
	}
	return count;
}










void CRecordSearch::OnTvnSelchangedDevlist(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR);

	*pResult = 0;
	HTREEITEM hItem=m_DevTree.GetSelectedItem();
	if(hItem==NULL)
	{//没有选上
		return ;
	}
	TiXmlNode * node=(TiXmlNode *)m_DevTree.GetItemData(hItem);
	if(node)
	{//如果是双击到子设备，则进行播放
		TiXmlElement * nodeElm=node->ToElement();
		_bstr_t itemName=_bstr_t(nodeElm->Value());
		if(itemName==_bstr_t("Camera"))
		{//<Camera Id="86002S1289896136" Name="IPC88195"  MasterId="86002M1289896122" Type="1"  IsDoubleStream="1" 
			//WithPTZ="1"  WithAudioIn="1" WithAudioOut="1"  VSSId="3" ConnType="2"  MFSCmdIP="0" MFSCmdPort="0"  
			//VSSCmdIP="-2074564416" VSSCmdPort="554"  VisitStreamOption="0"  IpAddr="0"  CommPort="1024"  
			//LoginName="admin"  LoginPassword="123456" />

			if(m_parent->m_loginForm.nVideoReplayRight)
			{//视频播放权限

				TiXmlNode * pParentNode=nodeElm->Parent();//取主设备
				if(pParentNode==NULL)
				{
					MessageBox(_T("取主设备失败"),_T("取主设备失败"));
					return ;
				}

				const char * ip=nodeElm->Attribute("VSSCmdIP");//查看用户对此设备是否有权限访问
				const char * port=nodeElm->Attribute("VSSCmdPort");//查看用户对此设备是否有权限访问
				
				
				vssip=atol(ip);
				vssport=atol(port);

				TiXmlElement * parentElm=pParentNode->ToElement();
				const char * havevideoRight=parentElm->Attribute("VideoReplayRight");//查看用户对此设备是否有权限访问
				if(_bstr_t(havevideoRight)!=_bstr_t("1"))
				{
					MessageBox(_T("此用户没权限回放此视频"),_T("没权限"));
					return ;
				}
				selectDevId=_bstr_t(nodeElm->Attribute("Id"));//取得在观看的视频ID
				SetDlgItemText(IDC_DEVID,selectDevId);
				pSelectNode=nodeElm;
			}else
			{
				MessageBox(_T("此用户没有回放权限"),_T("无权限操作"));
			}
		}
	}
	*pResult = 0;
}




///来源类型更改了
void CRecordSearch::OnCbnSelchangeCombo2()
{
	int value=m_VideoSrc.GetCurSel();//来源类型
    switch(value)
    {
        case 0:
        {
			m_MediaType.ModifyStyle(0,WS_DISABLED);
			m_StreamType.ModifyStyle(0,WS_DISABLED);

			m_RecordType.ResetContent();
			m_MediaType.ResetContent();

			int idx=m_RecordType.InsertString(0,_T("全部"));
			m_RecordType.SetItemData(idx,7);
			idx=m_RecordType.InsertString(1,_T("定时录像"));
			m_RecordType.SetItemData(idx,1);
			idx=m_RecordType.InsertString(2,_T("报警录像"));
			m_RecordType.SetItemData(idx,2);
			m_RecordType.SetCurSel(0);

			idx=m_MediaType.InsertString(0,_T("全部"));
			m_MediaType.SetItemData(idx,7);
			idx=m_MediaType.InsertString(1,_T("音频和视频"));
			m_MediaType.SetItemData(idx,1);
			idx=m_MediaType.InsertString(2,_T("视频"));
			m_MediaType.SetItemData(idx,4);
			m_MediaType.SetCurSel(0);
            

        }
        break;
        case 2:
        {
			m_MediaType.ModifyStyle(WS_DISABLED,0);
			m_StreamType.ModifyStyle(WS_DISABLED,0);
            

			m_RecordType.ResetContent();
			m_MediaType.ResetContent();
			
			int idx=m_RecordType.InsertString(0,_T("全部"));
			m_RecordType.SetItemData(idx,7);
			idx=m_RecordType.InsertString(1,_T("定时录像"));
			m_RecordType.SetItemData(idx,1);
			idx=m_RecordType.InsertString(2,_T("IO报警"));
			m_RecordType.SetItemData(idx,2);
			idx=m_RecordType.InsertString(3,_T("移动侦测"));
			m_RecordType.SetItemData(idx,4);
			m_RecordType.SetCurSel(0);
            

            
			idx=m_MediaType.InsertString(0,_T("全部"));
			m_MediaType.SetItemData(idx,7);
			idx=m_MediaType.InsertString(1,_T("音频和视频"));
			m_MediaType.SetItemData(idx,1);
			idx=m_MediaType.InsertString(2,_T("视频"));
			m_MediaType.SetItemData(idx,4);
			idx=m_MediaType.InsertString(3,_T("图片"));
			m_MediaType.SetItemData(idx,2);
			m_MediaType.SetCurSel(0);

        }
        break;
        case 1:
        { 

			m_MediaType.ModifyStyle(WS_DISABLED,0);
			m_StreamType.ModifyStyle(WS_DISABLED,0);


			m_RecordType.ResetContent();
			m_MediaType.ResetContent();

			int idx=m_RecordType.InsertString(0,_T("全部"));
			m_RecordType.SetItemData(idx,7);
			idx=m_RecordType.InsertString(2,_T("IO报警"));
			m_RecordType.SetItemData(idx,2);
			idx=m_RecordType.InsertString(3,_T("移动侦测"));
			m_RecordType.SetItemData(idx,4);
			m_RecordType.SetCurSel(0);

			idx=m_MediaType.InsertString(0,_T("全部"));
			m_MediaType.SetItemData(idx,7);
			idx=m_MediaType.InsertString(1,_T("音频和视频"));
			m_MediaType.SetItemData(idx,1);
			idx=m_MediaType.InsertString(2,_T("视频"));
			m_MediaType.SetItemData(idx,4);
			m_MediaType.SetCurSel(0);
        }
        break;    
    }
}


CString GetComDataValue(CComboBox * box)
{
	int idx=box->GetCurSel();
	int value=box->GetItemData(idx);
	if(value<0)
	{
		return _T("-1");
	}
	CString msg;
	msg.Format(_T("%d"),value);
	return msg;
}


///搜索
void CRecordSearch::OnBnClickedSearch()
{
	pageid=0;
	SearchPage(0);
}


int CRecordSearch::SearchPage(int idx)
{
	CString devid;
	GetDlgItemText(IDC_DEVID,devid);
	CString startTime;
	CString endTime;
	CTime time;
	m_starttime.GetTime(time);
	startTime.Format(_T("%04d/%02d/%02d %02d:%02d:%02d")
		,time.GetYear(),time.GetMonth(),time.GetDay()
		,time.GetHour(),time.GetMinute(),time.GetSecond()
		);

	


	m_endtime.GetTime(time);
	endTime.Format(_T("%04d/%02d/%02d %02d:%02d:%02d")
		,time.GetYear(),time.GetMonth(),time.GetDay()
		,time.GetHour(),time.GetMinute(),time.GetSecond()
		);
	CString pagestr;
	pagestr.Format(_T("%d"),idx);
	_bstr_t filterstr="";
	filterstr=filterstr+"<Filter nCategory='"+GetComDataValue(&m_VideoSrc)+"' szDevId='"+devid+"' ";
	filterstr=filterstr+" nPageNum='"+pagestr+"' ";//第几页
	filterstr=filterstr+"  startTime='"+startTime+"' ";
	filterstr=filterstr+"  mediaType='"+GetComDataValue(&m_MediaType)+"' ";
	filterstr=filterstr+"  recordType='"+GetComDataValue(&m_RecordType)+"' ";
	filterstr=filterstr+"  streamType='"+GetComDataValue(&m_StreamType)+"' ";
	filterstr=filterstr+"  endTime='"+endTime+"' />";

	int ret=m_parent->m_plogObj->QueryRecord(_bstr_t(devid),filterstr);
	if(ret!=0)
	{
		MessageBox(_T("查询记录失败!"));
		return -1;
	}
	return 0;
}


void CRecordSearch::OnBnClickedNext()
{
	pageid++;
	SearchPage(pageid);
}

void CRecordSearch::OnBnClickedPrev()
{
	if(pageid<=0)
	{
		MessageBox(_T("当前为第一页!"));
		return ;
	}
	pageid--;
	SearchPage(pageid);
}

void CRecordSearch::OnNMDblclkSeartresult(NMHDR *pNMHDR, LRESULT *pResult)
{
	*pResult = 0;
	POSITION pos=m_recordList.GetFirstSelectedItemPosition();
	int idx=m_recordList.GetSelectionMark();
	if(idx>=0)
	{
		long ip;
		int port=554;
		//_bstr_t devid;
		CString did;
		GetDlgItemText(IDC_DEVID,did);
		//devid=did;
		//_bstr_t itemdata;
		CString itdata=m_recordList.GetItemText(idx,0);
		//itemdata=itdata;
		switch(playtype)//=141;
		{
		case 141:
			{
				m_Player.PlayVSSFile(vssip,vssport,_T("zfw"),did,itdata,1);
			}
			break;
		case 145:
			{
				m_Player.PlayVSSFile(vssip,vssport,_T("zfw"),did,itdata,1);
			}
			break;
		case 149:
			{//ipc文件
				m_Player.PlayVSSFile(vssip,vssport,_T("zfw"),did,itdata,3);
			}
			break;
		}
	}
}