var $area = $("#area");
var $startTime = $("#startTime");
var $endTime = $("#endTime");
var $timeType = $("#interval");
var dataTable = null;
var resultData = null;
var areaInfo;
var buttonname = '';
var companyname;
var tiggleValue = "";
var allNetsData = [];
var countryNetsData = [];
var data1;
var data2;
var data3;
var data4;
$("#interval").val("月份");
/**
 * 电压等级排序自定义比较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
 */
$(function () {
    //初始化区域
    $.ajax({
        type: "POST",
        url: "/pqs9000/user/getAreasInfo",
        dataType: 'json',
        success: function (data) {
            areaInfo = data;
            $("#area").val(data[0].name);
            $("#area").attr("index", data[0].id);
            areaTree = $.fn.zTree.init($("#areaTree"), settingAreaTree, data);
            //初始化页面内容
            var sTemp = $("#_startTime").val();
            var eTemp = $("#_endTime").val();
            var aTemp = $("#_area").val();
            var iTemp = $("#_interval").val();
            sTemp = filterXSS(sTemp);
            eTemp = filterXSS(eTemp);
            aTemp = filterXSS(aTemp);
            iTemp = filterXSS(iTemp);
            if (sTemp === "" | sTemp === undefined) {
                var area = $area.eq(0).attr("index");
                var startTime = $startTime.eq(0).val();
                var endTime = $endTime.eq(0).val();
                refresh(area, startTime, endTime);
            } else {
                //填充区域、时间输入框
                $("#startTime").val(sTemp);
                $("#endTime").val(eTemp);
                $("#interval").val(iTemp);
                judgeInterval(iTemp);
                if (aTemp === "" | aTemp === undefined) {
                    aTemp = $area.eq(0).attr("index");
                } else {
                    $area.eq(0).val(getDeptsName(aTemp));
                    $area.eq(0).attr("index", aTemp);
                }
                refresh(aTemp, sTemp, eTemp);
            }
        }
    });

    var start = $startTime.eq(0).val();
    var end = $endTime.eq(0).val();
    $.ajax({
        type: "POST",
        data: {
            start: start,
            end: end
        },
        async: false,
        url: "/pqs9000/device/getMsgInfo",
        dataType: 'json',
        success: function (data) {
            buttonname = data.body.name;
            tiggleValue = data.body.name;
        }
    });

    $.ajax({
        type: "POST",
        url: "/pqs9000/theme/getThemeInfo",
        async: false,
        dataType: 'json',
        success: function (data) {
            companyname = data.body.name;
        }
    });
    //初始化页面内容(1是国网 0是全部)
    if (gwType.val() == '1') {
        tiggleValue="国网";
        $("#checkbox").prop('checked', false);
    } else {
        $("#checkbox").prop('checked', true);
    }
    //开关初始化
    $(".wanzheng").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) {
                tiggleValue = buttonname;
                initTable(allNetsData);
                $('#online').text(data1===null?0:data1);
                $('#offline').text(data2===null?0:data2);
            } else {
                tiggleValue = companyname;
                initTable(countryNetsData);
                $('#online').text(data3===null?0:data3);
                $('#offline').text(data4===null?0:data4);
            }
        }
    });

});

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

//获取表格数据
function refresh(area, startTime, endTime,devflag,powerId,runFlag) {
    var i;
    $.ajax({
        type: "POST",
        url: "/pqs9000/area/getIntegrityData",
        dataType: "json",
        data: {
            startTime: startTime,
            endTime: endTime,
            area: area,
            devflag:devflag,
            powerId:powerId,
            runFlag:runFlag
        },
        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;
                data1 = null;
                data2 = null;
                data3 = null;
                data4 = null;
            } else {
                allNetsData = data.body.allNets;
                countryNetsData = data.body.countryNets;
                data1 = data.body.allOnlineNum;
                data2 = data.body.allOfflineNum;
                data3 = data.body.countryOnlineNum;
                data4 = data.body.countryOfflineNum;
            }
            startQuery();
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(i);
        }
    });
}

