var dataTable;
var height = $(window).height()
var pqge = 1;
var charts =null;

$("#interval").val("月份");
//下拉框禁用
$("#interval").prop("disabled", true);
$(function () {
    $('#div_height').css('height',height-50)
    refresh()


    //点击查询按钮
    $("#query").on("click", function () {
        refresh();
    });

    $('#shai').click(function () {
        let con = $('#content').val()
        searchResult(con)
    })
})

var mealAll = ''
var mealUse = ''
var mealBi = ''
//初始化图表数据
function initDate(arr) {
    if(arr!=null && arr.length>0){
    var i;
    let map = {
        startTime:$('#startTime').val(),
        list:arr,
        mealBi:mealBi,
        mealUse:mealUse,
        mealAll:mealAll,
    }
    $.ajax({
        type: 'post',
        url: '/pqs9900/terminalmanger/getFlowStatiscsList',
        dataType: "json",
        contentType: 'application/json;charset=UTF-8',
        data:JSON.stringify(map),
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER()
        },
        success: function (data) {
            let arr = data.body
            if (data.code == 200) {
                init(arr)
                //***********关闭loading
                ityzl_CLOSE_LOAD_LAYER(i);
            }

        },
        error: function () {
            layer.msg('未知错误', {icon: 2})
        }
    })
    }else {
        init(arr)
    }
}


/**
 * 初始化获取后台数据
 */
function refresh() {
    /*获取各项条件 */
    let start = $('#startTime').val()
    let times = start.split("-")
    start = times[0]+"-"+times[1]
    var indexi;
    $.ajax({
        type: "get",
        url: "/pqs9900/terminalmanger/getTerminalList",
        dataType: "json",
        data: {
            status: null,
            devType: null,
            startTime:start
        },
        beforeSend: function () {
            indexi = ityzl_SHOW_LOAD_LAYER();
        },
        success: function (data) {
            if (data.code === 200) {
                let arr = data.body
                //初始化表格
                initTransactionTable(arr);
            } else {
                layer.msg(data.message, {icon: 2, time: 2000})
                initTransactionTable(null);
            }
            ityzl_CLOSE_LOAD_LAYER(indexi);
        }
    })
}

function init(data) {
        var arrName = data.map(function (item) {
            return item.devName
        })
        var arrActual =[]
        var arrAll =[]
    let obj=null;
    if(data.length >0){
        data.forEach(function (item) {
            if(item.actualflow>=item.allFlow){
                obj={y:item.actualflow,color:'red',devIndex:item.devIndex}
            }else {
                obj={y:item.actualflow,devIndex:item.devIndex}
            }
            arrActual.push(obj)
            arrAll.push({y:item.allFlow,devIndex:item.devIndex})

        })
    }
        charts = Highcharts.chart('flow_sta', {
            chart: {
                marginBottom:70,
                height:height-70,
                type: 'column',
                borderWidth: 1,
                borderColor:'#d9d9d9',
                plotBorderWidth: 1,
                spacingRight:50,
                inverted: true,
                backgroundColor: canvasBG,//背景色
                /*events:{
                    click:function (e) {
                        console.log(e.xAxis[0].value)
                    }
                }*/

            },
            title: {
                text: ''
            },
            xAxis: [{
                tickPixelInterval:10,
                tickmarkPlacement:-0.1,
                categories: arrName,
                labels:{
                    autoRotation:[15],
                    formatter:function () {
                        return this.value
                    }
                },

            }],
            yAxis: [{
                min:0,
                offset:3,
                labels: {
                    format: '{value}M',
                },
                opposite:true,
                //  minorGridLineColor: '#C5EEFA',
                tickPixelInterval: 55,
                title: {
                    text: false,

                    /*style: {
                        color: Highcharts.getOptions().colors[2]
                    }*/
                },
            }],
            plotOptions: {
                column: {
                    dataLabels: {
                        // 开启数据标签
                        enabled: true,
                        formatter: function() {
                            if(this.point.y !=0){
                                return  this.point.y;
                            }else {
                                return  "";
                            }

                        },
                    },
                    grouping: false,
                    shadow: false,
                    borderWidth: 0,

                },
                series: {
                    cursor: 'pointer',
                    events: {
                        click: function (event) {
                            let devIndex = event.point.devIndex
                            let devName = event.point.category
                            layer.open({
                                type: 2,
                                title: '流量使用情况',
                                maxmin: false,
                                area: ['100%', '100%'],
                                content: 'flowdetail?devIndex=' + devIndex+'&devName='+devName+'&flag=2',
                                scrollbar: false,
                                end: function () {
                                   // refresh();
                                }
                            })
                        }
                    }
                }
            },
            exporting:{
                buttons: {
                    contextButton:{
                        align:'left',
                        enabled:true
                    }
                },
            },
            credits:{
                enabled: false // 禁用版权信息
            },
            tooltip: {
                shared: true,
                valueDecimals: 2
            },
            legend: {
                align: 'center',
            },
            series: [{
                name: '套餐总量',
                type: 'column',
                color: orange,
                data: arrAll,
                pointWidth:18,
                pointPlacement:0.1
            },{
                name: '流量使用量',
                type: 'column',
                color: green,
                data: arrActual,
                // barMaxWidth: barMax,
                dataLabels:{
                    formatter:function () {
                        if(this.y!=0){
                            return this.y.toFixed(2)
                        }else {
                            return ''
                        }
                    }
                },
              pointWidth:10,
              pointPlacement:0.1
            }]
        });


}

