var $area=$("#area");
var $startTime=$("#startTime");
var $endTime=$("#endTime");
var $vollevel = $("#vollevel")

var buttonname;
var companyname;
var tigName;
var volData;
var dataTable=null;
var startTime,endTime,area,vollevel;

$(function () {
    startTime = $startTime.eq(0).val();
    endTime = $endTime.eq(0).val();
    area = $area.eq(0).val();
    vollevel = $vollevel.eq(0).val();
    loadselect("电压等级","vollevel");
    $.ajax({
        type: "POST",
        data:{
            start: startTime,
            end: endTime
        },
        async:false,
        url: "/pqs9000/device/getMsgInfo",
        dataType: 'json',
        success: function (data) {
            buttonname = data.body.name;
            tigName = data.body.name;
        }
    })

    $.ajax({
        type: "POST",
        url: "/pqs9000/theme/getThemeInfo",
        async: false,
        dataType: 'json',
        success: function (data) {
            companyname = data.body.name;
        }
    })

    //初始化按钮开关
    $(".checkbox").bootstrapSwitch({
        onText: buttonname,      // 设置ON文本
        offText: companyname,    // 设置OFF文本
        onColor: "primary",// 设置ON文本颜色     (info/success/warning/danger/primary)
        offColor: "primary",  // 设置OFF文本颜色        (info/success/warning/danger/primary)
        size: "small",    // 设置控件大小,从小到大  (mini/small/normal/large)
        handleWidth: "50",//设置控件宽度
        // 当开关状态改变时触发
        onSwitchChange: function (event, state) {
            if (state === true) {
                tigName = buttonname;
                refresh(vollevel,area, startTime, endTime,tigName);
            } else {
                tigName = companyname;
                refresh(vollevel,area, startTime, endTime,tigName);
            }
        }
    });
    //初始化区域
    $.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);
            //初始化页面内容
            area = $area.eq(0).attr("index");
            vollevel = $vollevel.eq(0).val();
            startTime = $startTime.eq(0).val();
            endTime = $endTime.eq(0).val();
            refresh(vollevel,area, startTime, endTime,tigName);
        }
    })
})


//点击确定，去后台请求参数
$("#query").click(function() {
    area = $area.eq(0).attr("index");
    vollevel = $vollevel.eq(0).val();
    startTime = $startTime.eq(0).val();
    endTime = $endTime.eq(0).val();
    refresh(vollevel,area,startTime,endTime,tigName);
});

