var windowId, proName = window.location.pathname.split("/")[1],
    sysUrl = "http://" + window.location.host + "/" + proName, toEdit;
var proName = window.location.pathname.split("/")[1];
var sysUrl = "http://" + window.location.host + "/" + proName;
var detailWindowId = $.uniqueId();
//var id = $.getUrlParam("id");
var cacheStatusObj = {};
var AllTree = null;
var videoalarmTree = null;
var arrs=[];
$(function () {
    initDefault();
    ywVideo();
    //initTreePanel();
});

//默认
function initDefault() {
    /*
    $('#xx5').combobox({
        url:'xtclAction!query_Xtcl.do?csdl=xx5&page=1&rows=1000',
        textField:"csmc",
        valueField:"csdm",
        panelWidth:148,
        loadFilter:function(data){
            //data.unshift({"csmc":"选择","csdm":""});
            return data;
        }
    });
    $("#xx6").textbox("setValue",records.xx6);
    $("#xx7").combobox("setValue",records.xx7);
    $("#xx8").combobox("setValue",records.xx8);
    $("#xx9").datetimebox("setValue",$.getNowTime());
    $("#xx10").datetimebox("setValue",$.getTodayStart('00:00:00',-3));//往前推3天  +'00:00:00'
    $("#xx11").datetimebox("setValue",$.getTodayEnd());//当天 +'23:59:59'
    $("#xx12").datetimebox("setValue",$.getDateNumToStr(records.xx12));
    $("#xx13").numberbox("setValue",records.xx13);
    */

    $.ajax({
        type: 'post',
        dataType: 'json',
        url: 'ptxzsAction!query_PtxzsTree.do',
        data: {
            order: " order by jdpx asc "
        },
        success: function (data) {
            videoalarmTree = $('#videoalarm').comboTree({
                source: data,
                isMultiple: true,
                cascadeSelect: true,
                collapse: false
            });
        }
    });


    initGrid();
}

//查询条件
function getQueryParams() {
    var sParam = {};
    sParam.LIKEchannelname = $("#LIKEchannelname").text();
    sParam.LIKEvideonum = $("#LIKEvideonum").text();
    sParam.channelnum = $("#channelnum").text();
    sParam.LIKEremarks = $("#bz").textbox('getValue');
    sParam.emptyremarks =$('#combobz').combobox('getValue');
//	sParam.currentstate = $("#currentstate").combobox("getValue");
    var chosed = $('#currentstate').combobox('getValues');
    var currentstate = "";
    // for (var i in chosed) {
    //     currentstate += " or isonline= " + chosed[i];
    //
    // }
    // if (currentstate == "1") {
    //     sParam.tableparam = " and (isonline is not null and isonline!=0)";
    // } else {
    //     if (currentstate != "") {
    //         sParam.tableparam = " and (" + currentstate.substr(3) + ") ";
    //     }
    // }

    for (var i in chosed) {
        // if(chosed[i]=="3"){
        //     currentstate += " or isonline !=3";
        // }else{
            currentstate += " or isonline= " + chosed[i];
        // }
    }
    if (currentstate == "") {
        sParam.tableparam = "";
    } else {
        if (currentstate != "") {
            sParam.tableparam = " and (" + currentstate.substr(3) + ") ";
        }
    }

    //sParam.xzbh = $("#videoalarm").combobox("getValue");
    if (videoalarmTree != null && videoalarmTree != undefined) {
        var videoalarm = videoalarmTree.getSelectedIds();
        if (videoalarm != null && videoalarm.length > 0) {
            //讲数组赋值给行政区划的值['1','2']

            sParam.xzbh = videoalarm.join(",");
        }
    }

    sParam.order = "order by isonline ";
    return sParam;
}

