var $area = $("#area");
var $startTime = $("#startTime");
var $endTime = $("#endTime");
var dataTable = null;
var resultData = null;
var areaInfo;
$("#interval").val("月份");
$(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);
            }
        }
    })

    //初始化区域
    $.ajax({
        type: "POST",
        url: "/pqs9000/user/getAreasInfo",
        dataType: "json",
        success: function (info) {
            if (info != null) {
                for (var i = 0; i < info.length; i++) {
                    $("#areaDepts").append(
                        "<option value='" + info[i].dicIndex + "'>"
                        + info[i].city + "</option>");
                }

            }
        }
    });
})

//点击确定，去后台请求参数
$("#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",
        url: "/pqs9000/area/getOnlineRateData",
        dataType: "json",
        data: {
            startTime: startTime,
            endTime: endTime,
            area: area
        },
        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() - 155;
    var length = Math.floor(height / 28);
    if (length < 1) {
        length = 1;
    }
    dataTable = $("#onlineRatelist").DataTable();
    dataTable.clear().draw();
    dataTable = $('#onlineRatelist').DataTable({
        order: [6, "desc"],
        columnDefs: [
            {
                orderable: false,
                targets: [0]
            }
        ],
        columns: [
            {width: "6%", data: null},
            {width: "15%", data: "powerCompany"},
            {width: "16%", data: "substation"},
            {width: "16%", data: "device"},
            {width: "16%", data: "deviceIp"},
            {width: "16%", data: "company"},
            {
                width: "15%", data: "onlineRate",
                render: function (data, type, full, meta) {
                    var temp = Number(data);
                    if (temp > 100) {
                        return 100;
                    } else if (temp < 0) {
                        return 0;
                    } else {
                        return temp;
                    }
                }
            },
        ],
        destroy: true,
        data: data,
        lengthChange: false,
        searching: true,
        dom: 'rtip',
        scrollY: height,
        // scrollX: false,
        lengthMenu: [length],
        language: {
            url: '/pqs9000/json/chine.json'
        },
        fnDrawCallback: function (oTable) {
            $("#onlineRatelist_info").addClass("fl");
            $("#onlineRatelist_paginate").addClass("fr");
            $("#onlineRatelist_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 = $("#onlineRatelist").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],
                    format: {
                        body: function (data, rID, cID) {
                            if (cID === 0) {
                                return rID + 1;
                            } 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 refreshQuery() {
    var width = $("#onlineRatelist").width();
    if (width > 100) {
        initTable(resultData);
        window.clearInterval(it)
    }
}

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