var $area=$("#area");
var $startTime=$("#startTime");
var $endTime=$("#endTime");
var tiggleValue="online";
var dataTable=null;
var resultData=null;
var minfuzhi = null;//最小暂态幅值
var maxfuzhi = 0;//最大暂态幅值
var mintime = 0;//最小持续时间
var maxtime = 0;//最大持续时间
var minseverity = 0;//最小严重度
var maxseverity = 0;//最大严重度
var eventType = null;//暂降类型
var eventReson = null;//暂降理由
var triggerType = null;//触发类型
var fileflag = null;//是否有波形
$("#interval").val("月份");
$(function () {
    //初始化按钮开关
    $(".checkbox").bootstrapSwitch({
        onText: "在线",      // 设置ON文本
        offText: "离线",    // 设置OFF文本
        onColor: "primary",// 设置ON文本颜色     (info/success/warning/danger/primary)
        offColor: "primary",  // 设置OFF文本颜色        (info/success/warning/danger/primary)
        size: "small",    // 设置控件大小,从小到大  (mini/small/normal/large)
        handleWidth: "60",//设置控件宽度
        // 当开关状态改变时触发
        onSwitchChange: function (event, state) {
            if (state === true) {
                tiggleValue = "online";
            } else {
                tiggleValue = "offline";
            }
        }
    });
    //初始化区域
    $.ajax({
        type: "POST",
        url: "/pqs9000/user/getAreasInfo",
        dataType:'json',
        success:function (data) {
            $("#area").val(data[0].name);
            $("#area").attr("index", data[0].id);
            areaTree = $.fn.zTree.init($("#areaTree"), settingAreaTree, data);
            //初始化页面内容
            var area = $area.eq(0).attr("index");
            var startTime = $startTime.eq(0).val();
            var endTime = $endTime.eq(0).val();
            refresh(area, startTime, endTime);
        }
    })
})

//实现多条件查询
$('#maxQuery').click(function () {
    layer.open({
        type: 2,
        title: '多条件筛选',
        area : ['27%','65%'],
        content: '/pqs9000/business/vdlistquery'

    });

})

//点击确定，去后台请求参数
$("#query").click(function() {
    var area = $area.eq(0).attr("index");
    var startTime = $startTime.eq(0).val();
    var endTime = $endTime.eq(0).val();
    refresh(area,startTime,endTime);
});
//获取表格数据
function refresh(area,startTime,endTime){
    var i ;
    $.ajax({
        type : "POST",
        contentType: 'application/json;charset=UTF-8',
        url : "/pqs9000/area/getVoltageDetail",
        dataType : "json",
        data : JSON.stringify({
            startTime : startTime,
            endTime : endTime,
            area:area,
            type:tiggleValue,
            minfuzhi:null,
            maxfuzhi:null,
            mintime:null,
            maxtime:null,
            minseverity:null,
            maxseverity:null,
            eventType:null,
            eventReason:null,
            triggerType:null,
            fileflag:null
        }),
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER();
        },
        success : function(data) {
            if (data.code === 500) {
                layer.msg(data.message,{icon:2,time:2000})
                resultData=null;
            } else {
                resultData=data.body;
            }
            startQuery();
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(i);
        }
    });
}