//加载列表
function initGrid() {
    videoStatistics();
    var toolbar = [{
        text: '查询',
        iconCls: 'icon-search',
        handler: doSearch
    }];
    $('#tableGrid').datagrid({
        toolbar: toolbar,
        singleSelect: true,
        rownumbers: true,
        queryParams: getQueryParams(),
        url: 'ywvideocurrentstateAction!listYwvideocurrentstateByPage.do',
        columns: [[
            {
                field: 'A',
                checkbox: 'true',
                width: 30
            },
            {field: 'channelname', title: '通道名称', hidden: false, width: 200},
            {field: 'sbip', title: '设备IP', hidden: false, width: 120},
            {field: 'cjmc', title: '设备厂商', hidden: false, width: 120},
            // {field:'videostatus',title:'设备状态',hidden:true,width:90,
            // 	formatter:function showClick(value,record,num){
            // 		if (record.isonline == "0") {
            // 			return "设备不在线";
            // 		}
            // 		if(value=="1"){
            // 			return "正常";
            // 		}else if(value=="101"){
            // 			return "网络异常";
            // 		}else if(value=="102"){
            // 			return "设备不在线";
            // 		}else if(value=="103"){
            // 			return "抽帧异常";
            // 		}else if(value=="104"){
            // 			return "抽帧异常";
            // 		}
            // 	}
            // },
            {field: 'repairstatename', title: '维修状态', hidden: false, width: 200},
            {
                field: 'isonline', title: '是否在线', hidden: false, width: 60,
                formatter: function showClick(value, record, num) {
                    return transStatus(value + "");
                }
            },
            // {field:'vqcstate',title:'抽帧状态',hidden:false,width:60,
            // 	formatter:function showClick(value,record,num){
            // 		return transStatus(value+"");
            // 	}
            // },
//			{field:'vqdstate',title:'质量诊断状态',hidden:true,width:70,
//				formatter:function showClick(value,record,num){
//					return transStatus(value+"");
//				}
//			},
// 			{field:'nosignalstatus',title:'信号丢失',hidden:false,width:60,
// 				formatter:function showClick(value,record,num){
// 					return nosignalTransStatus(value+"");
// 				}
// 			},
// 			{field:'videoocclusionstatus',title:'视频遮挡',hidden:false,width:60,
// 				formatter:function showClick(value,record,num){
// 					return transStatus(value+"");
// 				}
// 			},
// 			{field:'scenechangestatus',title:'场景变更',hidden:false,width:60,
// 				formatter:function showClick(value,record,num){
// 					return transStatus(value+"");
// 				}
// 			},
// 			{field:'imgtoodarkstatus',title:'亮度过低',hidden:false,width:60,
// 				formatter:function showClick(value,record,num){
// 					return transStatus(value+"");
// 				}
// 			},
// 			{field:'imgoverbrightstatus',title:'亮度过高',hidden:false,width:60,
// 				formatter:function showClick(value,record,num){
// 					return transStatus(value+"");
// 				}
// 			},
// 			{field:'imgclearstatus',title:'图像模糊',hidden:false,width:60,
// 				formatter:function showClick(value,record,num){
// 					return transStatus(value+"");
// 				}
// 			},
// 			{field:'imgcolorstatus',title:'图像偏色',hidden:false,width:60,
// 				formatter:function showClick(value,record,num){
// 					return transStatus(value+"");
// 				}
// 			},
// 			{field:'recordstate',title:'录像状态',hidden:false,width:60,
// 				formatter:function showClick(value,record,num){
// 					return transStatus(value+"");
// 				}
// 			}
            {
                field: 'bz',
                title: '备注',
                hidden: false,
                width: 300,
                formatter: function showClick(value, record, num) {
                    if (value == null)
                        return "<a  href='javascript:void(0);' class='ahref' onclick='showupdate(" + num + ")'>无 </a>";
                    else
                        return "<a  href='javascript:void(0);' class='ahref' onclick='showupdate(" + num + ")'>" + value + "</a>";
                }
            },

        ]],
        onLoadSuccess: function (data) {
            $(".tip").tooltip({
                onShow: function () {
                    $(this).tooltip('tip').css({
                        width: '100',
                        boxShadow: '1px 1px 3px #292929'
                    });
                }
            })
        }
    });
}