//实例化表格
function initTable(data) {
    var height = $(window).height() - 155;
    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]
            }
        ],
        columns: [
            {width: "4%", 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: "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: "8%", data: "deviceIp"},
            {width: "6%", data: "frontDev"},
            {
                width: "5%", data: "devFlag", render: function (data, type, full, meta) {
                    var temp = Number(data);
                    switch (temp) {
                        case 0:
                            return "投运";
                        case 1:
                            return "检修";
                        case 2:
                            return "退运";
                    }
                }
            },
            {
                width: "5%", data: "status", render: function (data, type, full, meta) {
                    var temp = Number(data);
                    switch (temp) {
                        case 0:
                            return "中断";
                        case 1:
                            return "正常";
                    }
                }
            },
            {width: "10%", data: "updateTime"},
            {
                width: "8%", 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: "device"},
            {width: "8%", data: "company"},
            {width: "5%", data: "voltage", type: "number-fate"},
            {
                width: "12%", data: "", render: function (data, type, full, meta) {
                    let button;
                    if (full.devType!=null && full.devType.indexOf("CLD") != -1) {
                        button = "<div>" +
                            "<button type='button' class='btn btn-primary' style='float: left;margin-left: 5px' onclick='socketSend(\"" + full.lineId + "\",\"" + full.devId + "\",\"" + full.substation + "\",\"" + full.lineName + "\")'>数据补招</button>" +
                            "<button id='integrityDetail' type='button' class='btn themeBGColor' style='float: left;margin-left: 5px' onclick='showDetail(\"" + full.lineId + "\")'>详情</button>" +
                            "</div>"
                    } else {
                        button = "<div>" +
                            "<button type='button' class='btn themeBGDisableColor' disabled style='float: left;margin-left: 5px' href='javascript:void(0);'>数据补招</button>" +
                            "<button id='integrityDetail' type='button' class='btn themeBGColor' style='float: left;margin-left: 5px' onclick='showDetail(\"" + full.lineId + "\")'>详情</button>" +
                            "</div>";
                    }
                    return button;
                }
            },
        ],
        destroy: true,
        data: data,
        lengthChange: false,
        searching: true,
        dom: 'rtip',
        scrollY: height,
        scrollX: true,
        lengthMenu: [length],
        language: {
            url: '/pqs9000/json/chine.json'
        },
        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);
            });
        }
    });
    var name = $area.find("option:selected").text();
    new $.fn.dataTable.Buttons(dataTable, {
        buttons: [
            {
                extend: 'csv',
                title: name + '数据完整性',//导出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 socketSend(lineId,devId,subName,lineName) {
    layer.open({
        type: 2,
        title: '数据补招',
        maxmin: false,
        shadeClose: true, // 点击遮罩关闭层
        area: ['25%', '70%'],
        content: '/pqs9000/business/timerange?lineId='+lineId+"&devId="+devId+"&titleName="+subName+"_"+lineName,
        scrollbar: false
    });
}

//查看完整性详情
function showDetail(lineId) {
    var startTime = $startTime.eq(0).val();
    var endTime = $endTime.eq(0).val();
    var timeType = $timeType.eq(0).val();
    if (timeType === '自定义'){
        layer.msg("暂不支持自定义的维度查看", {icon: 2, time: 2000})
    } else {
        layer.open({
            type: 2,
            title: '数据完整性详情',
            maxmin: false,
            shadeClose: true, // 点击遮罩关闭层
            area: ['100%', '100%'],
            content: '/pqs9000/business/integralityDetail?startTime=' + startTime + "&endTime=" + endTime + "&timeType=" + timeType + "&lineId=" + lineId,
            scrollbar: false
        });
    }
}

function showAnalysis() {
    layer.open({
        type: 2,
        title: '监测点统计分析',
        maxmin: false,
        shadeClose: true, // 点击遮罩关闭层
        area: ['100%', '100%'],
        content: '/pqs9000/business/statisticalAnalysis',
        scrollbar: false
    });
}



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 refreshQuery() {
    var width = $("#integritylist").width();
    if (width > 100) {
        if (tiggleValue === buttonname) {
            initTable(allNetsData);
            $('#online').text(data1===null?0:data1);
            $('#offline').text(data2===null?0:data2);
        } else {
            initTable(countryNetsData);
            $('#online').text(data3===null?0:data3);
            $('#offline').text(data4===null?0:data4);
        }
        window.clearInterval(it)
    }
}

//特殊处理，表头紧缩问题--end