//实例化表格
function initTable(data){
    var height=$(window).height()-140;
    dataTable=$("#vdlist").DataTable();
    dataTable.clear().draw();
    dataTable=$('#vdlist').DataTable({
        order:[],
        columnDefs : [
            {
                orderable : false,
                targets : [0,1,10]
            }
        ],
        columns: [
            {width:"3%",data:"eventDetailIndex",
                render:function (data, type, full, meta) {
                    if(full.fileFlag==="0"){
                        return "<input type ='checkbox' name='disable' class='icheckbox_minimal' disabled >";
                    }else{
                        return "<input type ='checkbox' name='test' class='icheckbox_minimal' value='"+data+"'>";
                    }
                }
            },
            {width: "4%",data:null},
            {width: "10%",data:"time"},
            {width: "7%",data:"gdName", render:function (data, type, full, meta) {
                    var value=data;
                    if(data.length>8){
                        value=data.substring(0,7)+"...";
                        value="<span title="+data+">"+value+"</span>";
                    }
                    return value;
                }},
            {width: "10%",data:"subName", render:function (data, type, full, meta) {
                    var value=data;
                    if(data.length>13){
                        value=data.substring(0,12)+"...";
                        value="<span title="+data+">"+value+"</span>";
                    }
                    return value;
                }},
            {width: "7%",data:"ip"},
            {width: "7%",data:"lineName", render:function (data, type, full, meta) {
                    var value=data;
                    if(data.length>10){
                        value=data.substring(0,9)+"...";
                        value="<span title="+data+">"+value+"</span>";
                    }
                    return value;
                }},
            {width: "7%",data:"scale",type:"number-fate"},
            {
                width: "6%", data: "waveType", render: function (data, type, full, meta) {
                    return displayWaveType(data);
                }
            },
            {width: "8%",data:"eventValue"},
            {width: "7%",data:"eventValue",render: function (data, type, full, meta) {
                    data = Number(data);
                    if(data>100){
                        return '/';
                    }else if(data<0){
                        return 0;
                    }else{
                        return (100-data).toFixed(2);
                    }

                }
            },
            {width: "7%",data:"persistTime"},
            {width: "7%",data:"severity",
                render:function (data, type, full, meta) {
                    return displayYzd(data,full.persistTime,full.eventValue,full.waveType);
                }
            },
            {width: "10%",data:"eventDetailIndex",
                render:function (data, type, full, meta) {
                    var flag=true;
                    if(full.fileFlag==="0"){
                        flag=false;
                    }
                    var bxck;
                    if(flag){
                        bxck="<button type='button' class='btn themeBGColor' style='margin-right:10px;' href='javascript:void(0);'  onclick='viewWave(\"" + data + "\")' >波形分析</button>";
                    }else{

                        if ((full.devType).indexOf("CLD") != -1) {
                            bxck = "<button type='button' class='btn themeBGDisableColor'" +
                                " style='margin-right:10px;' href='javascript:void(0);' onclick='viewBZ(\"" + full.lineId + "\",\"" + full.time + "\")' >波形补招</button>";
                        } else {
                            bxck = "<button type='button' class='btn themeBGDisableColor' style='margin-right:10px;' href='javascript:void(0);'  >暂无波形</button>";
                        }
                    }
                    return bxck;
                }
            }
        ],
        autoWidth:false,
        serverSide : false,
        destroy : true,
        data : data,
        lengthChange: false,
        searching: true,
        dom: 'rtip',
        scrollY: height,
        scrollX: true,
        lengthMenu : [ 50 ],
        language : {
            url:'/pqs9000/json/chine.json'
        },
        fnDrawCallback: function(oTable) {
            $("#vdlist_info").addClass("fl");
            $("#vdlist_paginate").addClass("fr");
            $("#vdlist_paginate").append("<div style='float:right;padding-top:4px;padding-left:10px'>到第 <input type='text' id='changePage' class='input-text' style='width:50px;height:28px;'> 页  <button class='btn btn-primary' id='dataTable-btn'>确定</button></div>");
            var table = $("#vdlist").dataTable();
            $('#dataTable-btn').click(function(e) {
                if($("#changePage").val() && $("#changePage").val() > 0) {
                    var redirectpage = $("#changePage").val() - 1;
                } else {
                    var redirectpage = 0;
                }
                table.fnPageChange(redirectpage);
            });
        }
    });

    var name = $area.find("option:selected").text();
    new $.fn.dataTable.Buttons( dataTable, {
        buttons: [
            {
                extend: 'csv',
                title:name+'暂降事件列表',//导出csv名称
                exportOptions:{
                    columns :[1,2,3,4,5,6,7,8,9,10,11,12],
                    format:{
                        body:function(data,rID,cID){
                            if(cID===0){
                                return rID+1;
                            }else if(cID===1){
                                return data.replace("0","O");
                            }else if(cID===3|cID===2|cID===5){
                                if(data.indexOf("title")>0){
                                    return data.substring(data.indexOf("=")+1,data.indexOf(">"));
                                }else{
                                    return data
                                }
                            } else if (cID === 11) {
                                var temp = "";
                                if (data.indexOf("color") > 0) {
                                    temp = data.substring(data.indexOf(">") + 1, data.indexOf("</"));
                                }
                                return temp;
                            }else{
                                return data;
                            }
                        }
                    }
                }
            }
        ]
    } );
    modifyCss(dataTable);
    dataTable.on('order.dt search.dt',
        function() {
            dataTable.column(1, {
                search: 'applied',
                order: 'applied'
            }).nodes().each(function(cell, i) {
                cell.innerHTML = i + 1;
            });
        }).draw();

    //获取出搜索框内的内容，进行数据筛选
    var value = $("#searchValue").val();
    searchResult(value);
}
function modifyCss(dataTable){
    dataTable.buttons().container().css("display","inline-block");
    dataTable.buttons().container().css("float","right");
    dataTable.buttons().container().css("top","4px");
    dataTable.buttons().container().find("a").prepend("<i class='glyphicon glyphicon-share'></i>");
    dataTable.buttons().container().find("a").before("<button id='downloadWave' type='button' class='btn btn-primary mr10' > <i class='glyphicon glyphicon-download'></i>下载波形</button>");
    dataTable.buttons().container().appendTo('.header');
    dataTable.buttons().container().after($("#fliteData")[0]);
}