function showupdate(index) {
    var rows = $('#tableGrid').datagrid('getRows')[index];
    rows.remarks=rows.bz;
    rows.currentstateid=rows.xh;
    windowId = top.$.createWin({
        title: '修改信息',
        width: 650,
        height: 300,
        data: rows,
        buttons: [{
            text: $.fn.textbox.defaults.ok,
            handler: saveNodeInfo
        }],
        url: sysUrl + "/yw/videoalarm/ywvideocurrentstateDetail.jsp"
    });

}


function saveNodeInfo() {
    //保存备注信息
    var win = $.getTopWindowById(windowId);
    var jq = win.$;
    $.ajax({
        type: 'post',
        dataType: 'json',
        url: 'ywvideocurrentstateAction!update_sbtdspsrRemarks.do',
        data: {"remarks": jq('#bz').val(), "XGTJid": jq('#XGTJid').val(),"XGTJvideonum":jq("#XGTJsbbh").val(),"XGTJchannelnum":jq("#XGTJtdbh").val()},
        success: function (value) {
            if (value == "success") {
                $.showMsg("操作成功！");
                top.$("#"+windowId).dialog('close');
                doSearch();
            } else if (value == "same") {
                $.showMsg("已存在！");
            } else {
                $.showMsg("操作失败！");
            }
        }
    });

}

//查询
function doSearch() {
    videoStatistics();
    $('#tableGrid').datagrid('load', getQueryParams());
}

//统计
function videoStatistics() {
    $.ajax({
        url: "ywvideocurrentstateAction!videoCurrentStateStatistics.do",
        dataType: "JSON",
        type: "POST",
        data: {},//getQueryParams(),
        success: function (res) {
            if (res != null) {
                var num = 0;
                var num_zc = 0;
                for(var i in res.data){

                    if(res.data[i].csmc=='normal'){
                        $("#normalFrontDeviceTotal").html(res.data[i].cnt);
                    }
                    if(res.data[i].csmc=='total'){
                        $("#frontDeviceTotal").html(res.data[i].cnt);
                    }
                    if(res.data[i].csmc=='abnormal'){
                        $("#abnormalFrontDeviceTotal").html(res.data[i].cnt);
                    }
                }
                var colors=["#e16616","#754599","#84ccc9"];
                var data = {
                    "title": "设备故障类型占比分析",
                    data: []
                };
                //遍历返回结果
                for (var i in res.data) {
                        if( res.data[i].csdm=="normal") {
                            data.data.push({
                                name: "正常", value: res.data[i].cnt, color: "#32c99d"
                            })
                        }
                        else if( res.data[i].csdm=="abnormal") {
                            data.data.push({
                                name: "异常", value: res.data[i].cnt, color: "#fe0000"
                            })
                        }
                }


                EchartsBase.pieChart({
                    id: "deviceAnalysisGraphChart",
                    data: data,
                    orient: 'horizontal', // 'vertical'
                });
            }
            //console.log("resresres",res);
        }
    });
}

//视频播放
function doPlay(id) {
//	var selRows = $('#tableGrid').datagrid('getSelected'); 
    if (!id) {
        $.showMsg('请先选择记录! ');
        return;
    }
    var url = sysUrl + "/yw/videoalarm/itemPage/detailVideoQuality.jsp";
    windowid = top.$.createWin({
        title: '详情',
        width: '720',
        height: '400',
        data: id,
        url: url,
    });
}

