var dataTable;
var resultData = null;
var areaInfo;
var companyname;
var allNetsData = [];
var countryNetsData=[];
var height = $(window).height() - 125;
$("#interval").val("月份");

/**
 * 电压等级排序自定义比较end
 */
$(function () {
    initselect()
    refresh(startTime, endTime,0,0);
    $.ajax({
        type: "POST",
        url: "/pqs9900/theme/getThemeInfo",
        async: false,
        dataType: 'json',
        success: function (data) {
            companyname = data.body.name;
        }
    });




});

//点击确定，去后台请求参数
$("#query").click(function () {

    refresh();
});

//获取表格数据
function refresh() {
    var startTime = $("#startTime").val();
    var endTime =$("#endTime").val();
    var lineGrade = $("#selectId").val();
    var isRight =$("#isRight").val()
    var i;
    $.ajax({
        type: "POST",
        url: "/pqs9900/inStrategy/getIntegrityData",
        dataType: "json",
        data: {
            startTime: startTime,
            endTime: endTime,
            lineGrade:lineGrade,
            colorFlag:isRight
        },
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER();
        },
        success: function (data) {
            if (data.code === 500) {
                layer.msg(data.message, {icon: 2, time: 2000})
                //没有数据
                allNetsData = null;
                countryNetsData = null;
            } else {
                allNetsData = data.body.allNets;
                countryNetsData =data.body.countryNets;
            }
            startQuery();
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(i);
        }
    });
}

//实例化表格
function initTable(data) {

    var length = Math.floor(height / 28);
    if (length < 1) {
        length = 1;
    }
    dataTable = $("#integritylist").DataTable();
    dataTable.clear().draw();
    dataTable = $('#integritylist').DataTable({
        order: [8, "desc"],
        columnDefs: [
            {
                orderable: false,
                targets: [0,12]
            }
        ],
        columns: [
            {width: "3%", data: null},
            {width: "8%", data: "powerCompany", 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: "10%", data: "substation", 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: "8%", data: "voltage", type: "number-fate"},
            {width: "8%", data: "lineName" , render:function (data, type, full, meta) {
                    var value=data;
                    if(data.length>12){
                        value=data.substring(0,11)+"...";
                        value="<span title="+data+">"+value+"</span>";
                    }
                    return value;
                }},
            {width: "5%", data: "lineGrade",render:function (data, type, full, meta) {
                    if(data == 0){
                        return "极重要"
                    }else if(data == 1){
                        return "重要"
                    }else if(data == 2){
                        return "普通"
                    }else if(data == 3){
                        return "不重要"
                    }else{
                        return "/"
                    }
                }},
            {
                width: "5%", data: "integrity",
                render: function (data, type, full, meta) {
                    var temp = Number(data);
                    if (temp > 100) {
                        return 100;
                    } else if (temp < 0) {
                        return 0;
                    } else {
                        return temp;
                    }
                }
            },
            {width: "8%", data: "deviceIp"},

            {width: "5%", data: "status",render:function (data, type, full, meta) {
                    var temp = Number(data);
                    switch (temp){
                        case 0:
                            return "中断";
                        case 1:
                            return "正常";
                    }
                }},
            {width: "8%", data: "updateTime"},

            {width: "8%", data: "device"},
            {width: "10%", data: "company"},

            {width: "8%", data: "lineId",
                render: function (data, type, full, meta) {
                var lineGradeStr = full.colorFlag;
                var lineGrade = full.lineGrade;
                var uploadck = "";
                if(lineGradeStr==0 ){
                    uploadck = "<button type='button' class='btn themeBGDisableColor'" +
                        " style='margin-right:10px;' href='javascript:void(0);' onclick='viewBZ(\"" + full.lineId + "\",\""+lineGrade+"\")' >数据补招</button>";
                }else {
                    uploadck = "<button type='button' class='btn themeBGDisableColor' style='margin-right:10px;' href='javascript:void(0);' disabled='true' >数据达标</button>";
                }
                return uploadck;
            }
            }
        ],
        destroy: true,
        data: data,
        lengthChange: false,
        searching: true,
        dom: 'rtip',
        scrollY: height,
        scrollX: true,
        lengthMenu: [length],
        language: {
            url: '/pqs9900/json/chine.json'
        },
        createdRow: function (row, data, index) {
            if (data.colorFlag == 0) {
                $('td', row).eq(6).css('color', '#ED1C24')
            }


        },
        fnDrawCallback: function (oTable) {
            $("#integritylist_info").addClass("fl");
            $("#integritylist_paginate").addClass("fr");
            $("#integritylist_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 = $("#integritylist").dataTable();
            $('#dataTable-btn').click(function (e) {
                if ($("#changePage").val() && $("#changePage").val() > 0) {
                    var redirectpage = $("#changePage").val() - 1;
                } else {
                    var redirectpage = 0;
                }
                table.fnPageChange(redirectpage);
            });
        }
    });

    new $.fn.dataTable.Buttons(dataTable, {
        buttons: [
            {
                extend: 'csv',
                title: '数据完整性'+new Date().getTime(),//导出csv名称
                exportOptions: {
                    columns: [0, 1, 2, 3, 4, 5, 6, 7, 8,9,10,11],
                    format: {
                        body: function (data, rID, cID) {
                            if (cID === 0) {
                                return rID + 1;
                            }else if(cID===1|cID===2|cID===3){
                                if(data.indexOf("title")>0){
                                    return data.substring(data.indexOf("=")+1,data.indexOf(">"));
                                }else{
                                    return data
                                }
                            }else {
                                return data;
                            }
                        }
                    }
                }
            }
        ]
    });
    modifyCss(dataTable);
    dataTable.on('order.dt search.dt',
        function () {
            dataTable.column(0, {
                search: 'applied',
                order: 'applied'
            }).nodes().each(function (cell, i) {
                cell.innerHTML = i + 1;
            });
        }).draw();
}

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().appendTo('.header');
    dataTable.buttons().container().after($("#fliteData")[0]);
}

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

