//@ sourceURL=user_menu_relation.js
//以下一段代码是权限树的级联效果，可以直接复制使用
//菜单树的方法区间
var menuNodeCheckedSilent = false;
var menuNodeUncheckedSilent = false;

function menuNodeChecked(event, node) {
    if (menuNodeCheckedSilent) {
        return;
    }
    menuNodeCheckedSilent = true;
    checkAllParent("menuTree",node);
    checkAllSon("menuTree",node);
    menuNodeCheckedSilent = false;
}
function menuNodeUnchecked(event, node) {
    if (menuNodeUncheckedSilent)
        return;
    menuNodeUncheckedSilent = true;
    uncheckAllParent("menuTree",node);
    uncheckAllSon("menuTree",node);
    menuNodeUncheckedSilent = false;
}
//菜单树的方法区间结尾
//人员树方法开始
var userNodeCheckedSilent = false;
var userNodeUncheckedSilent = false;

function userNodeChecked(event, node) {
    if (userNodeCheckedSilent) {
        return;
    }
    userNodeCheckedSilent = true;
    checkAllParent("userTree",node);
    checkAllSon("userTree",node);
    userNodeCheckedSilent = false;
    userCheckEd();
}
function userNodeUnchecked(event, node) {
    if (userNodeUncheckedSilent)
        return;
    userNodeUncheckedSilent = true;
    uncheckAllParent("userTree",node);
    uncheckAllSon("userTree",node);
    userNodeUncheckedSilent = false;
    userCheckEd();
}
//人员树方法结束

//选中全部父节点
function checkAllParent(id, node) {
    $('#' + id).treeview('checkNode', node.nodeId, {
        silent: true
    });
    var parentNode = $('#' + id).treeview('getParent', node.nodeId);
    if (!("nodeId" in parentNode)) {
        return;
    } else {
        checkAllParent(id, parentNode);
    }
}

//取消全部父节点
function uncheckAllParent(id, node) {
    $('#' + id).treeview('uncheckNode', node.nodeId, {
        silent: true
    });
    var siblings = $('#' + id).treeview('getSiblings', node.nodeId);
    var parentNode = $('#' + id).treeview('getParent', node.nodeId);
    if (!("nodeId" in parentNode)) {
        return;
    }
    var isAllUnchecked = true; //是否全部没选中
    for (var i in siblings) {
        if (siblings[i].state.checked) {
            isAllUnchecked = false;
            break;
        }
    }
    if (isAllUnchecked) {
        uncheckAllParent(id, parentNode);
    }
}

//级联选中所有子节点
function checkAllSon(id, node) {
    $('#' + id).treeview('checkNode', node.nodeId, {
        silent: true
    });
    if (node.nodes != null && node.nodes.length > 0) {
        for (var i in node.nodes) {
            checkAllSon(id, node.nodes[i]);
        }
    }
}

//级联取消所有子节点
function uncheckAllSon(id, node) {
    $('#' + id).treeview('uncheckNode', node.nodeId, {
        silent: true
    });
    if (node.nodes != null && node.nodes.length > 0) {
        for (var i in node.nodes) {
            uncheckAllSon(id, node.nodes[i]);
        }
    }
}

$(function () {
    //用户树
    $.ajax({
        type: "GET",
        url: '/thmz/getNewUserTree',
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            $('#userTree').treeview({//初始化权限树，把节点数据，就是data数据添加到树里面
                showCheckbox: true,//确认展示checkbox
                data: res.data,//数据
                onNodeChecked: userNodeChecked,//当选中节点check时响应函数
                onNodeUnchecked: userNodeUnchecked,//当不选中时响应函数，就是用于级联效果
                highlightSelected: true,
            });
            $("#userTree").treeview('collapseAll');//关闭展开
            //$("#userTree").treeview('expandNode',0);//展开第一个节点
        }
    });


    //菜单树
    getMenuTree();


    $("#btn_save").click(function (t) {
        saveRelation();
    });
    $("#btn_clean").click(function (t) {
        resetTree();
    });


});

/**
 * 取消所有的选中
 */
function resetTree() {
    $('#userTree').treeview('uncheckAll', { silent: true });
    $('#menuTree').treeview('uncheckAll', { silent: true });
}


