/// <reference path="Extjs_Intellisense.js" />
/// <reference path="src/data/XmlStore.js" />
/// <reference path="addjs/Base.js" />
/// <reference path="addjs/XmlTreeLoader.js" />


var SearchRecordxmlReader=new Ext.data.XmlReader({
               record: 'Item'
               ,totalRecords: '@total'
           }, [
            {name: 'DevID', mapping: '@DevID'},
            {name: 'startTime', mapping: '@startTime'},
            {name: 'endTime', mapping: '@endTime'},
            {name: 'FilePath', mapping: '@FilePath'}
            ]);
            
var SearchRecordxmlstr='<Response Code="141" szDevId="755000012" TotalNum="3000" RecordNum="10" Result ="0"></Response>';
var VssFileResultGrid=null;
var SearchRecordxmlStore = new Ext.data.Store({
        proxy:new Ext.data.StringProxy({appendData:false,xml:SearchRecordxmlstr,reader:SearchRecordxmlReader}),//
        reader:SearchRecordxmlReader
	});
	
	
	
var lang_downloadfile=GetDefaultLang("lang_downloadfile","下载文件");
var lang_stopdownfile=GetDefaultLang("lang_stopdownload","停止下载");
var lang_redownloadfile=GetDefaultLang("lang_redownload","重新下载");

//[id(141), helpstring("方法")] HRESULT QueryRecord(BSTR strCameraId,BSTR strFilter,[out,retval] LONG* nResult);
//[id(142), helpstring("方法")] HRESULT DownloadRecord(BSTR strCameraId,LONG nCategory,BSTR strRecordUrl,BSTR strLocalPath,[out,retval] LONG* nResult);
function DownLoadFile(devid,file,type,htmlobj)
{
    var text=htmlobj.innerText;    
    var fileid=file.replace(/[^0-9a-zA-Z]+/g,"");
    var obj=$("file_"+fileid); 
    SetProValue(obj,-1,GetDefaultLang("lang_waitfordownload","等待下载"));
    if(text==lang_downloadfile || lang_redownloadfile==text)
    {
        var loginobj=$("loginobj");
        var ret=loginobj.DownloadRecord(devid,type,file,downloadfiledir); 
        WriteWebLog("下载["+devid+"]:"+file+",返回"+ret);
        if(ret!=0)
        {
            //alert("下载"+file+"失败！","下载失败",null,460);
            oldAlert(GetDefaultLang("lang_downloadfileerror24","下载{filename}失败！").replace("{filename}",file));
            SetProValue(obj,0,GetDefaultLang("lang_downloaderror25","下载失败"));
        }else
        {
            htmlobj.innerText=lang_stopdownfile;
        }
    }else if(lang_stopdownfile==text)
    {
        var loginobj=$("loginobj");
        var ret=loginobj.CancelDownloadRecord(devid,type,file);
        WriteWebLog("停止下载["+devid+"]:"+file+",返回"+ret);
        if(ret!=0)
        {
            oldAlert(GetDefaultLang("lang_stopdownloaderror25","停止下载{filename}失败！").replace("{filename}",+file));
            SetProValue(obj,0,GetDefaultLang("lang_downlaoderror26","下载失败"));
            //alert("停止下载"+file+"失败！","停止下载失败",null,460);
        }else
        {//CancelDownloadRecord
            htmlobj.innerText=lang_downloadfile;
        } 
    }else
    {
        return false;
    }
    return false;
}


function GetDeviceName(val,metaData, record, rowIndex, colIndex, store)
{
    var res=val;
    try
    {        
        var filegrid=GetSearchResultGrid();
        if(filegrid && filegrid.DevName!="")
        {
            res=filegrid.DevName;
        }
    }catch(eeee){}
    return res;
}

 
function SetProValue(obj,value,text,filetype)
{
    try
    {
        var html="<span class='cssclassprocess' style='width:"+value+"px'></span>"+text;
        if(value<=0)
        {
            html=text;
        }
        obj.innerHTML=html;
    }catch(eee){}
}



// replay loc file
function PlayLoacFile(filename)
{
    try
    {
        var obj=$("replay1");
        obj.SetDrawBorder(0);
        obj=$("replay2");
        obj.SetDrawBorder(0);
        lastRealPlayIdx=GetReplayPlayerIdx();
        obj=$("replay"+lastRealPlayIdx);
        var nowFile=""+filename;
        ShowPlayBack(lastRealPlayIdx,nowFile);
        var ret=obj.PlayFile(nowFile);
    }catch(eee){}
}