//波形分析
function viewWave(eventIndex){
    layer.open({
        type: 2,
        title: '波形分析',
        maxmin : false,
        area : ['100%' , '100%'],
        content: '/pqs9000/business/vdwaveform?eventIndex='+eventIndex,
        scrollbar: false
    });
}



//处理触发类型
function displayWaveType(data){
    switch(data){
        case 0:
            return '扰动';
        case 1:
            return '暂降';
        case 2:
            return '暂升';
        case 3:
            return '中断';
        case 4:
            return '其他';
        case 5:
            return '录波';
        case 6:
            return '外部录入';
    }

}

//实现全选功能
$("#all_checked").click(function(){
    $('[name=test]:checkbox').prop('checked',this.checked);//checked为true时为默认显示的状态
});

//实现反选功能
$("#checkrev").click(function(){
    $('[name=test]:checkbox').each(function(){
        this.checked=!this.checked;
    });
});

//点击下载波形
$("body").on("click","#downloadWave",function(){
    var indexs=[];
    var $checkboxs=$("[name=test]:checked");
    var length=$checkboxs.length;
    if(length===0){
        layer.msg('请选中需要下载的波形',{icon:2,time:2000});
    }else if(length>5){
        layer.msg('最多同时下载5个波形数据',{icon:2,time:2000});
    }else{
        for (var i=0;i<length;i++){
            indexs.push($checkboxs.eq(i).val())
        }
        //执行波形下载
        downloadWave(indexs);
    }
})

//下载波形
function downloadWave(index) {
    var i ;
    $.ajax({
        type:"post",
        url:"/pqs9000/area/downloadWave",
        dataType:"json",
        data:{
            index:index
        },
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER_WAVE();
        },
        success:function(data){
            if(data.code===200){
                downloadZip();
            }else{
                layer.msg(data.message,{icon:2,time:2000})
            }
            ityzl_CLOSE_LOAD_LAYER(i);
        }
    })
}

function downloadZip() {
    window.location.href='/pqs9000/area/downWaveZip';
}

//搜索表中的数据
function searchResult(value) {
    dataTable.search(value).draw();
}

//特殊处理，表头紧缩问题--start
var it=null;
function startQuery() {
    //实时刷新时间单位为毫秒
    it= setInterval('refreshQuery()',100);

}
/* 刷新查询 */
function refreshQuery(){
    var width=$("#vdlist").width();
    if(width>100){
        initTable(resultData);
        window.clearInterval(it)
    }
}
//特殊处理，表头紧缩问题--end