//初始化下拉框
function handleA(e) {
    var event = e;
    //console.log("e")
    //e.stopPropagation();
    //e.preventDefault();
}
function ywVideo(){
    $.ajax({
        type: 'post',
        async:true,
        dataType: 'json',
        url: 'xtclAction!listXtclByPage.do',//dac 行政树
//		 url:'ptxzsAction!query_Ptxzs.do' ,//本地 行政树
		 data:{
             LIKEcsdl: "ywVideoCurrent",
             LIKEcslm:"",
             LIKEcsdm:"",
             LIKEcsmc:"",
             order: "order by csdl asc",
             page: 1,
             rows: 20,
		 },
    }).done(function (data) {
        var arr=[];
        if(data.rows.length>0){
            for(var i in data.rows){
                arr.push({name:data.rows[i].csmc,value:data.rows[i].csdm});
            }
        }
        arrs = arr;
        initCacheStatus();
        // var a =data;
    });
}
//初始化下拉框
function initCacheStatus() {
    var ywDeviceStatusArr = [];
    // var videoStatus = Constants.videoStatus;
    var videoStatus = arrs;
    for (var i in videoStatus) {
        ywDeviceStatusArr.push({"id": videoStatus[i].value, "text": videoStatus[i].name})
    }
    $("#currentstate").combobox("loadData", ywDeviceStatusArr);
    $('#currentstate').combobox({
        formatter: function (row) {
            var opts = $(this).combobox('options');
            return row[opts.textField];
        }
    });
    var firstShowPanel = true;
    var ht=[];
    for(var i=0;i<arrs.length;i++){
        var str = "#_easyui_combobox_i1_"+i;
        ht.push({id:str});
    }
    for(var i=0;i<ht.length;i++){
        $(ht[i].id).after("<div onclick='handleA' class='handleCom1' style='display:none;'>" + $(ht[i].id).html() + "</div>");
    }
    // var html = $("#_easyui_combobox_i1_0").html();
    // var html1 = $("#_easyui_combobox_i1_1").html();
    // var html2 = $("#_easyui_combobox_i1_2").html();
    // var html3 = $("#_easyui_combobox_i1_3").html();
    // var html4 = $("#_easyui_combobox_i1_4").html();
    // var html5 = $("#_easyui_combobox_i1_5").html();
    // $("#_easyui_combobox_i1_0").after("<div onclick='handleA' class='handleCom1' style='display:none;'>" + html + "</div>");
    // $("#_easyui_combobox_i1_1").after("<div onclick='handleA' class='handleCom' style='display:none;'>" + html1 + "</div>");
    // $("#_easyui_combobox_i1_2").after("<div onclick='handleA' class='handleCom' style='display:none;'>" + html2 + "</div>");
    // $("#_easyui_combobox_i1_3").after("<div onclick='handleA' class='handleCom' style='display:none;'>" + html3 + "</div>");
    // $("#_easyui_combobox_i1_4").after("<div onclick='handleA' class='handleCom' style='display:none;'>" + html4 + "</div>");
    // $("#_easyui_combobox_i1_5").after("<div onclick='handleA' class='handleCom' style='display:none;'>" + html5 + "</div>");
    $('#currentstate').combobox({
        onUnselect: function (record) {
            var opts = $(this).combobox('options');
            var values = $('#currentstate').combobox('getValues');
            if (record.id == 1) {
                // $("#_easyui_combobox_i1_1").show();
                // $("#_easyui_combobox_i1_2").show();
                // $("#_easyui_combobox_i1_3").show();
                // $("#_easyui_combobox_i1_4").show();
                // $("#_easyui_combobox_i1_5").show();
                for(var i=1;i<=arrs.length;i++){
                    $("#_easyui_combobox_i1_"+i).show();
                }
                $(".handleCom").hide();
            } else {
                if (values.length <= 1) {
                    var values = $('#currentstate').combobox('getValues');
                    $(".handleCom1").hide();
                    $("#_easyui_combobox_i1_0").show();
                }
            }
        },
        onChange: function () {
            var values = $('#currentstate').combobox('getValues');
        },
        onHidePanel: function () {
            selectedValues = $('#currentstate').combobox('getValues');
            firstShowPanel = false;
        },
        onShowPanel: function () {
            if (!firstShowPanel) {
                if (selectedValues.indexOf("1") != -1) {
                    for(var i=1;i<=arrs.length;i++){
                        $("#_easyui_combobox_i1_"+i).hide();
                    }
                } else {
                    if (selectedValues.length > 0) {
                        $("#_easyui_combobox_i1_0").hide();
                    }
                }
            }
        },
        onSelect: function (record) {
            var values = $('#currentstate').combobox('getValues');
            var opts = $(this).combobox('options');
            if (record.id == 1) {
                // for(var i=1;i<=arrs.length;i++){
                //     $("#_easyui_combobox_i1_"+i).hide();
                // }
                $(".handleCom").show();
            } else {
                $("#_easyui_combobox_i1_0").hide();
                $(".handleCom1").hide();
            }
            return false;
        }
    });
}