function ShowDownLoadResult(devid,filepath,AviFilePath,retva)
{
    var grid=GetSearchResultGrid();
    if(lastSearchDeviceId!=devid)
    {//与当前ID不一样，则不显示进度
           return false;
    }
    var fileid=filepath.replace(/[^0-9a-zA-Z]+/g,"");
    var obj=$("file_"+fileid); 
    var linkobj=$("link_"+fileid);
    if(linkobj && linkobj.innerText)
    {
        linkobj.innerText=lang_redownloadfile;
    }
    if(retva===0 || retva==="0")
    {
        SetProValue(obj,-1,"<a href='#'  class='linka' onclick='PlayLoacFile(\"'+AviFilePath+'\");' >"+GetDefaultLang("lang_playlocfile","播放本地文件")+"</a> ");
    }else
    {
        SetProValue(obj,-1,GetDefaultLang("lang_covfileerror28","转换失败"));
    }
}


function ShowDownLoadProccess(devid,filepath,value,nCode)
{//lastSearchDeviceId
    var grid=GetSearchResultGrid();
    if(lastSearchDeviceId!=devid)
    {//与当前ID不一样，则不显示进度
           return false;
    }
    var fileid=filepath.replace(/[^0-9a-zA-Z]+/g,"");
    var obj=$("file_"+fileid);
    if(obj && obj.getAttribute("filetype")!="upload")
    {
        if(value<0)
        {//失败了
            //Progress=0;//失败了
        }else if(nCode==220)
        {//
            value=value/2;
        }else
        {
            value=value/2+50;
        }
    }
    value=Math.floor(value);
    if(value>=0)
    {
        if(value>=100)
        {
            value=100;            
            var linkobj=$("link_"+fileid);    
            if(linkobj && linkobj.innerText)
            {
                linkobj.innerText=lang_redownloadfile;
            }
        }
        if(obj && obj.style)
        {
            SetProValue(obj,1+value,""+value+"%");
        }
    }else
    {//下载失败
        var linkobj=$("link_"+fileid);    
        if(linkobj && linkobj.innerText)
        {
            linkobj.innerText=lang_redownloadfile;
        }
        if(obj && obj.style)
        {
            SetProValue(obj,0,GetDefaultLang("lang_downloaderror30","下载失败"));
        }
    }   
}


function PlaySelectFile(devId,filepath,type,htmlobj)
{  
    try
    {
        $("PlayBackFileNameDiv").innerText=filepath;
        var node=null;
        var realtree=GetRelaTimeTree();
        if(realtree && realtree.root)
        {
            node=realtree.root.findChild("id","rc"+devId,true);
        }
        if(node==null  || node.attributes==null || node.attributes["Id"]!=devId)
        {
            return false;   
        }
        var ip=parseInt(node.attributes["VSSCmdIP"]);
        var port=parseInt(node.attributes["VSSCmdPort"]);
        var obj=$("replay1");
        obj.SetDrawBorder(0); 
        obj=$("replay2");
        obj.SetDrawBorder(0); 
        
       
        lastRealPlayIdx=GetReplayPlayerIdx();
        obj=$("replay"+lastRealPlayIdx);        
        
        loginUser=""+loginUser;
        devId=""+devId;
        switch(type)
        {
            case 0:
            case 1://报警录像和平台录像完全一样
            {
                ShowPlayBack(lastRealPlayIdx,filepath);
                obj.Stop();
                var ret=obj.PlayVSSFile(ip,port,loginUser,devId,filepath,1);
            }
            break;
            case 2:
            {
                ShowPlayBack(lastRealPlayIdx,filepath);
                obj.Stop();
                var ret=obj.PlayVSSFile(ip,port,loginUser,devId,filepath,3);
            }
            break;
        }
    }catch(ee)
    {
        
    }    
}



//(value, metaData, record, rowIndex, colIndex, store)
function ShowOprHtml(val,metaData, record, rowIndex, colIndex, store)
{
    var html="";
    if(have_VideoReplayRight)
    {
        var grid=GetSearchResultGrid();
        var fileid=val.replace(/[^0-9a-zA-Z]+/g,"");
        html+= "<a id='link_"+fileid+"' onclick='DownLoadFile(\""+lastSearchDeviceId+"\",\""+val+"\","+lastSearchRecordTypeId+",this);' href='#'  class='linka'  >"+lang_downloadfile+"</a> ";
        //if(grid.RecordType!=1)
        if(val.replace(".jpg","").replace(".JPG","")==val)
        {
            html+= "<a onclick='PlaySelectFile(\""+lastSearchDeviceId+"\",\""+val+"\","+lastSearchRecordTypeId+",this);' href='#'  class='linka'  >"+GetDefaultLang("lang_playfile","播放")+"</a> ";
        }
    }else
    {
        html=GetDefaultLang("lang_notallowthisopr","无权操作");
    }
    return html;
}

