/**
 * 供应商角色权限分配页面 permissions
 * @Author NZhang
 * system/role/supplier/permissions.ftl
 * RoleSupplierController
 */

var el = {
    id: '#id',
    tb: '#tb',
    resources: '#resources',
    buttons: '#buttons',
    type: "#type"
};

var selfData = {
    resList: [],
    butList: []
};

var type = $(el.type).val();
$(function () {
    //初始化表格
    loadGrid();
    //初始化数据
    initData();
});

//初始化数据
function initData() {
    var resources = $(el.resources).val();
    var buttons = $(el.buttons).val();
    selfData.resList = eval('(' + resources + ')');
    selfData.butList = eval('(' + buttons + ')');

    //获取权限表格数据。并处理数据，做成树结构
    $.get(g.ctx + 'pc/sys/role/permissionGrid?type=' + $(el.type).val(), {}, function (data) {
        var grid = [];
        $.each(data, function (index, item) {
            var children = item.children;
            if (!children) {
                children = [];
            }
            $.each(data, function (ind, ite) {
                if (ite.parentId === item.id) {
                    children.push(ite);
                }
            });
            item.children = children;
        });
        $.each(data, function (index, item) {
            if (item.parentId === '0') {
                grid.push(item)
            }
        });
        $(el.tb).treegrid('loadData', grid);
    });
}

//初始化表格
function loadGrid() {
    $(el.tb).treegrid({
        iconCls: 'icon-list',
        title: '',
        singleSelect: false,
        pagination: false,
        idField: 'id',
        loadMsg: "数据加载中......",
        rownumbers: true,
        fitColumns: true,
        remoteSort: true,
        striped: true,
        treeField: 'text',
        animate: true,
        queryParams: {
            type: 1
        },
        columns: [[
            {
                field: 'text',
                title: '菜单权限',
                width: '300',
                align: 'left'
            },
            {
                title: 'id',
                field: 'id',
                checkbox: true,
                align: 'center',
                width: 60
            },
            {
                field: 'buttons',
                title: '操作按钮权限',
                hidden: type == 2,
                width: '140',
                align: 'left',
                formatter: function (value, row) {
                    if (row.children.length === 0 && value) {
                        var html = '';
                        html += '<div style="text-overflow: ellipsis;white-space: pre-wrap;overflow: hidden;">';

                        $.each(value, function (index, item) {
                            html += '<span style="margin-left: 7px">'
                                + '<input class="button" type="checkbox" data-value="' + item.resourceId
                                + '" value="' + item.id + '" onclick="selectButton(' + row.id + ',this,event)" style="vertical-align: text-top;"/>'
                                + item.name + '</span>';
                        });

                        html += '</div>';
                        return html;
                    }
                }
            }
        ]],
        onLoadSuccess: function () {
            $.each(selfData.resList, function (index, item) {
                $(el.tb).treegrid('select', item);
            });
            $.each(selfData.butList, function (index, item) {
                $('input[type=checkbox][class="button"][value=' + item + ']').prop('checked', true);
            })
        },
        onSelect: function (row) {
            //选中时，父级节点都要选中
            var parent = $(el.tb).treegrid('getParent', row.id);
            if (parent) {
                $(el.tb).treegrid('select', parent.id);
            }
            //所属按钮全部选中
            // var buttons = row.buttons;
            // if (buttons) {
            //     $.each(buttons, function (index, item) {
            //         $('input[type=checkbox][class="button"][value=' + item.id + ']').prop('checked', true);
            //     });
            // }
        },
        onUnselect: function (row) {
            //取消选中，所有子节点都要取消选中
            var children = $(el.tb).treegrid('getChildren', row.id);
            if (children.length > 1) {
                $.each(children, function (index, item) {
                    $(el.tb).treegrid('unselect', item.id);
                })
            }
            //所属按钮也要取消选中
            var buttons = row.buttons;
            if (buttons) {
                $.each(buttons, function (index, item) {
                    $('input[type=checkbox][class="button"][value=' + item.id + ']').prop('checked', false);
                });
            }

        }
    });
}

//操作按钮点击事件
function selectButton(id, checkbox, event) {
    if (checkbox.checked === true) {
        $(el.tb).treegrid('select', id);
    }
    //阻止事件冒泡
    event.stopPropagation();
}

//权限分配 保存事件
function save(call) {

    var rows = $(el.tb).treegrid('getSelections');
    var resButton = $('input[type=checkbox][class="button"]:checked');
    var roleId = $(el.id).val();

    var resources = [], buttons = [];
    if (rows.length > 0) {
        $.each(rows, function (index, item) {
            resources.push(item.id);
        });
        if (resButton.length > 0) {
            $.each(resButton, function (index, item) {
                buttons.push({'id': parseInt(item.value), 'resourceId': parseInt(item.dataset.value)});
            });
        }

        var roleResource = {};
        roleResource.roleId = roleId;
        roleResource.resources = resources;
        roleResource.buttons = buttons;
        roleResource.menuType = type;
        let loadIndex =  topWin.layer.load(0, {
            shade: [0.6, '#eee'] //0.1透明度的白色背景
        });
        $.ajax({
            url: g.ctx + 'pc/sys/role/updatePermission',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(roleResource),
            complete: function () {
                topWin.layer.close(loadIndex);
            },
            success: function (data) {
                topWin.layer.alert("保存成功", {icon: 1}, function (idx) {
                    topWin.layer.close(idx);
                    call();
                });
            },
            error: function (data) {
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    } else {
        layer.msg("未选择任何数据!");
    }

}