var type;

$(function () {
    //初始化页面内容
    if (gwType.val() == '1') {
        type = '1';
        $("#checkbox").prop('checked', false);
    } else {
        type = '0';
        $("#checkbox").prop('checked', true);
    }
    //获取当前日期
    $("#checkbox").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: "40",//设置控件宽度
        // 当开关状态改变时触发
        onSwitchChange: function (event, state) {
            if (state == true) {
                type = '0';
            } else {
                type = '1';
            }
            load();
        }
    });

});

/**
 * 终端运行管理
 */
var dataTable = null;
var resultData = null;
var area = null;
var devTypeBefore = "";//记录之前的状态
var devTypeNow = "";//记录更改后的状态
$(document).ready(function () {
    getGdnameG();
});
$("#query").click(function () {
    area = $area.eq(0).attr("index");
    load();
});


function getGdnameG() {
    $.ajax({
        method: "post",
        url: "/pqs9000/device/getGdname",
        data: '',
        success: function (data) {
            if (data.body != null) {
                for (var i = 0; i < data.body.length; i++) {
                    var option = $("<option style='text-align: center;' value='"
                        + data.body[i].gdNa + "'>"
                        + data.body[i].gdNa + "</option>");
                    $("#gdIndex").append(option);
                }
            }
        }
    })
    $.ajax({
        method: "post",
        url: "/pqs9000/device/getManufacturers",
        data: '',
        success: function (data) {
            if (data.body != null) {
                for (var i = 0; i < data.body.length; i++) {
                    var option ;
                    if(data.body[i].manufacturer === facturer){
                        option = $("<option style='text-align: center;'  value='"
                            + data.body[i].manufacturer + "' selected>"
                            + data.body[i].manufacturer + "</option>");
                    }else{
                         option = $("<option style='text-align: center;' value='"
                            + data.body[i].manufacturer + "'>"
                            + data.body[i].manufacturer + "</option>");
                    }
                    $("#manufacturer").append(option);
                }
            }
            $.ajax({
                type: "POST",
                url: "/pqs9000/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;
                    load();
                }
            })
        }
    })
}

function load() {
    var status = $("#status option:selected").val();
    var devflag = $("#devflag option:selected").val();
    var gdIndex = $("#gdIndex option:selected").val();
    var manufacturer = $("#manufacturer option:selected").val();
    var i;
    $.ajax({
        method: "post",
        url: "/pqs9000/device/getDeviceDetail",
        data: {
            area: area,
            status: status,
            devflag: devflag,
            gdName: gdIndex,
            manufacturer: manufacturer,
            type: type
        },
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER();
        },
        error: function (data) {
            layer.msg("暂无数据", {
                icon: 5,
                time: 3000
            });
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(i);
        },
        success: function (data) {
            if (data == "") {
                resultData = null;
                //没有数据
                initTable(null);
            } else {
                var info = $.parseJSON(data);
                if (info.code == 500) {
                    resultData = null;
                    //没有数据
                    initTable(null);
                } else {
                    resultData = info;
                    initTable(info);
                }
            }
            startQuery();
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(i);
        }
    });
}

$('#addDev').click(function () {
    layer.open({
        type: 2,
        title: '终端管理',
        maxmin: false,
        shadeClose: true, //点击遮罩关闭层
        area: ['100%', '100%'],
        content: 'addDev',
        scrollbar: false
    });
});

$('#importExl').click(function () {
    layer.open({
        type: 2,
        title: '批量导入',
        shadeClose: true,
        shade: 0.3,
        area: ['380px', '200px'],
        maxmin: false,
        content: 'importdev',
        scrollbar: false,
        end: function () {

        }
    });
});