function ShowFilePath(val,metaData, record, rowIndex, colIndex, store)
{
    return "<span style='width:16px;' >"+val+"</span>";
}

function ShowStatus(val,metaData, record, rowIndex, colIndex, store)
{
    var fileid=val.replace(/[^0-9a-zA-Z]+/g,"");
    var typemsg="upload";
    if(lastSearchRecordTypeId==2)
    {//说明是平台文件，不用上传即可以下载
        typemsg="";
    }
    return "<span  filetype='"+typemsg+"'  id='file_"+fileid+"' ></span>";
}

  
function GetSearchResultGrid()
{
    if(VssFileResultGrid==null)
    {       
        VssFileResultGrid =new Ext.grid.GridPanel({
            DevId:"",
            DevName:"",
            title:GetDefaultLang("lang_searchresultlist",'搜索结果列表'),
            SelectDevNode:{},
            nowpage:0,
            RecordType:0,
            havelastPage:false,
            store: SearchRecordxmlStore,
            columns: 
            [   
                {header: GetDefaultLang("lang_devname",'设备名称'), width: 100, sortable: true,renderer:GetDeviceName, dataIndex: 'DevId'},
                {header: GetDefaultLang("lang_filepath",'文件路径'), width: 260, sortable: false,renderer:ShowFilePath,  dataIndex: 'FilePath'},
                {header: GetDefaultLang("lang_starttime",'开始时间'), width: 128, sortable: false, dataIndex: 'startTime'},
                {header: GetDefaultLang("lang_endtime",'结束时间'), width: 128,  sortable: false, dataIndex: 'endTime'},
                {header: GetDefaultLang("lang_useropr",'操作'), width: 128, ssortable: false,renderer:ShowOprHtml, dataIndex: 'FilePath'},
                {header: GetDefaultLang("lang_downloadstatus",'下载状态'), width: 150,  sortable: false,renderer:ShowStatus, dataIndex: 'FilePath'}
            ],
            stripeRows: true,
            width:.85,
            height:450
        });        
    }
    return VssFileResultGrid;
}




function ShowSearchResultByXml(xml)
{
    var filegrid=GetSearchResultGrid();
    var doc=CreateXml(xml);
    if(doc && doc.documentElement)
    {
        doc=doc.documentElement;
    }
    if(doc)
    {
        var code=doc.getAttribute("Code");
        filegrid.DevName=filegrid.DevId=doc.getAttribute("DevId");//doc["szDevId"];
        //filegrid.DevName=doc.getAttribute("DevName");//doc["szDevId"];
                
        try
        {
            var node=null;
            var realtree=GetRelaTimeTree();
            if(realtree && realtree.root)
            {
                node=realtree.root.findChild("id","rc"+filegrid.DevId,true);
            }
            if(node)
            {
                filegrid.DevName=node.attributes["Name"];
            }
        }catch(eeee){}
        
        switch(code)
        {
            case 141:
            case "141":
            {
                filegrid.RecordType=0;
            }
            break;
            case 145:
            case "145":
            {
                filegrid.RecordType=1;
            }
            break;
            case 149:
            case "149":
            {
                filegrid.RecordType=2;
            }
            break;
        }
    }
    
    try
    {
        var TotalNum=parseInt(doc.getAttribute("TotalNum"));
        var RecordNum=parseInt(doc.getAttribute("RecordNum"));
        var allpage=Math.floor((TotalNum+9)/10);//第0页,共0页
        var nowpage=lastSearchPageNumber;        
        if(allpage>0)
        {
            
        }else
        {
            allpage=0;
            nowpage=-1;
        }
        var playbackform=GetSearchPlayBackForm();
        if(playbackform.haveNextPage && RecordNum==10)
        {//说明返回的记录为10条，此时，要判断是否为最后一页
            if(allpage==(1+nowpage) )
            {
                playbackform.haveNextPage=false;
            }
        } 
        main_text_showpage.setText(GetDefaultLang("lang_searchrespage","第{idx}页,共{all}页").replace("{idx}",(1+nowpage)).replace("{all}",allpage));
    }catch(eee){}
    
    filegrid.store.proxy.xml=xml;
    filegrid.store.load();
    if(0>10)
    {
        filegrid.havelastPage=true;
    }else
    {
        filegrid.havelastPage=false;
    }           
}















