var RoleMap = new HashMap()
var PermisionMap = new HashMap()
var edittype = "add"
var zdata = [];
var cols = [{
    width: 10,
    text: '序号',
    type: 'number',
    flex: true,
    colClass: 'text-center'
}, {
    width: 30,
    text: '角色',
    type: 'string',
    flex: true,
    colClass: 'text-center'
}, {
    width: 30,
    text: '操作权限',
    type: 'string',
    flex: true,
    sort: 'down',
    colClass: 'text-center'
}, {
    width: 140,
    text: '操作',
    type: 'string',
    flex: true,
    colClass: 'text-center'
}];
$(document).ready(function () {
    // $("#main_content_title").html("权限管理")
    $('#dashboard').dashboard({ draggable: true });
    var zTreeObj;
    var zNodes = [];
    dept_tree = $.fn.zTree.init($("#permision_tree"), {}, zNodes);
    getPermission()
    $("#permision_add").on("click", function () {
        var nodedata = dept_tree.getSelectedNodes();
        edittype = "add"
        loadPermisionData(nodedata)
        $('#addModal').modal('show')
    })
    $("#permision_edit").on("click", function () {
        //获取选中的节点
        var nodedata = dept_tree.getSelectedNodes();
        if (nodedata.length < 1) {
            layer.msg('请先选择权限！', {
                time: 2000, //20s后自动关闭
            });
            return;
        }
        edittype = "edit"
        loadPermisionData(nodedata)
        $('#addModal').modal('show');
    });
    $("#permision_delete").on("click", function () {
        //获取选中的节点
        var nodedata = dept_tree.getSelectedNodes();
        if (nodedata.length < 1) {
            layer.msg('请先选择权限！', {
                time: 2000, //20s后自动关闭
            });
            return;
        }

        deleteItem4CallBack(function(){
            PermisionDelete(nodedata[0].id, function (data) {
                layer.msg('删除成功！', {
                    time: 2000, //20s后自动关闭
                });
                dept_tree.removeNode(nodedata[0]);
            }, function (error) {

            });
        }); 
        
    });
    $("#role_add").on("click", function () {
        var nodedata = dept_tree.getSelectedNodes();
        edittype = "add"
        if (nodedata.length < 1) {
            layer.msg('请先选择权限！', {
                time: 2000, //20s后自动关闭
            });
            return;
        }
        loadPermisionRoleData(nodedata, 0)
        $('#addRoleModal').modal('show');
        $('#addRoleModal .modal-title').html('添加角色');
    });

    $('.datatable').datatable({
        checkable: false,
        sortable: false,
        data: {
            cols: cols,
            rows: []
        }
    });

    $('.datatable').on('click', 'button', function () {
        if (this.name == "user_edit") {
            var nodedata = dept_tree.getSelectedNodes();
            edittype = "edit";
            var user = nodedata;
            loadPermisionRoleData(user, this.id);
            $('#addRoleModal').modal('show');
            $('#addRoleModal .modal-title').html('修改角色');
        }
        if (this.name == "user_delete") {
            var nodedata = dept_tree.getSelectedNodes();
            var data = {
                "role_id": this.id,
                "permission_id": nodedata[0].id
            }
            deleteItem4CallBack(function(){
                PermisionRoleDELETE(data, function (data) {
                    var nodedata = dept_tree.getSelectedNodes();
                    updateRole(nodedata[0].id)
                    layer.msg('角色删除成功！', {
                        time: 2000, //20s后自动关闭
                    }, function () {
                    });
                },
                function (error) {

                })
            });
        }
    });

});



function getPermission() {
    function zTreeOnRename(event, treeId, treeNode, isCancel) {
        alert(treeNode.tId + ", " + treeNode.name);
    }

    //  function zTreeBeforeDrop(treeId, treeNodes, targetNode, moveType) {
    //      return !(targetNode == null || (moveType != "inner" && !targetNode.parentTId));
    //  };

    function zTreeOnRemove(event, treeId, treeNode) {
        alert(treeNode.tId + ", " + treeNode.name);
    }

    function zTreeOnClick(event, treeId, treeNode) {
        updateRole(treeNode.id)
    };


    var setting = {
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "pId",
                rootPId: null
            }
        },
        view: { //表示tree的显示状态
            selectMulti: false //表示禁止多选
        },
        check: { //表示tree的节点在点击时的相关设置
            enable: false, //是否显示radio/checkbox
            chkStyle: "checkbox", //值为checkbox或者radio表示
            checkboxType: { p: "", s: "" }, //表示父子节点的联动效果
            radioType: "level" //设置tree的分组
        },
        callback: {
            onRename: zTreeOnRename,
            //  beforeDrop: zTreeBeforeDrop,
            onRemove: zTreeOnRemove,
            onClick: zTreeOnClick
        },
        edit: {
            enable: true,
            drag: {
                autoExpandTrigger: true,
                isMove: true,
                prev: false,
                next: true,
                inner: true,
                autoOpenTime: 0
            },
            showRenameBtn: false,
            showRemoveBtn: false
        }
    };

    PermisionGetAll(function (data) {
        zdata = [];
        for (var i = 0; i < data.length; i++) {
            var m = data[i];
            var zdataItem = {};
            zdataItem["id"] = m.id;
            zdataItem["value"] = m.id;
            zdataItem["pId"] = null;
            zdataItem["name"] = m.name;
            zdataItem["open"] = true;
            zdataItem["children"] = addobj(m);
            zdata.push(zdataItem);

            PermisionMap.set(m.id, m);
        }
        dept_tree = $.fn.zTree.init($("#permision_tree"), setting, zdata)
    }, function (error) {

    });
}



function addobj(data) {
    var zdata = [];
    if (typeof (data.childs) != "undefined" && data.childs != null &&
        data.childs.length > 0) {
        for (var i = 0; i < data.childs.length; i++) {
            var m = data.childs[i];
            var zdataItem = {};
            zdataItem["id"] = m.id;
            zdataItem["value"] = m.id;
            zdataItem["pId"] = data.id;
            zdataItem["icon"] = "";
            zdataItem["open"] = true;
            zdataItem["name"] = m.name;
            zdataItem["children"] = addobj(m);
            zdata.push(zdataItem);

            PermisionMap.set(m.id, m);
        }
        return zdata;
    } else {
        return [];
    }
}
function updateRole(permisionid) {

    RoleGetByPermision(permisionid, function (data) {

        //跟新table
        var rowdata = [];
        if (data != null && data.length > 0) {
            for (var i = 0; i < data.length; i++) {
                var role = data[i];

                RoleMap.set(role.id, role)
                var roledata = {};
                roledata["checked"] = false;
                roledata["data"] = [i + 1, typeof (role.des) == "undefined" ? "" : role.des, typeof (role.mod) == "undefined" ? getpertype(1) : getpertype(role.mod), '<button class="btn btn-primary" name="user_edit" id=' + role.id + '><i class="icon icon-edit"></i>修改</button>  <button class="btn btn-primary" name="user_delete" id=' + role.id + ' ><i class="icon icon-remove-circle"></i>删除</button>'];
                rowdata.push(roledata);

                RoleMap.set(role.id, role);
            }
        }

        // 使用data参数更新数据：
        $('.datatable').datatable('load', {
            cols: cols,
            rows: rowdata
        });

    },
        function (error) {

        });
}

function getpertype(mod) {
    switch (mod) {
        case 1:
            return "读写";
        case 2:
            return "写";
        case 3:
            return "读";
        case 4:
            return "删除";
        default: return "读";
    }

}