function updateDevflag(nameTest) {
    var username = $("#username").val();
    confirmIndentity(username, function () {
        var str =
            "<div>" +
            "<input type='radio' name='time' id='time'  value='0'>投运" +
            "<input type='radio' name='time' id='time' style='margin-left:25%' value='1'>检修" +
            "<input type='radio' name='time' id='time' style='margin-left:25%' value='2'>退运" +
            "<br/>" +
            "更改原因:<input type='text' class='form-control' style='width: 80%;display: inline' name='terminalDescribe' id='terminalDescribe'>" +
            "</div>"
        $.ajax({
            method: "post",
            url: "/pqs9000/device/getDevflag",
            data: {
                name: nameTest
            },
            success: function (data) {
                if (data.devFlag == 0) {
                    $("input[name='time'][value='0']").attr("checked", true);
                    devTypeBefore = "投运";
                } else if (data.devFlag == 1) {
                    $("input[name='time'][value='1']").attr("checked", true);
                    devTypeBefore = "检修";
                } else {
                    $("input[name='time'][value='2']").attr("checked", true);
                    devTypeBefore = "退运";
                }
            }
        });
        layer.open({
            title: '修改终端运行状态',
            content: str,
            resize: false,
            shadeClose: true,
            scrollbar: false,
            area: "350px",
            closeBtn: 0,
            btn: ['确定', '取消'],
            yes: function (index) {
                var devflag = $('input:radio:checked').val();
                if (devflag == 0) {
                    devTypeNow = "投运";
                } else if (devflag == 1) {
                    devTypeNow = "检修";
                } else {
                    devTypeNow = "退运";
                }
                var terminalDescribe = $("#terminalDescribe").val();
                var str = terminalDescribe.replace(/(^\s*)|(\s*$)/g, '');//去除空格;
                if (str == '' || str == undefined || str == null) {
                    layer.tips('请填写更改终端状态原因', '#terminalDescribe',
                            {
                                tips: [2, 'red'],
                                time: 2000
                            });
                    $("#terminalDescribe").val("");
                } else {
                    var terminalDescribeReason="由"+devTypeBefore+"状态更改到"+devTypeNow+"状态，原因是"+terminalDescribe;
                    $.ajax({
                        method: "post",
                        url: "/pqs9000/device/updateDevice",
                        data: {
                            name: nameTest,
                            devflag: devflag,
                            terminalDescribe:terminalDescribeReason
                        },
                        success: function (data) {
                            if (data == 200) {
                                layer.msg("修改终端运行状态成功", {
                                    icon: 6,
                                    time: 1000
                                }, function () {
                                    load();
                                    layer.close(index);
                                });
                            } else if (data == 500) {
                                layer.msg("密码验证失败!", {
                                    icon: 5,
                                    time: 1000
                                }, function () {
                                    layer.close(index)
                                });
                            } else {
                                layer.msg("修改终端运行状态失败", {
                                    icon: 5,
                                    time: 1000
                                }, function () {
                                    layer.close(index)
                                });
                            }
                        }
                    })
                }
            }
        })
    })
}

