var dataTable = null;
var loading;

$(function () {
    refresh()


})

$("#addStratey").click(function () {
    operate(1,null)
})

function addSubmit(type) {

    let lineGrade = $('#lineGrade').val()
    let integrityValue = $("#integrityValue").val()
    let onlineValue = $("#onlineValue").val()
    let offtimeValue = $("#offtimeValue").val()
    let warnValue = $("#warnValue").val()



    if (lineGrade == null || lineGrade == '') {
        layer.msg("监测点等级不可为空", {icon: 2})
        return
    }

    if (integrityValue == null || integrityValue == '') {
        layer.msg("数据完整性标准值不可为空", {icon: 2})
        return
    }
    if (onlineValue == null || onlineValue == '') {
        layer.msg("终端在线率标准不可为空", {icon: 2})
        return
    }
    if (offtimeValue == null || offtimeValue == '') {
        layer.msg("持续中断时长标准不可为空", {icon: 2})
        return
    }
    if (warnValue == null || warnValue == '') {
        layer.msg("告警次数不可为空", {icon: 2})
        return
    }

    let reg = /^(?:0|[1-9][0-9]?|100)$/
    if(!reg.test(integrityValue)){
        layer.msg("请填写0-100之间的整数", {icon: 2})
        return
    }
    if(!reg.test(onlineValue)){
        layer.msg("请填写0-100之间的整数", {icon: 2})
        return
    }
    if(!reg.test(warnValue)){
        layer.msg("请填写0-100之间的整数", {icon: 2})
        return
    }


    let obj = {
        dicIndex: lineGrade,
        integrityValue: integrityValue,
        onlineValue:onlineValue,
        offtimeValue: offtimeValue,
        warnValue:warnValue
    }

    layer.confirm("确认操作吗?",function () {
        if(type == 1){
            $.ajax({
                type: "post",
                url: "/pqs9900/inStrategy/addForRun",
                dataType: "json",
                contentType: 'application/json;charset=UTF-8',
                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})
                    } else {
                        layer.msg('添加成功', {icon: 1},function () {
                            refresh()
                            layer.close(op2)
                        })


                    }

                    //***********关闭loading
                    ityzl_CLOSE_LOAD_LAYER(loading);
                }
            });
        }else {
            $.ajax({
                type: "post",
                url: "/pqs9900/inStrategy/updateForRun",
                dataType: "json",
                contentType: 'application/json;charset=UTF-8',
                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})
                    } else {
                        layer.msg('修改成功', {icon: 1},function () {
                            refresh()
                            layer.close(op2)
                        })


                    }

                    //***********关闭loading
                    ityzl_CLOSE_LOAD_LAYER(loading);
                }
            });
        }
    })




}

//点击确定，去后台请求参数
$("#query").click(function () {
    refresh();
});

//获取表格数据
function refresh() {
    var i;
    $.ajax({
        type: "get",
        url: "/pqs9900/inStrategy/queryListForRun",
        dataType: "json",
        beforeSend: function () {
            i = 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;
            }
            startQuery();
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(i);
        }
    });
}

//实例化表格
function initTable(data) {
    var height = $(window).height() - 155;
    var length = Math.floor(height / 28);
    if (length < 1) {
        length = 1;
    }
    dataTable = $("#onlineRateStrategy").DataTable();
    dataTable.clear().draw();
    dataTable = $('#onlineRateStrategy').DataTable({
        columnDefs: [
            {
                orderable: false,
                targets: [6]
            }
        ],
        order: [],
        columns: [
            {width: "6%", data: "lineGrade"},
            {width: "15%", data: "integrityValue"},
            {width: "10%", data: "onlineValue"},
            {width: "15%", data: "offtimeValue"},
            {width: "10%", data: "warnValue"},
            {width: "15%", data: "updateTime",render:function (data) {
                    return formatTime(data,1)
                }},
            {width: "15%", data: "updateUser"},
            {
                width: "10%", data: "dicIndex", render: function (data, type, full, meta) {
                    return "<button type='button' class='btn themeBGColor mr10'  onclick='gradeOperate(\"" + full.dicIndex + "\",2)' >修改</button>" +
                        "<button type='button' class='btn themeBGColor'  onclick='gradeOperate(\"" + full.dicIndex + "\",3)' >删除</button>"

                }
            }
        ],
        destroy: true,
        data: data,
        lengthChange: false,
        searching: true,
        dom: 'rtip',
        scrollY: height,
        scrollX: false,
        lengthMenu: [length],
        language: {
            url: '/pqs9900/json/chine.json'
        },
        fnDrawCallback: function (oTable) {
            $("#onlineRateStrategy_info").addClass("fl");
            $("#onlineRateStrategy_paginate").addClass("fr");
            $("#onlineRateStrategy_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 = $("#onlineRateStrategy").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: {
                    columns: [0, 1, 2, 3, 4,5,6],

                }
            }
        ]
    });
    modifyCss(dataTable);

}


