var node;
var dataTable = null;
var deptsIndex;

//绑定供电公司
function DeptsGdByIndex(index) {
    var username = $("#username").val();
    confirmIndentity(username, function () {
        deptsIndex = index;
        layer.open({
            type: 2,
            title: '绑定监测点',
            shadeClose: true,
            resize: false,
            shade: 0.3,
            area: ['55%', '85%'],
            content: 'deptsLine', //iframe的url
            scrollbar: false,
            end: function () {
                parent.close();
            }
        });
    })
}

//修改部门
function updateDeptsByIndex(index) {
    var username = $("#username").val();
    confirmIndentity(username, function () {
        $("#deptsIndex").val(index);
        var deptsIndex = index;
        layer.open({
            type: 2,
            title: '修改部门',
            shadeClose: true,
            resize: false,
            shade: 0.3,
            area: ['25%', '80%'],
            content: 'updateDept', //iframe的url
            scrollbar: false,
            end: function () {
                close();
            }
        });
    })
}

//删除部门
function deleteDeptsByIndex(index) {
    var deptsIndex = index;
    var username = $("#username").val();
    confirmIndentity(username, function () {
        layer.confirm('确定删除？', function (index) {

            $.ajax({
                type: "POST",
                url: "/pqs9900/depts/deleteDeptsByIndex",
                dataType: "text",
                data: {
                    index: deptsIndex
                },
                success: function (data) {
                    if (data == "") {
                        layer.msg("省级部门不可删除", {icon: 5, time: 2000}, function () {
                            layer.closeAll()
                        });
                    } else {
                        var info = $.parseJSON(data);
                        if (info.code == 500) {
                            //删除部门异常、或者失败
                            layer.msg(info.message, {
                                icon: 5,
                                time: 1000
                            }, function () {
                                refresh();
                            });
                        } else {
                            //删除部门成功
                            layer.msg(info.message, {
                                icon: 6,
                                time: 1000
                            }, function () {
                                refresh();
                                getTreeDepts();
                            });
                        }
                    }
                }

            });
            layer.close(index);
        })
    })
}

//终端树
var treeObj = null;
var setting = {
    check: {
        enable: true,
        chkDisabledInherit: true
    },
    data: {
        simpleData: {
            enable: true
        }
    },
    view: {
        fontCss: setHighlight // 高亮一定要设置，setHighlight是自定义方法
    },
    callback: {
        onCheck: onCheck1,
        onClick: zTreeOnClick
    }
};

function onCheck1() {
    var checkCount = 1, totalcount = 4;
    var zTree = jQuery.fn.zTree.getZTreeObj("tree1");
    if (zTree != null) {
        checkCount = zTree.getCheckedNodes(true).length;
        var nodes = zTree.getCheckedNodes(true);
        totalcount = checkCount;
        treecheck = [];

        if (number != 0) {
            if (checkCount >= number) {
                disabledNode(true);
            } else {
                disabledNode(false);
            }
        }
    }
}

//选中时关联父子节点，py、pn代表父节点，sy、sn代表子节点，需要关联设置为p、s即可
function setCheck1() {
    var zTree = jQuery.fn.zTree.getZTreeObj("tree1"), py = "", sy = "p", pn = "p", sn = "s", type = {
        "Y": py + sy,
        "N": pn + sn
    };

}

function disabledNode1(e) {
    var zTree = jQuery.fn.zTree.getZTreeObj("tree1");

}

function zTreeOnClick() {
    var zTree = $.fn.zTree.getZTreeObj("tree1");

    if (zTree != null) {
        var nodes = zTree.getSelectedNodes();   //获取树控件选中对象集合

        node = nodes[0].id;
        if(node==null){
            node = 10001;
        }
        getId(node);
    }
}