function transStatus(data) {
    if (data != "0") {
        return "<div style='height:13px;width:13px;background-color:#60b631;border-radius:50%;-moz-border-radius: 50%;-webkit-border-radius: 50%;margin:0 auto;'></div>";
    } else {
        return "<div style='height:13px;width:13px;background-color:#fe0000;border-radius:50%;-moz-border-radius: 50%;-webkit-border-radius: 50%;margin:0 auto;'></div>";
    }
    return "";
}

function nosignalTransStatus(data) {
    if (data == "1") {
        return "<div style='height:13px;width:13px;background-color:#60b631;border-radius:50%;-moz-border-radius: 50%;-webkit-border-radius: 50%;margin:0 auto;'></div>";
    } else if (data == "2") {
        return "<div class='tip' title='码流中断' style='height:13px;width:13px;background-color:#ff7a05;border-radius:50%;-moz-border-radius: 50%;-webkit-border-radius: 50%;margin:0 auto;'></div>";
    } else if (data == "3") {
        return "<div class='tip' title='帧率过低' style='height:13px;width:13px;background-color:#fe0000;border-radius:50%;-moz-border-radius: 50%;-webkit-border-radius: 50%;margin:0 auto;'></div>";
    } else if (data == "4") {
        return "<div class='tip' title='丢包' style='height:13px;width:13px;background-color:#fe0000;border-radius:50%;-moz-border-radius: 50%;-webkit-border-radius: 50%;margin:0 auto;'></div>";
    } else {
        return "";
    }
}

//初始化行政树
function initTreePanel() {
    $.ajax({
        type: 'post',
//		 async:false,
        dataType: 'json',
        url: 'menuConfigAction!query_Ptxzs.do',//dac 行政树
//		 url:'ptxzsAction!query_Ptxzs.do' ,//本地 行政树
//		 data:{
//			 order : " order by jdpx asc "
//		 },
    }).done(function (data) {
        if (data != null && data.length > 0) {
            $.each(data, function (i, o) {
                o.state = 'closed';
                o.treeId = o.xzbh;
                o.name = o.xzmc;
                o.treeType = "xz";
                o.id = o.xzbh;
                o.pid = o.sjxzbh;
                o.start = 0; //iconCls
            })
        }
        var xzfz = {};
        xzfz.treeType = "xz";
        xzfz.id = "-1";
        xzfz.pid = "xzTree";
        xzfz.start = 0; //iconCls
        xzfz.xzbh = "-1";
        xzfz.xzmc = "行政分组";
        xzfz.state = "closed";
        xzfz.treeId = "-1";
        xzfz.sjxzbh = "xzTree";
        xzfz.name = "行政分组";
        data.push(xzfz);
        $('#videoalarm').combotree({
            checkbox: false,
            border: false,
            parentField: "pid",
            textFiled: "name",
            idFiled: "id",
            panelWidth: 148,
            data: data,
            onLoadSuccess: function (node, data) {
                if (data) {

                }
            },
            onClick: function (node) {

            },
            data: data
        });
    });
}