//特殊处理，表头紧缩问题--start
var it = null;

function startQuery() {
    //实时刷新时间单位为毫秒
    it = setInterval('refreshQuery()', 100);

}
/*手动补招数据*/
function viewBZ(lineId,lineGrade){
    var startTime = $("#startTime").val();
    var endTime =$("#endTime").val();
    var interval =$("#interval").val();
    var reachMark = 0;
    $("#start").val(startTime);
    $("#end").val(endTime);
    $.ajax({
        type: "get",
        url: "/pqs9900/inStrategy/queryListForRun",
        dataType: 'json',
        success: function (data) {
            let da =  data.body;
            if(da.length!=0){
                da.forEach(function (item,index) {
                    if(item.dicLeave == lineGrade){
                        reachMark = item.integrityValue;
                        $("#lineIndex").val(lineId);
                        $("#reachMark").val(reachMark);
                        $("#intervaldata").val(interval);
                        layer.open({
                            type: 2,
                            title: '完整性统计',
                            shadeClose: true,
                            resize: false,
                            shade: 0.3,
                            area: ['100%', '100%'],
                            content: 'dataIntegrityStatis', //iframe的url
                            scrollbar: false,
                            end: function () {
                                layer.close();
                            }
                        });
                    }
                })
            }
        }
    })

}
/* 刷新查询 */
function refreshQuery() {
    var width = $("#integritylist").width();
    if (width > 100) {
        initTable(allNetsData);
        window.clearInterval(it)
    }
}

//特殊处理，表头紧缩问题--end
/**
 * 电压等级排序自定义比较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);
};



function initselect(){
    var option = "<option value=''>全部</option>";
    $.ajax({
        method: "post",
        url: "/pqs9900/device/getselect",
        data: {
            dictypeName: '终端等级'
        },
        dataType: 'json',
        async: false,
        success: function (data) {
            for (var i = 0; i < data.length; i++) {

                option = option + "<option value='"
                    + data[i].dicLeave + "'>"
                    + data[i].dicName + "</option>";

            }
            $("#selectId").empty()
            $("#selectId").append(option)
            $("#selectId").val(0)
        }
    })
}

$("#infomation").click(function () {
    layer.open({
        type: 2,
        title: '告警策略查看',
        maxmin : false,
        shadeClose: true, //点击遮罩关闭层
        area : ['100%' , '100%'],
        content : '/pqs9900/business/terminalrunstrategy',
        scrollbar : false

    });
})
