var $area = $("#area");
var loading;
var resultData;
var dataTable;
var area = null;

$(function () {
    $.ajax({
        type: "POST",
        url: "/pqs9200/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);
            // areaInfo = data;
            //初始化页面内容
            var aTemp = $("#_area").val();
            aTemp = filterXSS(aTemp);
            if (aTemp === "" || aTemp === undefined) {
                aTemp = $area.eq(0).attr("index");
            } else {
                $area.eq(0).val(getDeptsName(aTemp));
                $area.eq(0).attr("index", aTemp);
            }
            area = aTemp;


        }
    })
    getMonitorType();
    initData(1)
    initValue("type");
    initValue("voltage");
    initValue("appear");
    setCSS();
    getSelect("电压等级")
    getSelect("干扰源类型")

})

$("#query").click(function () {
    initData(2)
});

function getOptions(id) {
    var data = $('#' + id).selectpicker('val');
    var array = [];

    if (data != null) {
        for (var i = 0; i < data.length; i++) {
            array.push(data[i])
        }
    }

    return array;
}


function initData(type) {
    let obj;
    if (type == 1) {
        obj = {
            status: null,
            areaList: null,
            voltage: null,
            loadType: null,
            appear: null,
        }
    } else {
        let scale = getOptions("voltage")
        let type = getOptions("type")
        let status = $("#status").val()
        let appear = $("#appear").val()
        area = $area.eq(0).attr("index");
        let dept = []
        dept.push(area)

        scale.find(function (item) {
            if (item == -1) {
                scale = null;
            }
        })
        type.find(function (item) {
            if (item == -1) {
                type = null;
            }
        })
        obj = {
            status: status,
            areaList: dept,
            voltage: scale,
            loadType: type,
            appear: appear
        }
    }

    $.ajax({
        type: "POST",
        contentType: 'application/json;charset=UTF-8',
        url: "/pqs9200/getLineLedger",
        dataType: "json",
        data: JSON.stringify(obj),
        beforeSend: function () {
            loading = 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;
            }
            initTable(resultData);
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(loading);
        }
    });
}


