var dataTable;
var titleName='日均流量';
var flag=getQueryString("flag")

var devIndex=null;
devIndex= getQueryString("devIndex")

var devName =getQueryString("devName")
$("#interval").val("月份");
//下拉框禁用
$("#interval").prop("disabled", true);
$(function () {
    loadselect('装置功能')
    $("#wanzheng").show()
    //获取当前日期
    $("#wanzheng").bootstrapSwitch({
        onText: "日累计",      // 设置ON文本
        offText: "月累计",    // 设置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) {
                titleName = '日均流量';
            } else {
                titleName = '日流量增长';
            }
            //重新画图
            reDrawAllPic();
        }
    });

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

    refresh();


});

//开关触发图片更新
function reDrawAllPic() {
    queryData();
}

function queryData() {
    refresh();
}

/**
 * 初始化获取后台数据
 */
function refresh() {
    if(devIndex==null){
        return
    }
    var startTime = $("#startTime").val();
    let strs = startTime.split("-");
    startTime = strs[0] + "-" + strs[1]
    var indexi;
    $.ajax({
        type: "POST",
        url: "/pqs9900/flow/getFlowDayDetail",
        data: {
            startTime: startTime,
            devIndex: devIndex
        },
        async: false,
        beforeSend: function () {
            indexi = ityzl_SHOW_LOAD_LAYER();
        },
        success: function (data) {
            if (data.code === 500) {
                layer.msg(data.message, {icon: 2, time: 2000})
            } else {
              var  resultData = data.body;
                if (titleName == "日均流量") {
                    flowChart(resultData);
                    $("#flow_month2").hide();//隐藏
                    $("#flow_month").show();//显示
                } else {
                    flowChart2(resultData);
                    $("#flow_month").hide();//隐藏
                    $("#flow_month2").show();//显示
                }
            }
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(indexi);
        }
    })
    /*获取各项条件 */

     $.ajax({
         type: "post",
         url: "/pqs9900/terminalmanger/getTerminalFlowDetail",
         dataType: "json",
         data: {devIndex:devIndex,startTime:$("#startTime").val()},
         success: function (data) {
             if (data.code === 200) {
                     //初始化表格
                     initTransactionTable([data.body]);
             } else {
                 layer.msg(data.message, {icon: 2, time: 2000})
                 initTransactionTable(null);
             }
         }
     })
}

//初始化表格数据
function initTransactionTable(tableData) {
    dataTable = $("#deviceTable").DataTable();
    dataTable.clear().draw();
    dataTable = $('#deviceTable').DataTable({
        columnDefs: [
            {
                orderable: false,
                targets: [0,1,2,3,4]
            }
        ],
        columns: [
            {width: "20%", data: "timeid"},
            {width: "20%",render:function (data,type,full,meta) {
                    return Number(full.baseFlow)+Number(full.extendFlow)
                }},
            {width: "20%", data: "statFlow",render:function (data) {
                    if(data==null){
                        return 0
                    }else {
                        return Number(data).toFixed(2)
                    }

                }},
            {width: "20%", data: "actualflow",render:function (data,type,full,meta) {
                    return Number(data).toFixed(2)
                }},
            {
                data: "timeid", render: function (data, type, full, meta) {
                    return "<button type='button' class='btn themeBGColor' style='margin-right:10px;' href='javascript:void(0);'  onclick='flowMealtoUrl()' >流量套餐配置</button>"
                }
            }
        ],
        destroy: true,
        paging:false,
        bInfo:false,
        data: tableData,
        lengthChange: false,
        searching: true,
        dom: 'rtip',
        language: {
            url: '/pqs9900/json/chine.json'
        },
    });
}


//跳转流量管理页面
function flowMealtoUrl() {
    layer.open({
        type: 2,
        title: '流量配置',
        maxmin: false,
        area: ['100%', '100%'],
        content: 'flowcombo?type=2&devIndex='+devIndex,
        scrollbar: false,
    })
}