function getId(node) {
    $.ajax({
        type: 'POST',
        dataType: "text",
        url: '/pqs9900/depts/getD',
        data: {
            node: node
        },
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER();
        },
        success: function (data) {
            var height = $(window).height() - 238;
            var length = Math.floor(height / 28);
            if (length < 1) {
                length = 1;
            }
            if (data == 301) {
                location.href = '/pqs9900';
            } else {
                var info = $.parseJSON(data);
                dataTable = $("#deptsId").DataTable();
                dataTable.clear().draw();
                dataTable = $('#deptsId').DataTable({
                    order: [],
                    columnDefs: [
                        {
                            orderable: false,
                            targets: [5, 6]
                        }
                    ],
                    data: info.body,
                    destroy: true,
                    searching: true,
                    dom: 'rtip',
                    pageLength: length,
                    "columns": [
                        {"width": "9%"},
                        {"width": "8%"},
                        {"width": "15%"},
                        {"width": "9%"},
                        {"width": "9%"},
                        {"width": "10%"},
                        {"width": "6%"},
                        {"width": "20%"},
                    ],
                    language: {
                        url: '/pqs9900/json/chine.json'
                    },
                    "createdRow": function (row, data, index) {
                        if (data[4] == "web自定义") {
                            $('td', row).eq(4).css('color', '#A52a2a')
                        } else if (data[4] == "app自定义") {
                            $('td', row).eq(4).css('color', "#DAA520")
                        } else if(data[4] == "非自定义"){
                            $('td', row).eq(4).css('color', '#2E8B57')
                        }
                    },
                    'fnDrawCallback': function (oTable) {
                        $("#deptsId_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 = $("#deptsId").dataTable();
                        $('#dataTable-btn').click(function (e) {
                            if ($("#changePage").val() && $("#changePage").val() > 0) {
                                var redirectpage = $("#changePage").val() - 1;
                            } else {
                                var redirectpage = 0;
                            }
                            table.fnPageChange(redirectpage);
                        });
                    }
                });

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

function getTreeDepts() {
    $.ajax({
        type: 'POST',
        dataType: "json",
        url: '/pqs9900/depts/selectDept',
        data: '',
        error: function () {},
        success: function (data) {
            var datalist = [];
            for (var i = 0; i < data.body.length; i++) {
                var str = '';
                str += '{' + "id:" + '"' + data.body[i].deptsIndex + '"';
                str += ',' + "pId:" + '"' + data.body[i].parentNodeId + '"';
                str += ',' + "open:" + true;
                str += ',' + "name:" + '"' + data.body[i].deptsName + '"' + '}';
                datalist.push(str);
            }
            datalist = eval('[' + datalist + ']');// string->json数组
            var zNodes = datalist;
            treeObj = $.fn.zTree.init($("#tree1"), setting, zNodes);
            setCheck1();
            disabledNode1(true);
        }
    })

};

// 模糊搜索name满足条件的节点
function searchNode(value) {
    if (value == "") return;

    // 获取搜索的节点
    var nodes = treeObj.getNodesByParamFuzzy("name", value);
    // 关闭所有节点的高亮
    var allNodes = treeObj.transformToArray(treeObj.getNodes());
    for (var i = 0; i < allNodes.length; i++) {
        allNodes[i].highlight = false;
        treeObj.updateNode(allNodes[i]);
    }
    // 展开第一层节点
    treeObj.expandAll(false);
    treeObj.expandNode(treeObj.getNodes()[0], true);
    // 高亮并展开搜索到的节点
    for (var i = 0; i < nodes.length; i++) {
        nodes[i].highlight = true;
        treeObj.updateNode(nodes[i]); // 更新节点，让高亮生效
        treeObj.expandNode(nodes[i].getParentNode(), true);
    }
}

// 设置高亮字体
function setHighlight(treeId, treeNode) {
    return (treeNode.highlight) ? {
        color: "#666",
        "font-weight": "bold",
        "border-bottom": "dotted 1px #fff"
    } : {color: "#666", "font-weight": "normal"};
}

// 延时搜索，用于输入框的按键事件，如果不延时，树就会不断的跳动
var timeoutId = null;

function searchNodeLazy(value) {
    if (timeoutId) {
        clearTimeout(timeoutId);
    }
    timeoutId = setTimeout(function () {
        searchNode(value);
    }, 500);
}

refresh();


$(document).ready(function () {
    $("#addDept").click(function () {
        layer.open({
            type: 2,
            title: '新增部门',
            shadeClose: true,
            resize: false,
            shade: 0.3,
            area: ['25%', '80%'],
            content: 'addDept', //iframe的url
            scrollbar: false,
            end: function () {
                parent.close();
            }
        });
    });

    getTreeDepts();
});
var i;

function refresh() {
    $.ajax({
        type: "POST",
        url: "/pqs9900/depts/getDepts",
        dataType: "text",
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER();
        },
        success: function (data) {
            if (data == 301) {
                location.href = '/pqs9900';
            } else {
                initTable(data);
                resultData = data;
            }
            startQuery();
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(i);
        }
    });
}

function initTable(data) {
    var height = $(window).height() - 238;
    var length = Math.floor(height / 28);
    if (length < 1) {
        length = 1;
    }
    if (data == 301) {
        location.href = '/pqs9900';
    } else {
        var info = $.parseJSON(data);
        dataTable = $("#deptsId").DataTable();
        dataTable.clear().draw();
        dataTable = $('#deptsId').DataTable({
            order: [],
            columnDefs: [
                {
                    orderable: false,
                    targets: [5, 6]
                }
            ],
            data: info.body,
            destroy: true,
            searching: true,
            dom: 'rtip',
            pageLength: length,
            "columns": [
                {"width": "9%"},
                {"width": "8%"},
                {"width": "15%"},
                {"width": "9%"},
                {"width": "9%"},
                {"width": "10%"},
                {"width": "6%"},
                {"width": "20%"},
            ],
            language: {
                url: '/pqs9900/json/chine.json'
            },
            "createdRow": function (row, data, index) {
                if (data[4] == "web自定义") {
                    $('td', row).eq(4).css('color', '#A52a2a')
                } else if (data[4] == "app自定义") {
                    $('td', row).eq(4).css('color', "#DAA520")
                } else if(data[4] == "非自定义"){
                    $('td', row).eq(4).css('color', '#2E8B57')
                }
            },
            'fnDrawCallback': function (oTable) {
                $("#deptsId_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 = $("#deptsId").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 searchResult(value) {
    dataTable.search(value).draw();
}

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

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

}

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

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