//实例化表格
function initTable(data) {
    var height = $(window).height() - 140;
    dataTable = $("#lineLedger").DataTable();
    dataTable.clear().draw();
    dataTable = $('#lineLedger').DataTable({
        order: [[1, 'asc'], [2, 'asc']],
        columnDefs: [
            {
                orderable: false,
                targets: [0]
            }
        ],
        columns: [
            {width: "0%",data:null},
            {width: "6%", data: "province"},
            {width: "7%", data: "gdName"},

            {width: "3%", data: "scale"},
            {width: "7%", data: "lineName"},
            {width: "4%", data: "subName"},
            {width: "7%", data: "loadType"},
            {
                width: "3%", data: "objName", render: function (data) {
                    return data == null ? '/' : data;
                }
            },
            {width: "3%", data: "powerSubstationName"},
            {width: "3%", data: "dlCmp"},
            {width: "3%", data: "devCmp"},
            {width: "3%", data: "xyCmp"},
            {
                width: "7%", data: "status", render: function (data) {
                    if (data == 1) {
                        return "正常"
                    } else {
                        return "中断"
                    }
                }
            },
            {width: "3%", data: "lineStatus"},
            {width: "3%", data: "lineNum"},
            {width: "3%", data: "devName"},
            {width: "3%", data: "nodeName"},
            {width: "3%", data: "monitorId", render: function (data, type, full, meta) {
                    if (data == null || data === ' '){
                        return "/"
                    }
                    return data;
                }
            },
            {
                width: "6%", data: "ptType", render: function (data, type, full, meta) {
                    switch (data) {
                        case 0:
                            return "星型接法";
                        case 1:
                            return "三角型接法";
                        case 2:
                            return "开口三角型接法";
                        default:
                            return "错误"

                    }
                }
            },
            {width: "8%", data: "voltageDev"},
            {width: "7%", data: "uVoltageDev"},
            {width: "7%", data: "freqDev"},
            {width: "7%", data: "uBalance"},
            {width: "10%", data: "iNeg"},
            {width: "10%", data: "flicker"},
            {width: "10%", data: "aberrance"},
            {width: "10%", data: "uharm3"},
            {width: "10%", data: "uharm2"},
            {width: "10%", data: "iharm2"},
            {width: "10%", data: "iharm3"},
            {width: "10%", data: "iharm4"},
            {width: "10%", data: "iharm5"},
            {width: "10%", data: "iharm6"},
            {width: "10%", data: "iharm7"},
            {width: "10%", data: "iharm8"},
            {width: "10%", data: "iharm9"},
            {width: "10%", data: "iharm10"},
            {width: "10%", data: "iharm11"},
            {width: "10%", data: "iharm12"},
            {width: "10%", data: "iharm13"},
            {width: "10%", data: "iharm14"},
            {width: "10%", data: "iharm15"},
            {width: "10%", data: "iharm16"},
            {width: "10%", data: "iharm17"},
            {width: "10%", data: "iharm18"},
            {width: "10%", data: "iharm19"},
            {width: "10%", data: "iharm20"},
            {width: "10%", data: "iharm21"},
            {width: "10%", data: "iharm22"},
            {width: "10%", data: "iharm23"},
            {width: "10%", data: "iharm24"},
            {width: "10%", data: "iharm25"},
            {width: "10%", data: "inuharm2"},
            {width: "10%", data: "inuharmAll"},
        ],
        autoWidth: true,
        destroy: true,
        data: data,
        lengthChange: false,
        searching: true,
        dom: 'rtip',
        scrollY: height,
        scrollX: true,
        lengthMenu: [50],
        language: {
            url: '/pqs9200/json/chine.json'
        },
        createdRow: function ( row, data, index ) {
            if(data.status=="1"){
                $('td', row).eq(12).css('color','#00ff04')
            }else if(data.status=="0"){
                $('td', row).eq(12).css('color','#ED1C24')
            }


        },
        fnDrawCallback: function (oTable) {
            $("#lineLedger_info").addClass("fl");
            $("#lineLedger_paginate").addClass("fr");
            $("#lineLedger_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 = $("#lineLedger").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: '监测点台账信息',//导出csv名称
                exportOptions: {

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

function initValue(id) {
    $("#" + id).selectpicker('val', '-1');
}

$('#voltage').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {
    if (clickedIndex != null) {
        var value = document.getElementById("voltage").options[clickedIndex].value;

        if ((value === '-1' && previousValue.length > 0 && previousValue[0] != '-1') || (value != '-1' && previousValue[0] === '-1')) { //清空并重新选中
            $('#voltage').selectpicker('deselectAll');
            $('#voltage').selectpicker('val', value);
            $('#voltage').selectpicker('refresh');
        }
    }
});

$('#type').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {
    if (clickedIndex != null) {
        var value = document.getElementById("type").options[clickedIndex].value;

        if ((value === '-1' && previousValue.length > 0 && previousValue[0] != '-1') || (value != '-1' && previousValue[0] === '-1')) { //清空并重新选中
            $('#type').selectpicker('deselectAll');
            $('#type').selectpicker('val', value);
            $('#type').selectpicker('refresh');
        }
    }
});


function setCSS() {
    //$('.bootstrap-select').find('button').eq(0).addClass('form-control');dropdown-toggle
    $('.dropdown-toggle').addClass('form-control');
}


function getSelect(dictypeName) {
    $.ajax({
        type: "post",
        url: "/pqs9200/device/getselect",
        dataType: "json",
        data: {dictypeName: dictypeName},
        success: function (data) {
            if (data.length != 0) {
                let html = '<option value="-1">全部</option>'
                for (let i = 0; i < data.length; i++) {
                    let option = '<option value="' + data[i].dicIndex + '">' + data[i].dicName + '</option>'
                    html += option;
                }
                if (dictypeName == '干扰源类型') {
                    $('#type').empty();
                    $('#type').append(html)
                    $('#type').selectpicker('val', '-1');
                    $('#type').selectpicker('refresh');
                } else if (dictypeName == '电压等级') {
                    $('#voltage').empty();
                    $('#voltage').append(html)
                    $('#voltage').selectpicker('val', '-1');
                    $('#voltage').selectpicker('refresh');
                } else {

                }


            }
        }
    });

}

function getMonitorType(){
    $.ajax({
        type: "POST",
        url: "/pqs9200/theme/getThemeInfo",
        async: false,
        data: {},
        dataType: 'json',
        success: function (data) {
            areaName = data.body.name;
            var name = data.body.name + "上报";
            var name2 = "非" + data.body.name + "上报";
            loadColor = data.body.value;
            var option = $("<option value='0'>" + name + "</option>");
            var option2 = $("<option value='1'>" + name2 + "</option>");
            $('#appear').append(option);
            $('#appear').append(option2);
        }
    })
}