var height = $(window).height() - 75;
var arr = []
var username = $('#username').val()
var resetName = ''
var websocket = window.parent.parent.webSocket
$(function () {
    $(".tablediv").css("height", height);
    getDeviceType()
    refresh();


    //终端状态管理
    $('#ztgl').click(function () {
        arr= []
        let checkdiv = $("[name=checkboxs]:checked")

        let len = checkdiv.length

        if(len == 0){
            layer.msg('请至少选择一台终端',{icon:2})
            return
        }
        for(let i = 0;i<len;i++){
            arr.push(checkdiv.eq(i).val())
        }

        passwordLocalIndentity(username,resetName,function () {
            layer.open({
                type: 2,
                title: '终端状态管理',
                maxmin: false,
                area: ['100%', '100%'],
                content: 'termainstate',
                scrollbar: false,
            })
        })

    })
    //流量套餐管理
    $('#tcgl').click(function () {
        arr= []
        let checkdiv = $("[name=checkboxs]:checked")

        let len = checkdiv.length

        if(len == 0){
            layer.msg('请至少选择一台终端',{icon:2})
            return
        }
        for(let i = 0;i<len;i++){
            arr.push(checkdiv.eq(i).val())
        }
        passwordLocalIndentity(username,resetName,function () {
            layer.open({
                type: 2,
                title: '流量套餐管理',
                maxmin: false,
                area: ['100%', '100%'],
                content: 'flowcombo?type=1',
                scrollbar: false,
            })
        })
    })
    //流量策略管理
    $('#clgl').click(function () {
        arr= []
        let checkdiv = $("[name=checkboxs]:checked")

        let len = checkdiv.length

        if(len == 0){
            layer.msg('请至少选择一台终端',{icon:2})
            return
        }
        for(let i = 0;i<len;i++){
            arr.push(checkdiv.eq(i).val())
        }
        passwordLocalIndentity(username,resetName,function () {
            layer.open({
                type: 2,
                title: '流量策略管理',
                maxmin: false,
                area: ['100%', '100%'],
                content: 'flowstrategy',
            })
        })
    })

    //重启服务器
    $('#rest').click(function () {
        layer.confirm('确认重启前置机服务吗?',function () {
            $.ajax({
                type:'post',
                url:'/pqs9900/terminalmanger/getWebIpList',
                dataType:"json",
                beforeSend:function(){
                    indexi = ityzl_SHOW_LOAD_LAYER();
                },
                success:function (data) {
                    if(data.code == 200){

                    }else {
                        layer.msg('重启前置服务异常',{icon:2})
                    }
                    ityzl_CLOSE_LOAD_LAYER(indexi);
                }
            })
        })
    })

    //流量统计
    $('#lltj').click(function () {
        layer.open({
            type: 2,
            title: '流量统计',
            maxmin: false,
            area: ['100%', '100%'],
            content: 'flowstatistics',
        })

    })



    //全选
    $('#all_checked').on("click", function () {
        $('[name=checkboxs]:checkbox').prop('checked', this.checked)
    })



    websocket.onmessage = function (evnt) {
        if (evnt.data != "") {
            var info = JSON.parse(evnt.data)
            if(info.type == 200){
                let html = "<div class=\"alert alert-success\">\n" +
                    "\t<a href=\"#\" class=\"close\" data-dismiss=\"alert\">\n" +
                    "\t\t&times;\n" +
                    "\t</a>\n" +
                    "\t<strong>{{1}}</strong>{{2}}\n" +
                    "</div>"
                let htmls = "<div class=\"alert alert-danger\">\n" +
                    "\t<a href=\"#\" class=\"close\" data-dismiss=\"alert\">\n" +
                    "\t\t&times;\n" +
                    "\t</a>\n" +
                    "\t<strong>{{1}}</strong>{{2}}\n" +
                    "</div>"
                if (info.resultcode == 10000) {
                   // layer.msg('服务重启成功',{icon:1})

                    $('#msgInfo').append(html.replace('{{1}}','成功').replace('{{2}}','ip为:'+info.resultmsg+'前置服务器重启成功'))
                }else if(info.resultcode == 13333) {
                    let ip = info.data
                    //layer.msg('ip为'+ip+'的服务重启失败',{icon:5})
                    $('#msgInfo').append(htmls.replace('{{1}}','失败！').replace('{{2}}','ip为:'+info.resultmsg+'前置服务器重启失败'))
                }else if (info.resultcode == 10003) {
                    layer.msg("JSON字符串解析出错", {
                        icon: 5,
                        time: 3000
                    });
                } else if (info.resultcode == 10004) {
                    layer.msg("socket处理出现异常", {
                        icon: 5,
                        time: 3000
                    });
                } else if (info.resultcode == 10005) {
                    layer.msg("未找到ID为对应的设备", {
                        icon: 5,
                        time: 3000
                    });
                }else {
                    $('#msgInfo').append(html.replace('{{1}}','重启失败！'))
                   // layer.msg('服务重启失败',{icon:2})
                }
                /*let time = null;
                time = window.setTimeout(function () {
                    $('#msgInfo').empty()
                },5000)*/
            }
        }
    }

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

});



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