//获取表格数据
function refresh(vollevel,area,startTime,endTime,tigName){
    let statFlag = $('#allLineCheck').is(":checked")
    var i ;
    $.ajax({
        type : "POST",
        url : "/pqs9000/responsibility/warningSubstationData",
        dataType : "json",
        data : {
            startTime : startTime,
            endTime : endTime,
            area:area,
            vollevel:vollevel,
            tigName:tigName,
            statFlag:statFlag
        },
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER();
        },
        success : function(data) {
            if (data.code === 500) {
                layer.msg(data.message,{icon:2,time:2000})
                volData=null;
            } else {
                // var sortData = bubbleSort(data);
                initTable(data.body)
            }
            //***********关闭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]
            }
        ],
        columns: [
            {width:"2%",data: null, render : function(data, type, full, meta){
                    return meta.row + 1 + meta.settings._iDisplayStart;
                }},
            // {width: "4%",data:"provinceCompany"},
            {width: "4%",data:"cityCompany"},
            {width: "6%",data:"plantName",render : function(data, type, full, meta){
                    var value=data;
                    if(data.length>15){
                        value=data.substring(0,14)+"...";
                        value="<span title="+data+">"+value+"</span>";
                    }
                    return value;
                }},
            {width: "4%",data:"plantVoltageLevel"},
            {width: "4%",data:"onlineMonitorCounts"},
            {width: "4%",data:"alertMonitorCounts"},
            {width: "4%",data:"alertCounts"},
            {width: "4%",data: "alertAlarmFrequency",render : function(data, type, full, meta){
                    var value= toDecimal2(data);
                    return value;
                }},
            {width: "4%",data:"frequencyDeviation",render : function(data, type, full, meta){
                    var value= toDecimal2(data);
                    return value;
                }},
            {width: "4%",data:"voltageDeviation",render : function(data, type, full, meta){
                    var value= toDecimal2(data);
                    return value;
                }},
            {width: "4%",data:"harmonicVoltage",render : function(data, type, full, meta){
                    var value= toDecimal2(data);
                    return value;
                }},
            {width: "4%",data:"harmonicCurrent",render : function(data, type, full, meta){
                    var value= toDecimal2(data);
                    return value;
                }},
            {width: "4%",data:"threePhaseVoltageUnbalance",render : function(data, type, full, meta){
                    var value= toDecimal2(data);
                    return value;
                }},
            {width: "4%",data:"flicker",render : function(data, type, full, meta){
                    var value= toDecimal2(data);
                    return value;
                }},
            {width: "4%",data:"interharmonic",render : function(data, type, full, meta){
                    var value= toDecimal2(data);
                    return value;
                }},
            {width: "4%",data:"negative",render : function(data, type, full, meta){
                    var value= toDecimal2(data);
                    return value;
                }},
            {width: "4%",data:"shortInterruption",render : function(data, type, full, meta){
                    var value= toDecimal2(data);
                    return value;
                }},
            {width: "4%",data:"voltageDip",render : function(data, type, full, meta){
                    var value= toDecimal2(data);
                    return value;
                }},
            {width: "4%",data:"voltageSwell",render : function(data, type, full, meta){
                    var value= toDecimal2(data);
                    return value;
                }}
        ],
        bAutoWidth:false,
        serverSide : false,
        destroy : true,
        data : data,
        lengthChange: false,
        searching: true,
        dom: 'rt',
        sScrollY: height,
        scrollX: true,
        //关闭分页功能
        bPaginate: false,
        language : {
            url:'/pqs9000/json/chine.json'
        },
    });
}


function loadselect(dictypeName,div){
    var part='#'+div;
    $(part).find("option").remove();
    $.ajax({
        method : "post",
        url : "/pqs9000/device/getselect",
        data : {
            dictypeName:dictypeName
        },
        async:false,
        success : function(data) {
            if(data == null){
                var message = dictypeName + '信息加载失败';
                layer.msg(message,{icon:1,time:1000});
            }else{
                var option0 = $("<option selected value='"
                    + null + "'>"
                    + "全部" + "</option>");
                $(part).append(option0);
                $.each(data, function(i, item) {
                    var option = $("<option value='"
                        + item.dicIndex + "'>"
                        + item.dicName + "</option>");
                    $(part).append(option);
                })
            }
        }
    })
}

//搜索表中的数据
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

//制保留2位小数，如：2，会在2后面补上00.即2.00
function toDecimal2(x) {
    var f = parseFloat(x);
    if (isNaN(f)) {
        return false;
    }
    var f = Math.round(x*100)/100;
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + 2) {
        s += '0';
    }
    return s;
}

//点击导出功能
$('#exportSubTable').click(function () {
    var startTime = $startTime.eq(0).val();
    var endTime = $endTime.eq(0).val();
    $("<form method='post' action='/pqs9000/responsibility/exportSubExcel?startTime="+startTime+"&endTime="+endTime+"'>"+
        "<input type='hidden'/>"+ encodeURIComponent("excelname")+
        "'/></form>").appendTo('body').submit().remove();
});

//排序
function bubbleSort(data) {
    for (var i=0;i<data.length-1;i++){
        for (var j=0;j<data.length-1-i;j++){
            if (data[j].alertCounts<data[j+1].alertCounts){
                var temp = data[j+1];
                data[j+1] = data[j];
                data[j] = temp;
            }
        }
    }
    return data
}
