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

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

$(function () {
    startTime = $startTime.eq(0).val();
    endTime = $endTime.eq(0).val();
    area = $area.eq(0).val();
    postType = $postType.eq(0).val();
    powerId = $powerId.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(area, startTime, endTime,postType,powerId);
            } else {
                tigName = companyname;
                refresh(area, startTime, endTime,postType,powerId);
            }
        }
    });
    //初始化区域
    $.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");
            startTime = $startTime.eq(0).val();
            endTime = $endTime.eq(0).val();
            postType = $postType.eq(0).val();
            powerId = $powerId.eq(0).val();
            refresh(area, startTime, endTime,postType,powerId);
        }
    })
})


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

//获取表格数据
function refresh(area,startTime,endTime,postType,powerId){
    var i ;
    $.ajax({
        type : "POST",
        url : "/pqs9000/area/statisticalAnalysis",
        dataType : "json",
        data : {
            startTime : startTime,
            endTime : endTime,
            area: area,
            postType: postType,
            powerId: powerId
        },
        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 {
                translateData(data.body);
            }
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(i);
        }
    });
}


function translateData(data) {
    var tableData = '';
    for (var i = 0; i < data.length; i++) {
        for (var j = 0; j < data[i].typeLists.length; j++) {
            for (var k = 0; k < data[i].typeLists[j].dataLists.length; k++) {
                tableData += '["","' + data[i].deptName + '", "' + data[i].typeLists[j].name + '","'
                    + data[i].typeLists[j].dataLists[k].name + '","' + data[i].typeLists[j].dataLists[k].allLineCount + '","' + data[i].typeLists[j].dataLists[k].runLineCount + '","'
                    + data[i].typeLists[j].dataLists[k].checkLineCount + '","' + data[i].typeLists[j].dataLists[k].backLineCount + '","';
                if (k === 0) {
                    var n = 0;
                    if (j === 0) {
                        for (var l = 0; l < data[i].typeLists.length; l++) {
                            for (var m = 0; m < data[i].typeLists[l].dataLists.length; m++) {
                                n++;
                            }
                        }
                    }
                    tableData += n + '","' + data[i].typeLists[j].dataLists.length + '"],';
                } else {
                    tableData += '0","0"],'; //前面表示所有行，后面表示自己的行
                }
            }
        }
    }
    tableData = tableData.substring(0, tableData.lastIndexOf(','));
    tableData = eval('[' + tableData + ']');
    console.log("tableData==:" + tableData)
    initTable(tableData);
}

function initTable(data) {
    $('#tongji').dataTable({
        "columns": [
            {"title": "序号"},
            {"title": "区域"},
            {"title": "类型"},
            {"title": "分类型"},
            {"title": "监测点总数"},
            {"title": "监测点投运数"},
            {"title": "监测点检修数"},
            {"title": "监测点退运数"}
        ],
        paging: false,
        scrollY: ($(window).height() * 0.83),
        lengthChange: false,
        language: {
            url: '/pqs9000/json/chine.json',
        },
        searching: false,
        info: false,
        ordering: false,
        destroy: true,
        data: data,
        fnDrawCallback: function () {
            this.api().column(0).nodes().each(function (cell, i) {
                cell.innerHTML = i + 1;
            });
        },
        columnDefs: [{
            targets: 1,
            createdCell: function (td, cellData, rowData, row, col) {
                var rowspan = rowData[8];

                if (rowspan > 1) {
                    $(td).attr('rowspan', rowspan)
                }
                if (rowspan == 0) {
                    $(td).remove();
                }
            }
        }, {
            targets: 2,
            createdCell: function (td, cellData, rowData, row, col) {
                var rowspan = rowData[9];

                if (rowspan > 1) {
                    $(td).attr('rowspan', rowspan)
                }
                if (rowspan == 0) {
                    $(td).remove();
                }
            }
        }]
    });
}


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);
                })
            }
        }
    })
}

//特殊处理，表头紧缩问题--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;
}