//初始化表格数据
function initTransactionTable(tableData) {
    $("#deviceTable").css('height',height-150)
   let tdHeight = (height-250)/10;

    dataTable = $("#deviceTable").DataTable();
    dataTable.clear().draw();
    dataTable = $('#deviceTable').DataTable({
        order: [8,'asc'],
        columns: [
            {data: "devIndex",visible:false},
            {width: "20px", data:null,orderable:false},
            {width: "100px", data: "name",orderable:false},
            {width: "110px", data: "gdName",orderable:false},
            {width: "110px", data: "bdName",orderable:false},
            {width: "150px", data: "ip",orderable:false},
            {width: "80px",render:function (data, type, full, meta) {
                    return full.baseFlow+full.extendFlow
                }},
            {width: "150px", data: "actualflow",render:function (data, type, full, meta) {
                    return Number(full.actualflow).toFixed(2)
                }},
            {width: "150px", render:function (data, type, full, meta) {
                    let all =  Number(full.baseFlow)+Number(full.extendFlow)
                    let use =all - Number(full.actualflow)
                    return (Number(use/all)*100).toFixed(2)+'%'
                }},

        ],
        destroy: true,
        data: tableData,
        lengthChange: true,
        searching: true,
        dom: 'rtip',
        scrollY: height-150,
        scrollX: true,
        lengthMenu: [10],
        language: {
            url: '/pqs9900/json/chine.json'
        },
        fnDrawCallback: function (oTable) {
            var api = this.api();
            api.column(1).nodes().each(function(cell, i) {
                cell.innerHTML =  i + 1;
            });
            $("#deviceTable_info").addClass("fl");
            $("#deviceTable_paginate").addClass("fr");
            $("#deviceTable_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 = $("#deviceTable").dataTable();
            var redirectpage;
            $('#dataTable-btn').click(function (e) {
                if ($("#changePage").val() && $("#changePage").val() > 0) {
                     redirectpage = $("#changePage").val() - 1;
                } else {
                     redirectpage = 0;
                }
                table.fnPageChange(redirectpage);
            });


            let obj = oTable.aLastSort[0]
            console.log(obj)

            let name =obj.dir
            if(obj.src == 8){
                mealBi = name
                mealAll = ''
                mealUse = ''
            }else if(obj.src == 7){
                mealBi = ''
                mealAll = ''
                mealUse = name
            }else if(obj.src == 6){
                mealBi = ''
                mealAll = name
                mealUse = ''
            }
            let arr =[]
            api.column(0,{ page:'current'}).nodes().each(function(cell, i) {
                arr.push(cell.innerHTML)
            });

            initDate(arr)
            $(".odd").find("td").css("height",tdHeight)
            $(".even").find("td").css("height",tdHeight)
        },


    });
}



//搜索表中的数据
function searchResult(value) {


    dataTable.search(value).draw();
}