function initTable(data) {
    var height = $(window).height() - 160;
    var length = Math.floor(height / 28);
    if (length < 1) {
        length = 1;
    }
    // var heightTemp = screen.height;
    // var length;
    // if (heightTemp === 768) {
    //     length = 10;
    // } else if (heightTemp === 1024) {
    //     length = 20;
    // } else if (heightTemp === 960) {
    //     length = 15;
    // } else if (heightTemp === 1050) {
    //     length = 18;
    // } else {
    //     length = 15;
    // }
    dataTable = $("#runtimeid").DataTable();
    dataTable.clear().draw();
    dataTable = $('#runtimeid').DataTable({
        order: [[10, 'asc']],
        columnDefs: [
            {
                orderable: false,
                targets: [0]
            }
        ],
        // columns: [
        //     {"width": "4%"},
        //     {"width": "6%"},
        //     {"width": "8%"},
        //     {"width": "8%"},
        //     {"width": "8%"},
        //     {"width": "6%"},
        //     {"width": "9%"},
        //     {"width": "7%"},
        //     {"width": "7%"},
        //     {"width": "6%"},
        //     {"width": "6%"},
        //     {"width": "6%"},
        //     {"width": "9%"},
        //     {"width": "5%"},
        //     {"width": "8%"}
        // ],
        autoWidth: false,
        serverSide: false,
        destroy: true,
        data: data,
        lengthChange: false,
        searching: true,
        dom: 'rtip',
        scrollY: height,
        scrollX: true,
        pageLength: length,
        language: {
            url: '/pqs9000/json/chine.json'
        },
        "createdRow": function (row, data, index) {
            if (data[9] == "退运") {
                $('td', row).eq(9).css('color', '#696969')

            } else if (data[9] == "检修") {
                $('td', row).eq(9).css('color', '#FFD700')
            } else if (data[9] == "投运") {
                $('td', row).eq(9).css('color', '#2E8B57')
            }
            if (data[10] == "中断") {
                $('td', row).eq(10).css('color', '#A52a2a')
            } else if (data[10] == "正常") {
                $('td', row).eq(10).css('color', '#2E8B57')
            }
            if (data[12] == "优") {
                $('td', row).eq(12).css('color', '#2E8B57')
            } else if (data[12] == "良") {
                $('td', row).eq(12).css('color', '#DAA520')
            } else if (data[12] == "差") {
                $('td', row).eq(12).css('color', '#A52a2a')
            }
            if (data[2].length > 8) {
                var realValue = data[2];
                var s = data[2].substr(0, 8) + '...'
                $('td', row).eq(2).prevObject[2].innerHTML = "<span title='" + realValue + "'>" + s + "</span>";
            }
            if (data[1].length > 6) {
                var realValue = data[1];
                var s = data[1].substr(0, 6) + '...'
                $('td', row).eq(1).prevObject[1].innerHTML = "<span title='" + realValue + "'>" + s + "</span>";
            }
            if (data[3].length > 12) {
                var realValue = data[3];
                var s = data[3].substr(0, 12) + '...'
                $('td', row).eq(3).prevObject[3].innerHTML = "<span title='" + realValue + "'>" + s + "</span>";
            }
            if (data[6].length > 14) {
                var realValue = data[6];
                var s = data[6].substr(0, 14) + '...'
                $('td', row).eq(6).prevObject[6].innerHTML = "<span title='" + realValue + "'>" + s + "</span>";
            }
            if (data[7].length > 14) {
                var realValue = data[7];
                var s = data[7].substr(0, 14) + '...'
                $('td', row).eq(7).prevObject[7].innerHTML = "<span title='" + realValue + "'>" + s + "</span>";
            }
        },
        fnDrawCallback: function (oTable) {
            $("#runtimeid_info").addClass("fl");
            $("#runtimeid_paginate").addClass("fr");
            $("#runtimeid_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 = $("#runtimeid").dataTable();
            $('#dataTable-btn').click(function (e) {
                if ($("#changePage").val() && $("#changePage").val() > 0) {
                    var redirectpage = $("#changePage").val() - 1;
                } else {
                    var redirectpage = 0;
                }
                table.fnPageChange(redirectpage);
            });
        }
    });
    dataTable.on('order.dt search.dt',
        function () {
            dataTable.column(0, {
                search: 'applied',
                order: 'applied'
            }).nodes().each(function (cell, i) {
                cell.innerHTML = i + 1;
            });
        }).draw();
    new $.fn.dataTable.Buttons(dataTable, {
        buttons: [
            {
                extend: 'csv',//导出格式
                title: '终端台账列表',//导出csv名称
                exportOptions: {
                    columns: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],//导出需要的列
                    format: {
                        body: function (data) {//对导出内容的筛选 data 表格内容 rid 行索引 cid 列索引
                            return data;
                        }
                    }
                }
            }
        ]
    });
    modifyCss(dataTable);

}

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 = $("#runtimeid").width();
    if (width > 100) {
        initTable(resultData);
        window.clearInterval(it)
    }
}

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