//初始化月流量图表
function flowChart(resultData) {
    var heightchar = $(window).height()-150
    $("#flow_month").css('height', heightchar);
    var x = [];
    var y = [];
    if (null != resultData) {
        for (var i = 0; i < resultData.length; i++) {
            let eValue = Number(resultData[i].dayFlow.toFixed(2));
            if(eValue>resultData[i].avgFlow){
                y.push({y:eValue,color:'red'})
            }else {
                y.push({y:eValue,color:'green'})
            }


            var strsss = new Array();
            strsss = resultData[i].timeId.split("-");
            x[i] = strsss[2];
        }
        strss = resultData[0].timeId.split("-");
        //aveDataPlan = parseFloat(dataPlan/resultData.length).toFixed(2);
    }
    var timeMonth = strss[0] + "-" + strss[1];

    var chart = Highcharts.chart('flow_month',{
        chart: {
            type: 'column',
            backgroundColor: canvasBG,//背景色
        },
        title: {
            text: devName + ' 日流量使用',
            style: {
                fontSize: "12px",
                fontWeight: 'bold'
            },

        },
        legend:{
            enabled:false
        },
        credits: {
            enabled: false
        },
        exporting:{
            buttons: {
                contextButton:{
                    enabled:true
                }
            },
        },
        xAxis: {
            categories: x,
            crosshair: true,
            title:{
                text:'时间(天)',
                align:'high',
            }
        },
        yAxis: {
            min: 0,
            max:(resultData[0].avgFlow+30).toFixed(2),
            title: {
                text: '流量(MB)'
            },
            minorGridLineColor: '#C5EEFA',
            tickPixelInterval: 30,
            plotLines: [{
                color: 'red',
                dashStyle: 'dot',
                width: 2,
                value: resultData[0].avgFlow.toFixed(2),
                label: {
                    align: 'right',
                    style: {
                        color:'blue',
                        fontStyle: 'italic',
                    },
                    x:-10,
                    text: '日均流量标准线('+resultData[0].avgFlow.toFixed(2)+' MB) ',
                },
                zIndex: 3
            }]
        },
        tooltip: {
            // head + 每个 point + footer 拼接成完整的 table
            headerFormat: '<span style="font-size:10px">{point.key} 日</span><table>',
            shared: true,
            useHTML: true
        },

        plotOptions: {
            column: {
                dataLabels: {
                    // 开启数据标签
                    enabled: true,
                    formatter: function() {
                        if(this.point.y !=0){
                            return  this.point.y;
                        }else {
                            return  "";
                        }

                    }
                },
            }
        },
        series: [{
            name:'当日使用流量',
            data:y,
            lineWidth:1.5,
            barMaxWidth: barMax,
            itemStyle: {
                normal: {
                    color: function (params) {
                        return 'red';
                    }
                }
            },
            dataLabels:{
                formatter:function () {
                    if(this.y!=0){
                        return this.y.toFixed(2)
                    }else {
                        return ''
                    }
                }
            },
        }]
    });

}

//初始日均增长率
function flowChart2(resultData) {
    let nowdate = formatTime(new Date())
    let da = nowdate.split('-')[2]

    var heightchar = $(window).height()-150
    $("#flow_month2").css('height', heightchar);
    var x = [];
    var y = [];
    if (null != resultData) {
        for (var i = 0; i < resultData.length; i++) {
            let eValue = Number(resultData[i].dayMuchFlow.toFixed(2));

            var strsss = new Array();
            strsss = resultData[i].timeId.split("-");
            x[i] = strsss[2];
            if(x[i]<=da){
                y.push(eValue)
            }else {
                y.push(null)
            }
        }
        strss = resultData[0].timeId.split("-");
        //aveDataPlan = parseFloat(dataPlan/resultData.length).toFixed(2);
    }
    var timeMonth = strss[0] + "-" + strss[1];

    var charts = Highcharts.chart('flow_month2',{
        chart: {
            type: 'spline',
            backgroundColor: canvasBG,//背景色
        },
        title: {
            text: devName + ' 日流量增长图',
            style: {
                fontSize: "12px",
                fontWeight: 'bold'
            },

        },
        legend:{
            enabled:false
        },
        credits: {
            enabled: false
        },
        xAxis: {
            categories: x,
            crosshair: true,
            title:{
                text:'时间(' + timeMonth + ')',
                align:'high',
            }
        },
        yAxis: {
            min: 0,
            title: {
                text: '流量(M)'
            },
            minorGridLineColor: '#C5EEFA',
            tickPixelInterval: 30,
        },
        tooltip: {
            shared: true,
            useHTML: true
        },
        plotOptions: {
            series: {
                dataLabels: {
                    align: 'center',
                    formatter:function(){
                        if(this.y!=0){
                            return  this.y
                        }else {
                            return null
                        }

                    },
                    enabled: true
                }
            }
        },
        series: [{
            color:'#A52a2a',
            lineWidth:1.5,
            type: 'spline',
            name:'日流量增长',
            data:y
        }]
    });

}

//获取所有功能
function loadselect(dictypeName){
    $.ajax({
        type : "post",
        url : "/pqs9900/device/getselect",
        data : {
            dictypeName:dictypeName
        },
        success : function(data) {
            $('#content_ch').empty()
            if(data == null){
                var message = dictypeName + '信息加载失败';
                layer.msg(message,{icon:2,time:1000});
            }else{
                let html = '<table ><tr>'
                for(let i=0;i<data.length;i++){

                    if((i+1)%7 == 0){
                        let th = '</tr><tr>'
                        html+=th;
                    }
                    let s ='<td  value="'+data[i].dicIndex+'" style="text-align: left;"><li style="padding: 5px 5px"></li><span>'+data[i].dicName+'</span></td>'
                    html+=s;
                }
                html = html+'</tr></table>'
                $('#content_ch').append(html)
                zuzhang(devIndex)
            }
        }
    })
}

function zuzhang(devIndex){
    $.ajax({
        type : "get",
        url : "/pqs9900/version/getDevfunction",
        data : {
            devIndex:devIndex
        },
        success : function(data) {
            $('#content_ch').find('td').each(function (index,item){
                let flag = true;
                let that = this
                    for(let i =0;i<data.body.length;i++){
                        if(data.body[i].fucname == $(that).attr('value')){
                            flag = false;
                           $(that).find('li').eq(0).addClass('glyphicon glyphicon-ok').css('color','green')
                        }
                    }
                if(flag){
                    $(that).find('li').eq(0).addClass('glyphicon glyphicon-remove').css('color','red')
                }


            })
        }
    })

}