var dataTable;

//初始化表格数据
function initTransactionTable(tableData) {
    var tableHeight = height - 75;
    var length = Math.floor(tableHeight / 32);
    if (length < 1) {
        length = 1;
    }
    var tableCellHeight = 32 * length+20;
    dataTable = $("#deviceTable").DataTable();
    dataTable.clear().draw();
    dataTable = $('#deviceTable').DataTable({
        order: [10, 'desc'],
        columnDefs: [
            {
                orderable: false,
                targets: [0,11]
            }
        ],
        columns: [
            {
                width: "15px", data: "devIndex", render: function (data, type, full, meta) {
                    return "<input type ='checkbox' name='checkboxs' class='icheckbox_minimal' value='" + data + "'>";
                }
            },
            {width: "110px", data: "name"},
            {width: "60px", data: "edName",render:function (data) {
                    return'<a href="javascript:void(0);" onclick="toUpdate()" ><font style="color:blue">'+data+'</font></a>'
                }},
            {width: "120px", data: "ip"},
            {width: "110px", data: "devType"},
            {width: "100px", data: "gdName"},
            {width: "110px", data: "bdName",render:function (data) {
                    let value = data;

                    if (data!=null && data.length > 14) {
                        value = data.substring(0, 14) + "..";
                        value = "<span title=" + data + ">" + value + "</span>";
                    }
                    return value;
                }},
            {width: "30px", data: "baseFlow"},
            {width: "30px", data: "extendFlow"},
            {width: "30px", data: "useFlow",render:function (data, type, full, meta) {
                   let useFlow = full.actualflow/(full.baseFlow+full.extendFlow)
                   return  isInteger(useFlow)
                }},
            {width: "30px", data: "status",render:function (data) {
                    return getWarnInfo(data)
                }},
            {
                width: "150px", data: "devIndex", render: function (data, type, full, meta) {
                    if(full.edName == '/' ||full.status == 0){
                        return "<button disabled type='button' class='btn themeBGColor' style='margin-right:10px;' href='javascript:void(0);'  onclick='viewTransactionDetail(\"" + full.devIndex + "\",\"" + full.gdName + "\",\"" + full.bdName + "\",\"" + full.name + "\",1)' >终端详情</button>" +
                            "<button type='button' class='btn themeBGColor' style='margin-right:10px;' href='javascript:void(0);'  onclick='viewTransactionDetail(\"" + full.devIndex + "\",\"" + full.gdName + "\",\"" + full.bdName + "\",\"" + full.name + "\",2)' >流量详情</button>"+
                        "<button type='button' class='btn themeBGColor' style='margin-right:10px;' href='javascript:void(0);'  onclick='getDevRunFlagLogs(\"" + full.devIndex + "\",\"" + full.gdName + "\",\"" + full.bdName + "\",\"" + full.name + "\",2)' >装置日志</button>";
                    }else {
                        return "<button type='button' class='btn themeBGColor' style='margin-right:10px;' href='javascript:void(0);'  onclick='viewTransactionDetail(\"" + full.devIndex + "\",\"" + full.gdName + "\",\"" + full.bdName + "\",\"" + full.name + "\",1)' >终端详情</button>" +
                            "<button type='button' class='btn themeBGColor' style='margin-right:10px;' href='javascript:void(0);'  onclick='viewTransactionDetail(\"" + full.devIndex + "\",\"" + full.gdName + "\",\"" + full.bdName + "\",\"" + full.name + "\",2)' >流量详情</button>"+
                            "<button type='button' class='btn themeBGColor' style='margin-right:10px;' href='javascript:void(0);'  onclick='getDevRunFlagLogs(\"" + full.devIndex + "\",\"" + full.gdName + "\",\"" + full.bdName + "\",\"" + full.name + "\",2)' >装置日志</button>";
                    }
                }
            }
        ],
        destroy: true,
        data: tableData,
        lengthChange: false,
        searching: true,
        dom: 'rtip',
        scrollY: tableCellHeight,
        scrollX: true,
        autoWidth:true,
        lengthMenu: [length],
        language: {
            url: '/pqs9900/json/chine.json'
        },
        fnDrawCallback: function (oTable) {
            $("#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();
            $('#dataTable-btn').click(function (e) {
                if ($("#changePage").val() && $("#changePage").val() > 0) {
                    var redirectpage = $("#changePage").val() - 1;
                } else {
                    var redirectpage = 0;
                }
                table.fnPageChange(redirectpage);
            });

        }
    });
}

//跳转升级页面
function toUpdate() {
    var tabs = window.parent.parent.parent.tabs;
    tabs.add({url : 'deviceversion',label : '终端程序版本管理',});
}

//搜索表中的数据
function searchResult(value) {
    dataTable.search(value).draw();
}
//判断是否是整数
function isInteger(obj) {
    if(obj==null){
        return 0
    }else {
        if(typeof obj === 'number' && obj%1 === 0){
            return obj*100
        }else {
            return (obj*100).toFixed(2)
        }
    }
}

//获取启用状态
function getWarnInfo(data) {
    data = Number(data);
    if (data === 0) {
        info = '<font style="color:#A52a2a">中断</font>'
    }else {
        info = '<font style="color:#2E8B57">正常</font>'
    }
    return info;
}

function viewTransactionDetail(subIndex,gdName,bdName,name,type) {

    if(type == 1){
        //首先判断webSocket是否连接
        if (websocket.readyState != 1) {
            layer.msg('webSocket连接关闭,请联系管理人员', {icon: 2})
            return;
        }
        //终端详情
        layer.open({
            type: 2,
            title: '终端使用情况',
            maxmin: false,
            area: ['60%', '75%'],
            content: 'deviceopen?devIndex=' + subIndex+'&gdName='+gdName+'&bdName='+bdName+'&devName='+name,
            scrollbar: false,
            end: function () {
                $.ajax({
                    type:'post',
                    dataType:"json",
                    url:'/pqs9900/terminalmanger/closeSocket',
                    data:{devIndex:subIndex},
                    success : function(data) {

                    }
                })
            }
        })
    }else {
        //流量详情
        layer.open({
            type: 2,
            title: '流量使用情况',
            maxmin: false,
            area: ['100%', '100%'],
            content: 'flowdetail?devIndex=' + subIndex+'&devName='+name+'&flag=1',
            scrollbar: false,
            end: function () {
                refresh();
            }
        })
    }


}

//获取所有装置类型
function getDeviceType() {
    $.ajax({
        type: 'post',
        url: '/pqs9900/device/getselect',
        data: {dictypeName: '装置类型'},
        dataType: 'json',
        success: function (data) {
            $('#decice_model').empty()
            var html = '<option value="">全部</option>'
            data.forEach(function (item) {
                let op = '<option value="' + item.dicIndex + '">' + item.dicName + '</option>'
                html += op;
            })
            $('#decice_model').append(html)
        }

    })
}


//终端运行日志弹框
function getDevRunFlagLogs(devIndex){
    layer.open({
        type: 2,
        title: '终端运行日志',
        maxmin: false,
        area: ['100%', '100%'],
        content: 'todevlogs?devIndex=' + devIndex,
        scrollbar: false,

    })
}


window.paramSend = function () {
    return arr;
}

window.flashResh=function () {
    refresh()
}
