/// <reference path="../Extjs_Intellisense.js" />
/// <reference path="Base.js" />
/// <reference path="XmlTreeLoader.js" />

connectwhileclick=false;



//<Response Code="203" DevId="755000002" Timestamp="2940684247" Type="7" Description="/mnt/mmc0/schedule/2010/05/19/143643-av-1.avi"  Result ="0"/>
//<Response Code="204" DevId="755000012" Timestamp="2147706207" Type="257" IsRaise="1" AlarmLevel="1" Description="motion detect"  Result ="0"/>


var __lastDevMsgXml="";
var tempnewdevmsgXml="";
var last_show_dev_xml="";

function ReLoadXmlData()
{
    if(__lastDevMsgXml!="")
    {
        window.setTimer("ReLoadXmlData();",1000);
        return ;
    }
    if(tempnewdevmsgXml!="")
    {
        var tempxml=tempnewdevmsgXml;
        tempnewdevmsgXml="";
        OnLoginObj(33,10240,tempxml);
    }
}


function OnTimerCloseNode()
{   
    var realtree=GetRelaTimeTree();
    realtree.root.firstChild.beginUpdate(); 
    realtree.root.firstChild.collapseChildNodes(true,true);
    realtree.root.firstChild.endUpdate(); 
}


function OnLoginObj(nCode, nDataLen, XmlData)
{
    //WriteWebLog("收到事件="+nCode+",XmlData="+XmlData);
    nCode=parseInt(nCode);
    var realtree=GetRelaTimeTree();
    switch(nCode)
    {//225
        case 83:
        {
            ShowDevStatusByString(XmlData);
        }
        break;
        case 86:
        {
            //<Response Code="86" CameraRegInfo="{devid1:reginfo1,devid2:reginfo2,...}" Result ="0" />
            //retginfo = bDoubleStream + (bWithPTZ*10) + (bWithAudioIn*100) + (bWithAudioOut*1000)            
            var doc=CreateXml(XmlData);
            if(doc==null || doc==undefined )
            {
                WriteWebLog("无法解释86XML内容:"+XmlData);
                delete XmlData;
                return false;
            }     
            var deviceInfo=doc.getAttribute("CameraRegInfo");//设备ID
            OnDeviceInfoChange(deviceInfo);            
        }
        break;
        case 33:
        {
            if(!__user_function_to_readcamera)
            {
//               if(__lastDevMsgXml!="")
//               {
//                   tempnewdevmsgXml=XmlData;
//                   return ;
//               }
//               if(last_show_dev_xml==XmlData)
//               {
//                   return ;
//               }
                //last_show_dev_xml=XmlData;
                //__lastDevMsgXml=XmlData;                
                var realtree=GetRelaTimeTree();
                var allXml="<xml>"+XmlData+"</xml>";
                WriteWebLog("开始读取列表IPC，长度为:"+allXml.length);
                if(realtree && realtree.root)
                {
                    realtree.root.removeAll();//=new Ext.tree.TreeNode({id: 'root_camera',text : 'root',draggable : false,autoScroll: false,expanded : false});//.removeAll();
                }
                cameraReader1.LoadFromXml(allXml,realtree.root);               
                //UpdateDevStatus();
                //StartUpdateDevStatusTimer();//启动定时更新列表状态
                userConfigStr="";//755000032,1\r\n755000012,0\r\n755000002,1\r\n755000042,1\r\n";                           
                for(var idx=1;idx<=Max_play_Count;idx++)
                {
                    var nowconfig="0,0";
                    try
                    {
                        nowconfig=loginObj.GetPlaySchemeInfo("",idx);
                        nowconfig=nowconfig.replace(" ",",");
                    }catch(eee)
                    {
                        nowconfig="0,0";
                    }
                    userConfigStr+=nowconfig+"\r\n";
                }
                try
                {
                    window.setTimeout("LoadConfingData(userConfigStr);",100);
                }catch(eee)
                {
                    PlayVideoByConfig(userConfigStr);
                    CheckPlayList(false);
                }                
                try
                {//
                    realtree.root.firstChild.collapseChildNodes(true,true);
                    //realtree.collapseAll();                    
                    //realtree.expand(realtree.root.firstChild);
                    //realtree.root.firstChild.beginUpdate(); 
                    //realtree.root.firstChild.collapseChildNodes(true,true);
                    //realtree.root.firstChild.endUpdate(); 
                    //realtree.root.firstChild.expandChildNodes(true,false);
                    //window.setTimer("OnTimerCloseNode();",5000);
                    
                }catch(ee){}                
                
                //ResizeLeftTreePlan();
//                if(tempnewdevmsgXml!="")
//                {//新数据已来了
//                    ReLoadXmlData();
//                }
//                __lastDevMsgXml="";

            }
        }
        break;
        case 93:
        {//对讲事件返回
            var doc=CreateXml(XmlData);
            if(doc==null || doc==undefined )
            {
                WriteWebLog("无法解释93XML内容:"+XmlData);
                delete XmlData;
                oldAlert(GetDefaultLang("lang_xmlerror50","播放失败,无法解释226XML内容"));
                return false;
            }     
            var DevId=doc.getAttribute("DevId");//设备ID  
            var result=doc.getAttribute("Result");//设备ID  
            if(LastTackCameraId!="" && DevId==DevId)
            {
                if(result==0 || result=="0")
                {//成功
                    
                }else
                {
                    main_but_startaudio.setText(GetDefaultLang("lang_startaudio","启动对讲"));
                    oldAlert(GetDefaultLang("lang_startaudioerror51","请求对讲失败"));
                }
            }
        }
        break;
        case 226:
        {// <Response Code="226" sDatFile=""   sAviFile=""  Result "" />    
            var doc=CreateXml(XmlData);
            if(doc==null || doc==undefined )
            {
                WriteWebLog("无法解释226XML内容:"+XmlData);
                delete XmlData;
                oldAlert(GetDefaultLang("lang_xmlerror53","播放失败,无法解释226XML内容"));
                return false;
            }     
            var DevId=doc.getAttribute("DevId");//设备ID  
            var retva=doc.getAttribute("Result");//设备ID
            var DatFilePath=doc.getAttribute("sDatFile");//设备ID
            var AviFilePath=doc.getAttribute("sAviFile");//设备ID
            ShowDownLoadResult(DevId,DatFilePath,AviFilePath,retva);
        }
        break;    
        case 220://CodeIpcFileUploadStatus = 220,//<0失败，0～100进度
		case 224://CodeFileDownloadStatus = 224,//<0失败，0～100进度
        {//<Response Code=""  DevId=""  FilePath="" Progress="" Result ="" />            
            var doc=CreateXml(XmlData);
            if(doc==null || doc==undefined )
            {
                WriteWebLog("无法解释220或224XML内容:"+XmlData);
                delete XmlData;
                oldAlert(GetDefaultLang("lang_xmlerror54","播放失败,无法解释220或224XML内容"));
                return false;
            }
            var DevId=doc.getAttribute("DevId");//设备ID
            var FilePath=doc.getAttribute("FilePath");//设备ID
            var Progress=doc.getAttribute("Progress");//设备ID
            Progress=parseInt(Progress);
            ShowDownLoadProccess(DevId,FilePath,Progress,nCode);
        }
        break;
        case 213:
        {//云台被抢占或视频被抢占
            //"<Response Code="213" TakebackType="1" DevId="860030012" grabedByUser=""  Result ="0"/>"           
//            #define VS_TAKEBACK_TYPE_STREAM 0
//            #define VS_TAKEBACK_TYPE_PTZ 1
//            #define VS_TAKEBACK_TYPE_AUDIO_TALK 2
//            #define VS_TAKEBACK_TYPE_AUDIO_BROARDCAST 3
            var doc=CreateXml(XmlData);
            if(doc==null || doc==undefined )
            {
                WriteWebLog("无法解释213XML内容:"+XmlData);
                delete XmlData;
                oldAlert(GetDefaultLang("lang_xmlerror55","播放失败,无法解释213XML内容"));
                return false;
            }                     
            var DevId=doc.getAttribute("DevId");//设备ID            
            var code=doc.getAttribute("TakebackType");//设备ID
            var groupnode=realtree.root.findChild("id","rc"+DevId,true);
            var DeviceName="";
            if(groupnode)
            {
                DeviceName=groupnode.text;
            }
            if(code=="0" || code==0)
            {
                oldAlert(GetDefaultLang("lang_errormsg60","{devname}视频被抢占！").replace("{devname}",DeviceName));
            }else if(code=="1" || code==1)
            {
                oldAlert(GetDefaultLang("lang_errormsg61","{devname}云台控制被抢占！").replace("{devname}",DeviceName));
            }else if(code=="2" || code==2)
            {
                if(LastTackCameraId!="")
                {//对讲被抢占了，直接去掉
                    LastTackCameraId="";
                }
                main_but_startaudio.setText(GetDefaultLang("lang_startaudio","启动对讲"));
                oldAlert(GetDefaultLang("lang_errormsg62","{devname}语音对讲被抢占！").replace("{devname}",DeviceName));
            }else if(code=="3" || code==3)
            {
                oldAlert(GetDefaultLang("lang_errormsg63","{devname}语音广播被抢占！").replace("{devname}",DeviceName));
            }
        }
        break;
        case 225:
        {//状态改变信息  <Response Code="225"  DevId="devid"  State=""  Result ="0" />";
            var doc=CreateXml(XmlData);
            if(doc==null || doc==undefined )
            {
                WriteWebLog("无法解释225XML内容:"+XmlData);
                delete XmlData;
                oldAlert(GetDefaultLang("lang_xmlerror70","播放失败,无法解释225XML内容"));
                return false;
            }
            var DevId=doc.getAttribute("DevId");//设备ID
            var State=doc.getAttribute("State");//设备ID
            
            var realtree=GetRelaTimeTree();
            if(realtree && realtree.root)
            {
                var groupnode=realtree.root.findChild("id","rg"+DevId,true);
                if(groupnode && groupnode.childNodes && groupnode.childNodes.length>0)
                {
                    var imgurl=getTreeNodeStatusFile(State,true);//"";
                    var nodeui=groupnode.getUI();
                    var img=nodeui.getIconEl();//img对象
                    if(img && img.src)
                    {//"resources/images/camera/mastnodeon.gif";
                        var srcurl=img.src;
                        if(srcurl.replace(imgurl,"")==srcurl)
                        {                        
                            img.src=imgurl;
                        }
                    }
                    imgurl=getTreeNodeStatusFile(State,false);
                    for(var camidx=0;camidx<groupnode.childNodes.length;camidx++)
                    {
                        var node=groupnode.childNodes[camidx];
                        var nodeui=node.getUI();
                        var img=nodeui.getIconEl();//img对象
                        if(img && img.src)
                        {
                            var srcurl=img.src;
                            if(srcurl.replace(imgurl,"")==srcurl)
                            {                        
                                img.src=imgurl;
                            }
                        }
                    }
                }
            }
            break;
        }
        case 203:
        {//实时事件
            //WriteWebLog("203:"+XmlData);
            ShowAlarmByXml(XmlData);
            break;
        }
        case 204:
        {//实时报警
            //WriteWebLog("204:"+XmlData);
            ShowAlarmByXml(XmlData);
            break;
        }
        case 91:
        {//云台申请响应<Response Code="91" CameraId="755000012" Result ="0"/>
            var doc=CreateXml(XmlData);
            if(doc==null || doc==undefined )
            {
                WriteWebLog("无法解释91XML内容:"+XmlData);
                delete XmlData;
                oldAlert(GetDefaultLang("lang_xmlerror71","请求云台控件错误,无法解释91XML内容"));
                return false;
            }
            var DevId=doc.getAttribute("CameraId");//设备ID
            var CmdInvOk=parseInt(doc.getAttribute("Result"));
            if(CmdInvOk===0)
            {//记下当前成功申请云台控制
                if(connectwhileclick)
                {
                    LastCmdOkDevId=DevId;
                    WriteWebLog("请求云台:"+DevId+"成功!");
                    //UpdatePresetList();
                }else
                {
                    if(LastRecvPtzString[DevId]=="")
                    {
                        WriteWebLog("请求云台:"+DevId+"成功!");
                        //UpdatePresetList(); 
                    }
                }
            }else
            {
                if(connectwhileclick)
                {
                    LastCmdOkDevId="";
                }
                WriteWebLog("请求云台:"+DevId+"失败!");
            }
        }
        break;
        case 92:
        {//云台命令响应<Response Code="92" IPCID="" DataLen="0" PTZResponse=""  Result ="20503"/>
        //"<Response Code="92" IPCID="755000012" DataLen="1411392049" PTZResponse="" Name="Camera_0001" Type="1" IsDoubleStream="1" WithPTZ="1" WithAudioIn="1" WithAudioOut="1" VSSId=""  Result ="0"/>"
            var doc=CreateXml(XmlData);
            if(doc==null || doc==undefined )
            {
                WriteWebLog("无法解释92XML内容:"+XmlData);
                delete XmlData;
                oldAlert(GetDefaultLang("lang_xmlerror72","云台命令响应错误,无法解释92XML内容"));
                return false;
            }
            var DevId=doc.getAttribute("DevId");//设备ID
            var CmdInvOk=parseInt(doc.getAttribute("Result"));
            if(DevId==LastCmdOkDevId)
            {//要处理
                var res=doc.getAttribute("PTZResponse");//响应结果
                var nodedoc=CreateXml(res);
                var bodynode=GetObjByName(nodedoc,"MESSAGE_BODY",0);
                if(bodynode)
                {
                    var text=bodynode.text;
                    UpdatePresetListByStr(text,DevId);
                }else
                {
                    UpdatePresetListByStr(res,DevId);
                }
            }
        }
        break;
        case 227:
        {
            var doc=CreateXml(XmlData);
            if(doc==null || doc==undefined )
            {
                WriteWebLog("无法解释93XML内容:"+XmlData);
                delete XmlData;
                oldAlert(GetDefaultLang("lang_xmlerror74","请求对讲返回XML无法解释"));
                return false;
            }
            var DevId=doc.getAttribute("szDevId");//设备ID
            var Code=parseInt(doc.getAttribute("Code"));
            var nMsgType=parseInt(doc.getAttribute("nMsgType"));
            var strDesc=(doc.getAttribute("strDesc"));
            if(DevId==LastTackCameraId)
            {//要处理
                switch(Code)
                {
                    case 93:
                    {//对讲失败
                        LastTackCameraId="";
                        try
                        {
                            main_but_startaudio.setText(GetDefaultLang("lang_startaudio","启动对讲"));
                        }catch(eevvd){}
                        oldAlert(GetDefaultLang("lang_errormsg80","启动对讲失败,错误信息为:{errormsg}").replace("{errormsg}",strDesc));
                    }
                    break;
                    case 1:
                    {
                        
                    }
                    break;
                    case 2:
                    {
                        
                    }
                    break;
                    case 3:
                    {
                           
                    }
                    break;
                }
            }      
        }
        break;
        case 81:
        {//播放流事件
            //LastPlayModeNeedShow[cameraId]=needshowError;
            WriteWebLog("81XML内容:"+XmlData);
            var doc=CreateXml(XmlData);
            if(doc==null || doc==undefined )
            {
                WriteWebLog("无法解释81XML内容:"+XmlData);
                delete XmlData;
                oldAlert(GetDefaultLang("lang_xmlerror85","播放失败,无法解释81XML内容"));
                return false;
            }
            var myplayid=selectPlayerId;
            var needShow=false;
            var DevId=doc.getAttribute("DevId");//设备ID
            
            for(var idx=1;idx<=Max_play_Count;idx++)
            {
                var playidmsg="player"+idx;
                if(playobjDevIdList[playidmsg]==DevId)
                {
                    myplayid=playidmsg;
                    break;
                }
            }
                                    
            needShow=LastPlayModeNeedShow[DevId];
            var result=""+doc.getAttribute("Result");
            if(result!="0")
            {
                if(needShow)
                {
                    switch(needShow)
                    {
//                        case 20502:
//                        {
//                            
//                        }
//                        break;
                        default:
                        {
                            oldAlert(GetDefaultLang("lang_errormsg90","播放失败,错误代码:{code}").replace("{code}",result));
                        }
                        break;
                    }
                }
                delete XmlData;
                return;
            }
            if(myplayid==undefined || myplayid=="" || (!GetPlayerById(myplayid)) )
            {
                myplayid="player1";
            }
            var play=GetPlayerById(myplayid);
            var nFsmType=parseInt(doc.getAttribute("nFsmType"));
            var groupip=0;
            var videoport=554;
            if(nFsmType==1)
            {//1不是组播,2是组播                            
                videoport=parseInt(doc.getAttribute("LocalPort"));
                groupip=0;
            }else if(nFsmType==2)
            {
                groupip=parseInt(doc.getAttribute("MulticastIP"));
                videoport=parseInt(doc.getAttribute("MulticastPort"));
            }else
            {
                
            }
            var treenode=realtree.root.findChild("id","rc"+DevId,true);
            var HeartBeatIP=0;
            var HeartBeatPort=0;
            if(treenode)
            {
                var connectType=treenode.attributes["ConnType"];
                HeartBeatIP=parseInt(treenode.attributes["VSSCmdIP"]);
                if(connectType==="0" || connectType===0)
                {//vss
                    
                }else if(connectType==="1" || connectType===1)
                {//mfs
                    HeartBeatIP=parseInt(treenode.attributes["MFSCmdIP"]);
                }else  if(connectType==="2" || connectType===2)
                {//connect ipc
                    
                }
                //HeartBeatPort=parseInt(treenode.attributes["VSSCmdPort"]);
                HeartBeatPort=parseInt(doc.getAttribute("MediaSendPort"));
            }            
            var videoparam=doc.getAttribute("VideoParam");
            var audioparam=doc.getAttribute("AudioParam");
            var videolen=doc.getAttribute("VideoParamLen");
            var audiolen=doc.getAttribute("AudioParamLen");
            var nSvrInstHole=doc.getAttribute("SrcInst");
            var nIsTcpConnect=doc.getAttribute("nTransPro");//0是UDP,1是TCP
            
            
            if(nIsTcpConnect===1 ||nIsTcpConnect==="1" )
            {
                play.SetConnectType(-1);
            }else
            {
                play.SetConnectType(0);
            }
            var  ret;
            if(nSvrInstHole>0)
            {
                
            }else
            {
                nSvrInstHole=1;
            }
            
            
//            var player2=GetPlayerById("player2");            
//            player2.SetConnectType(-1);
//            ret=player2.Stop();
//            var mediaType=parseInt(doc.getAttribute("MediaType"));//0x0101 后面是视频，前面是音频                                    
//            var haveaudio=((mediaType & 0x0100)!=0);
//            ret=player2.SetVideoParameter(groupip,videoport,HeartBeatIP,59999,nSvrInstHole);
//            ret=player2.SetupDecode(videoparam,videolen,0);
//            if(haveaudio)
//            {
//                ret=player2.SetupDecode(audioparam,audiolen,1);
//            }
//            player2.Play();
//            

            ret=play.Stop();
            var mediaType=parseInt(doc.getAttribute("MediaType"));//0x0101 后面是视频，前面是音频                                    
            var haveaudio=((mediaType & 0x0100)!=0);
            ret=play.SetVideoParameter(groupip,videoport,HeartBeatIP,HeartBeatPort,nSvrInstHole);
            ret=play.SetupDecode(videoparam,videolen,0);
            if(haveaudio)
            {
                ret=play.SetupDecode(audioparam,audiolen,1);
            }
            play.Play();
            var soundtext=GetDefaultLang("lang_startsound","播放声音");
            if(__playAudioDevId!="" && __playAudioDevId==DevId)
            {
                play.SetAudioOn(-1);                          
                if(myplayid==selectPlayerId)
                {// 选择了正在播放的 
                    soundtext=GetDefaultLang("lang_stopsound","停止声音");
                }
            }else
            {
                play.SetAudioOn(0);
            }
            main_but_stopsound.setText(soundtext);
        }
        break;
        
        case 228:
        {//导常处理 <Response Code="228"  nReason="" nMsgType="" DevId=“”></Response>
            var doc=CreateXml(XmlData);
            if(doc==null || doc==undefined )
            {//0超时，-1接收异常，1发送异常 
                WriteWebLog("无法解释"+nCode+"XML内容:"+XmlData);
                delete XmlData;
                return false;
            }
            var nMsgType=parseInt(doc.getAttribute("nMsgType"));
            var devid=doc.getAttribute("DevId");
            if(devid==lastSearchDeviceId)
            {
                if(nMsgType==4865  ||  4865==nMsgType || nMsgType==4881)
                {//0超时，-1接收异常，1发送异常
                    ShowSearchResultByXml("<data></data>");
                    var ErrorCode=nMsgType=parseInt(doc.getAttribute("nReason"));
                    if(ErrorCode===0)
                    {
                        var timeoutsearcherror=GetDefaultLang("lang_timeoutsearcherror","查询录像超时");
                        oldAlert(timeoutsearcherror);
                    }else if(ErrorCode===-1)
                    {
                        var recvsearcherror=GetDefaultLang("lang_recvrecordsearcherror","查询录像接收异常");
                        oldAlert(recvsearcherror);
                    }else if(ErrorCode===-2)
                    {
                        var sendsearcherror=GetDefaultLang("lang_sendsearcherror","查询录像发送导常");
                        oldAlert(sendsearcherror);
                    }
                    delete XmlData;
                    return false;
                }
            }
            /*
            case MSG_CM_QUERY_FILE: //查询平台录像 4865
            case MSG_CM_IPC_ALARMUP_QUERY_FILE: //查询告警上传录像 4873
            case MSG_CLIENT_MC_DVRRECORD_QUERY: //查询前端录像 4881
            */
        }
        break;
        case 141:
        case 145:
        case 149:
        case "141":
        case "145":
        case "149":
        {//查询录像记录影响
            var doc=CreateXml(XmlData);            
            if(doc==null || doc==undefined )
            {//
                WriteWebLog("无法解释"+nCode+"XML内容:"+XmlData);
                oldAlert(GetDefaultLang("lang_serachreserror100","搜索返回结果错误{ecode}，无法解释XML!").replace("{ecode}",nCode),GetDefaultLang("lang_notfindrecord","没有记录"));
                delete XmlData;
                return false;
            }
            var devid=doc.getAttribute("DevId");
            if(lastSearchDeviceId==devid)
            {
                var recCount=0;//doc.getAttribute("TotalNum")
                if(doc!=null && doc.attributes!=null )
                {
                    recCount=parseInt(doc.getAttribute("TotalNum"));
                }
                var result=parseInt(doc.getAttribute("Result"));
                if(recCount<=0 || recCount==NaN)
                {
                    ShowSearchResultByXml("<data></data>");
                    oldAlert(GetDefaultLang("lang_notfindrecord101","没有找到符合条件的记录!"),GetDefaultLang("lang_notfindrecord","没有记录"));
                    delete XmlData;         
                    return ;
                }else if(result!=0)
                {
                    ShowSearchResultByXml("<data></data>");
                    oldAlert(GetDefaultLang("lang_seracherror102","查询失败,错误代码:{code}!").replace("{code}",result),GetDefaultLang("lang_notfindrecord","没有记录"));
                    delete XmlData;
                    return ;
                }
                var nowCount=0;
                nowCount=parseInt(doc.getAttribute("RecordNum"));
                var grid=GetSearchPlayBackForm();
                if(nowCount<10)
                {
                    grid.haveNextPage=false;
                }else
                {
                    grid.haveNextPage=true;
                }
                ShowSearchResultByXml(XmlData);
            }
        }
        break;
    }
    delete XmlData;
}