//获取严重度显示的值
function displayYzd(data,persisttime,eventvaule,waveType) {
    var yzd=0;
    if(null===data|data===0.0){
        //根据持续时间计算出严重度
        yzd=calculateYzd(persisttime,eventvaule);
    }else{
        yzd=data;
    }
    //判断是否为暂升事件
    if(waveType === 2 | waveType === 5){
        yzd="/";
        return "<span style='color:#000'>"+yzd+"</span>";
    }
    if(0<=yzd&yzd<=1){
        return "<span style='color:#22B14C'>"+yzd+"</span>";
    }else if(yzd<=2){
        return "<span style='color:#3F48CC'>"+yzd+"</span>";
    }else if(yzd<=5){
        return "<span style='color:#FFA500'>"+yzd+"</span>";
    }else if(yzd<=10){
        return "<span style='color:#FF7F27'>"+yzd+"</span>";
    }else{
        return "<span style='color:#ED1C24'>"+yzd+"</span>";
    }
}

//计算严重度 persisttime持续时间ms eventvaule暂降幅值
function calculateYzd(persisttime,eventvaule){
    persisttime=persisttime*1000;
    eventvaule=eventvaule/100;
    var yzd=0;
    if (persisttime <= 20) {
        yzd = 1-eventvaule;
    } else if (persisttime > 20 && persisttime <= 200) {
        yzd = 2*(1-eventvaule);
    } else if (persisttime > 200 && persisttime <= 500) {
        yzd = 3.3*(1-eventvaule);
    }else if(persisttime > 500 && persisttime <=10000){
        yzd=5*(1-eventvaule);
    } else {
        yzd = 10*(1-eventvaule);
    }
    //精确3位小数
    yzd=yzd.toFixed(3);
    return yzd;
}


/**
 * 电压等级排序自定义比较start
 */
jQuery.fn.dataTableExt.oSort['number-fate-asc']  = function(s1,s2) {
    s1 = s1.replace('kV','');
    s2 = s2.replace('kV','');
    return Number(s1)-Number(s2);
};

jQuery.fn.dataTableExt.oSort['number-fate-desc'] = function(s1,s2) {
    s1 = s1.replace('kV','');
    s2 = s2.replace('kV','');
    return Number(s2)-Number(s1);
};
/**
 * 电压等级排序自定义比较end
 */


/**
 * 用于子页面调用传值
 */
window.paramToVd=function (obj){

    let area = $area.eq(0).attr("index");
    let startTime = $startTime.eq(0).val();
    let endTime = $endTime.eq(0).val();
    refreshForOpen(area,startTime,endTime,obj)
}

//获取表格数据
function refreshForOpen(area,startTime,endTime,obj){
    let i ;
    $.ajax({
        type : "POST",
        url : "/pqs9000/area/getVoltageDetail",
        contentType: 'application/json;charset=UTF-8',
        dataType : "json",
        data : JSON.stringify({
            startTime : startTime,
            endTime : endTime,
            area:area,
            type:tiggleValue,
            minfuzhi:obj.minfuzhi,
            maxfuzhi:obj.maxfuzhi,
            mintime:obj.mintime,
            maxtime:obj.maxtime,
            minseverity:obj.minseverity,
            maxseverity:obj.maxseverity,
            eventType:obj.eventType,
            eventReason:obj.eventReason,
            triggerType:obj.triggerType,
            fileflag:obj.fileflag
        }),
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER();
        },
        success : function(data) {
            if (data.code === 500) {
                layer.msg(data.message,{icon:2,time:2000})
                resultData=null;
            } else {
                resultData=data.body;
            }
            startQuery();
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(i);
        },error:function () {
            layer.msg('未知异常',{icon:2})
        }
    });
}


/****
 * 波形补招
 */
function viewBZ(lineId, time) {
    let ia;
    var timeId = new Date(time).getTime();
    $.ajax({
        type: "POST",
        url: "/pqs9000/device/socketonWave",
        dataType: "json",
        data: {
            type:100,
            ComtradeName:timeId,
            LineId: lineId
        },
        beforeSend: function () {
            ia = ityzl_SHOW_LOAD_LAYER();
        },
        success: function (data) {
            if (data.code == 200) {

                layer.msg(data.message+",请大约三十秒钟后刷新确认",{
                    icon: 1,
                    time: 3000
                },function () {
                    startQuery()
                })

            } else {
                layer.msg(data.message, {
                    icon: 5,
                    time: 3000
                });
            }
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(ia);
        }
    })
}