function gradeOperate(dicIndex, type) {
    if (type == 2) {
        //修改
        operate(2,dicIndex)
    } else {
        //删除
        layer.confirm('确认删除吗?',function () {
            $.ajax({
                method: "get",
                url: "/pqs9900/inStrategy/deleteForRun",
                data: {
                    dicIndex: dicIndex
                },
                dataType: 'json',
                success: function (data) {
                    if(data.code == 200){
                       layer.msg("删除成功!",{icon:1})
                        refresh()
                    }else {
                        layer.msg("删除失败!",{icon:2})
                    }


                }
            })
        })

    }

}
let op2;
function operate(type,dicIndex) {
    let title;
    if(type == 1){
        //新增
        title = "新增策略"
    }else {
        title = "修改策略"
    }
    op2 = layer.open({
        type: 1,
        title:title,
        shadeClose: true,
        resize: false,
        area: ['25%', '60%'],
        content: '<div style="padding: 15px 20px" class="form-horizontal" >\n' +
            '  <div class="form-group">\n' +
            '    <label for="firstname" style="padding-right: 1px" class="col-sm-4 control-label">监测点等级</label>\n' +
            '    <div class="col-sm-8">\n' +
            '      <select  class="form-control"  id="lineGrade" placeholder="请输入名字"></select>\n' +
            '    </div>\n' +
            '  </div>\n' +
            '  <div class="form-group">\n' +
            '    <label for="onlineValue" style="padding-right: 1px" class="col-sm-4 control-label">数据完整性标准</label>\n' +
            '    <div class="col-sm-8">\n' +
            '      <input type="text" class="form-control" id="integrityValue" placeholder="0~100(单位:%)">\n' +
            '    </div>\n' +
            '  </div>\n' +
            '  <div class="form-group">\n' +
            '    <label for="onlineValue" style="padding-right: 1px" class="col-sm-4 control-label">终端在线率标准</label>\n' +
            '    <div class="col-sm-8">\n' +
            '      <input type="text" class="form-control" id="onlineValue" placeholder="0~100(单位:%)">\n' +
            '    </div>\n' +
            '  </div>\n' +
            '  <div class="form-group">\n' +
            '    <label for="lastname" style="padding-right: 1px" class="col-sm-4 control-label">中断持续时长</label>\n' +
            '    <div class="col-sm-8">\n' +
            '      <input type="text" class="form-control" id="offtimeValue" placeholder="单位分钟">\n' +
            '    </div>\n' +
            '  </div>\n' +
            '  <div class="form-group">\n' +
            '    <label for="lastname" style="padding-right: 1px" class="col-sm-4 control-label">告警次数</label>\n' +
            '    <div class="col-sm-8">\n' +
            '      <input type="text" class="form-control" id="warnValue" placeholder="单位次">\n' +
            '    </div>\n' +
            '  </div>\n' +
            '  <div class="form-group" style="position: absolute;bottom: 10px;text-align: center;width: 93%">\n' +
            ' <button id="addsubmit" class="btn btn-primary" onclick="addSubmit('+type+')" >提交</button>\n' +
            '  </div>\n' +
            '</div>',
        success: function () {
            var option = "";
            $.ajax({
                method: "post",
                url: "/pqs9900/device/getselect",
                data: {
                    dictypeName: '终端等级'
                },
                dataType: 'json',
                success: function (data) {
                    for (var i = 0; i < data.length; i++) {

                        option = option + "<option value='"
                            + data[i].dicIndex + "'>"
                            + data[i].dicName + "</option>";

                    }
                    $("#lineGrade").empty()
                    $("#lineGrade").append(option)

                    if(type == 2){
                        $("#lineGrade").attr("disabled",true)
                        //修改
                        $.ajax({
                            method: "get",
                            url: "/pqs9900/inStrategy/queryForRun",
                            data: {
                                dicIndex: dicIndex
                            },
                            dataType: 'json',
                            success: function (data) {
                                if(data.code == 200){
                                    $('#lineGrade').val(data.body.dicIndex)
                                    $("#integrityValue").val(data.body.integrityValue)
                                    $("#offtimeValue").val(data.body.offtimeValue)
                                    $("#warnValue").val(data.body.warnValue)
                                    $("#onlineValue").val(data.body.onlineValue)
                                }else {
                                    layer.msg("查询失败!",{icon:2})
                                }


                            }
                        })
                    }
                }
            })

        }
    })
}

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

//特殊处理，表头紧缩问题--start
var it = null;

function startQuery() {
    //实时刷新时间单位为毫秒
    it = setInterval('refreshQuery()', 100);

}

/* 刷新查询 */
function refreshQuery() {
    var width = $("#onlineRateStrategy").width();
    if (width > 100) {
        initTable(resultData);
        window.clearInterval(it)
    }
}

//特殊处理，表头紧缩问题--end








