var $area=$("#area");
var $startTime=$("#startTime");
var $endTime=$("#endTime");
var $vollevel = $("#vollevel")
$("#interval").val("月份");

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: "60",//设置控件宽度
        // 当开关状态改变时触发
        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) {
            console.log(data[0])
            $("#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/overLimitMonitorData",
        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()-160;
    dataTable=$("#vdlist").DataTable();
    dataTable.clear().draw();
    dataTable=$('#vdlist').DataTable({
        order:[],
        columnDefs : [
            {
                orderable : false,
                targets : [0,1]
            }
        ],
        columns: [
            {width:"1%",data: null, render : function(data, type, full, meta){
                    return meta.row + 1 + meta.settings._iDisplayStart;
                }},
            {width: "1%",data:"provinceCompany"},
            {width: "1%",data:"cityCompany"},
            {width: "2.5%",data:"monitorName",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: "2%",data:"monitorType"},
            {width: "2%",data:"powerSubstationName",render:function (data) {
                    return data == null? '/':data;
                }},
            {width: "2%",data:"objName",render:function (data) {
                    return data == null? '/':data;
                }},
            {width: "2%",data:"monitorVoltageLevel"},
            {width: "2.5%",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: "2%",data:"plantVolageLevel"},
            {width: "1%",data: "dlcMp"},
            {width: "1%",data: "devcMp"},
            {width: "1%",data: "xycMp"},
            {width: "1%",data: "overLimitDay"},
            // 电压偏差
            {width: "2%",data:"overVoltageDeviationDay"},
            {width: "2%",data:"maxVoltageDeviationData",render : function(data, type, full, meta){
                    return data.toFixed(3);
                }},
            {width: "2%",data:"limitVoltageDeviationData"},
            {width: "2%",data:"diffVoltageDeviationData",render : function(data, type, full, meta){
                    return data.toFixed(3);
                }},
            //谐波电流
            {width: "2%",data:"overHarmonicCurrentDay"},
            {width: "2%",data:"maxHarmonicCurrentData",render : function(data, type, full, meta){
                    return data.toFixed(3);
                }},
            {width: "2%",data:"limitHarmonicCurrentData"},
            {width: "2%",data:"diffHarmonicCurrentData",render : function(data, type, full, meta){
                    return data.toFixed(3);
                }},
            //谐波电压
            {width: "2%",data:"overLimitHarmVDay"},
            {width: "2%",data:"maxLimitHarmVData",render : function(data, type, full, meta){
                    return data.toFixed(3);
                }},
            {width: "2%",data:"limitHarmVData"},
            {width: "2%",data:"diffHarmVData",render : function(data, type, full, meta){
                    return data.toFixed(3);
                }},
            //电压总谐波畸变率
            {width: "2%",data:"overVoltageDistortionDay"},
            {width: "2%",data:"maxVoltageDistortionData",render : function(data, type, full, meta){
                    return data.toFixed(3);
                }},
            {width: "2%",data:"limitVoltageDistortionData"},
            {width: "2%",data:"diffVoltageDistortionData",render : function(data, type, full, meta){
                    return data.toFixed(3);
                }},
            //谐波电压含有率
            {width: "2%",data:"overHarmonicVoltageDay"},
            {width: "2%",data:"maxHarmonicVoltageData",render : function(data, type, full, meta){
                    return data.toFixed(3);
                }},
            {width: "2%",data:"limitHarmonicVoltageData"},
            {width: "2%",data:"diffHarmonicVoltageData",render : function(data, type, full, meta){
                    return data.toFixed(3);
                }},
            //三相电压不平衡度
            {width: "2%",data:"overThreeVoltageUnbalanceDay"},
            {width: "2%",data:"maxThreeVoltageUnbalanceData",render : function(data, type, full, meta){
                    return data.toFixed(3);
                }},
            {width: "2%",data:"limitThreeVoltageUnbalanceData"},
            {width: "2%",data:"diffThreeVoltageUnbalanceData",render : function(data, type, full, meta){
                    return data.toFixed(3);
                }},
            //频率偏差
            {width: "2%",data:"overFrequencyDeviationDay"},
            {width: "2%",data:"maxFrequencyDeviationData",render : function(data, type, full, meta){
                    return data.toFixed(3);
                }},
            {width: "2%",data:"limitFrequencyDeviationData"},
            {width: "2%",data:"diffFrequencyDeviationData",render : function(data, type, full, meta){
                    return data.toFixed(3);
                }},
            //间谐波电压含有率
            {width: "2%",data:"overInterharmonicsDay"},
            {width: "2%",data:"maxInterharmonicsData",render : function(data, type, full, meta){
                    return data.toFixed(3);
                }},
            {width: "2%",data:"limitInterharmonicsData"},
            {width: "2%",data:"diffInterharmonicsData",render : function(data, type, full, meta){
                    return data.toFixed(3);
                }},
            //负序电流
            {width: "2%",data:"overNegativeDay"},
            {width: "2%",data:"maxNegativeDay",render : function(data, type, full, meta){
                    return data.toFixed(3);
                }},
            {width: "2%",data:"limitNegativeData"},
            {width: "2%",data:"diffNegativeData",render : function(data, type, full, meta){
                    return data.toFixed(3);
                }},
            //闪变
            {width: "2%",data:"overFlickerDay"},
            {width: "2%",data:"maxFlickerData",render : function(data, type, full, meta){
                    return data.toFixed(3);
                }},
            {width: "2%",data:"limitFlickerData"},
            {width: "2%",data:"diffFlickerData",render : function(data, type, full, meta){
                    return data.toFixed(3);
                }},
            //其他次谐波
            {width: "1%",data:"overVoltageThreeTimes"},
            {width: "1%",data:"overVoltageFiveTimes"},
            {width: "1%",data:"overVoltageSevenTimes"},
            {width: "1%",data:"overVoltageElevenTimes"},
            {width: "1%",data:"overVoltageThirteenTimes"},
            {width: "1%",data:"overVoltageTwentyThirdTimes"},
            {width: "1%",data:"overVoltageTwentyFiveTimes"},
            {width: "1%",data:"overVoltageOtherTimes"},
            {width: "1%",data:"overCurrentThreeTimes"},
            {width: "1%",data:"overCurrentFiveTimes"},
            {width: "1%",data:"overCurrentSevenTimes"},
            {width: "1%",data:"overCurrentElevenTimes"},
            {width: "1%",data:"overCurrentThirteenTimes"},
            {width: "1%",data:"overCurrentTwentyThirdTimes"},
            {width: "1%",data:"overCurrentTwentyFiveTimes"},
            {width: "1%",data:"overCurrentOtherTimes"},
            {width: "2%",data:"monitorNumber"}
        ],
        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;
}

//点击导出功能
$('#exportMonitorTable').click(function () {
    var startTime = $startTime.eq(0).val();
    var endTime = $endTime.eq(0).val();
    $("<form method='post' action='/pqs9000/responsibility/exportMonitorExcel?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].overLimitDay<data[j+1].overLimitDay){
                var temp = data[j+1];
                data[j+1] = data[j];
                data[j] = temp;
            }
        }
    }
    return data
}

$('#interval').change(function() {
    var selectedValue = $(this).val();
    if (selectedValue === '天'){
        $('#calculate').css("display","block");
    } else {
        $('#calculate').css("display","none");
    }
});

//点击确定，去后台请求参数
$("#calculate").click(function() {
    var i ;
    startTime = $startTime.eq(0).val();
    endTime = $endTime.eq(0).val();
    layer.msg("后台进行计算,请稍后查看数据",{icon:1,time:2000});
    $.ajax({
        type : "POST",
        url : "/pqs9000/responsibility/manualCalculation",
        dataType : "json",
        data : {
            startTime : startTime,
            endTime : endTime
        }
    });
});