function getMenuTree() {
    //菜单树
    $.ajax({
        type: "GET",
        url: '/thmz/getMenuTree',
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            $('#menuTree').treeview({//初始化权限树，把节点数据，就是data数据添加到树里面
                showCheckbox: true,//确认展示checkbox
                data: res.data,//数据
                onNodeChecked: menuNodeChecked,//当选中节点check时响应函数
                onNodeUnchecked: menuNodeUnchecked,//当不选中时响应函数，就是用于级联效果
                //silent: true, //折叠所有的节点，折叠整个树。
                collapsed: true,
                highlightSelected: true,
            });
            $("#menuTree").treeview('collapseAll');//关闭展开
           // $("#menuTree").treeview('expandNode',3);//展开第一个节点
        }
    });
}




/**
 * 设置用户和菜单权限关系
 */
function saveRelation() {
    var userTree = $('#userTree').treeview('getChecked');
    var menuTree = $('#menuTree').treeview('getChecked');
    var userIds=null;
    if(userTree.length>0){
        for (var i=0;i<userTree.length;i++){
            var dataId=userTree[i].dataId;
            if(userIds==null){
                userIds=dataId;
            }else {
                userIds+=","+dataId;
            }
        }
    }
    var menuIds=null;
    if(menuTree.length>0){
        for (var i=0;i<menuTree.length;i++){
            var dataId=menuTree[i].dataId;
            if(menuIds==null){
                menuIds=dataId;
            }else {
                menuIds+=","+dataId;
            }
        }
    }
    if(userIds==null){
        new PNotify({
            title: '提示',
            text: '您没有选择任何用户！',
            styling: 'bootstrap3'
        });
        return;
    }
    if (!confirm("是否要修改当前用户权限变更操作？")) {
        return;
    }
    $.ajax({
        type: "POST",
        url: '/thmz/saveUserMenuRelation',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        data:  JSON.stringify({
            userIds: userIds,
            menuIds: menuIds
        }),
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                resetTree();
                successMesage(res);
            } else {
                errorMesage(res);
            }
        }
    });

}


/**
 * 用户选中事件
 */
function userCheckEd() {
    var userTree = $('#userTree').treeview('getChecked');
    var userIds=null;
    if(userTree.length>0){
        for (var i=0;i<userTree.length;i++){
            if(userTree[i].nodes!=undefined){
                continue;
            }
            var dataId=userTree[i].dataId;
            if(userIds==null){
                userIds=dataId;
            }else {
                userIds+=","+dataId;
            }
        }
    }
    if(userIds==null){
        $('#menuTree').treeview('uncheckAll', { silent: true });
        $("#menuTree").treeview('collapseAll');//关闭展开
        return;
    }
    //先选中所有节点
    $('#menuTree').treeview('checkAll', { silent: true });
    var menuTree = $('#menuTree').treeview('getChecked');
    //取消所有选中
    $('#menuTree').treeview('uncheckAll', { silent: true });

    var realParams = JSON.parse('{"userIds":"","userMenuRelationVos":[]}');
    realParams.userIds = userIds;
    for (var i = 0; i < menuTree.length; i++) {
        var thisData = menuTree[i];
        var tempJson = JSON.parse('{"nodeId":"","dataId":""}');
        tempJson.nodeId = thisData.nodeId;
        tempJson.dataId = thisData.dataId;
        realParams.userMenuRelationVos[i] = tempJson;
    }
    $.ajax({
        type: "POST",
        url: '/thmz/getUserHadMenuRelation',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        data:  JSON.stringify(realParams),
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                for (var i=0;i<res.data.length;i++){
                    console.log( res.data[i]);
                    $('#menuTree').treeview('checkNode', res.data[i], {
                        silent: true
                    });
                }
                $("#menuTree").treeview('collapseAll');//关闭展开
                if(res.currentParentList!=undefined && res.currentParentList!=null && res.currentParentList.length>0){
                    for (var i=0;i<res.currentParentList.length;i++){
                        $("#menuTree").treeview('expandNode',parseInt($("#"+res.currentParentList[i]).attr("data-nodeid")));//展开节点
                    }
                }
            } else {
                errorMesage(res);
            }
        }
    });
}

