//获取公司树
getRoleTree()

//获取公司树结构 ajax请求
function getRoleTree() {

    ajaxRequest(USER_ROLE, "POST", {}, function(result) {
        let data = result.data;
        let items = '';
        let roleItems = '';

        data.forEach(function(item, key) {
            items += `<li>
            <span class="treeRole" data-id=${item.roleId}>
                <img src="images/login.png" alt="">
                ${item.roleName}
            </span>
        </li>`
        })
        $('#roleTree').html(items);
    }, function(errorMsg) {
        alert("请求数据失败!");
    })

}

//菜单列表
getMenuListDataAjax();

//获取菜单列表 ajax请求
function getMenuListDataAjax(queryParam = {}) {


    let parentIdOption = "<option value='0'>顶级菜单</option>";
    ajaxRequest(MENU_LIST, "POST", queryParam, function(result) {

        let data = result.data;
        let items = '';
        let items2 = '';
        data.forEach(function(item, key) {

            let statusMenu = "";
            if (item.type == 0) {
                statusMenu = "目录"
            } else if (item.type == 1) {
                statusMenu = "菜单"
            } else {
                statusMenu = "按钮"
            }
            let parentedMenu = item.parented ? '是' : '否';
            let perms = item.perms;
            let permSave = JSON.stringify(perms)
            delete(item.perms)

            items += "<tr>" +
                "<td class='status' data-perm=" + permSave + "  data-user='" + JSON.stringify(item) + "'></td>" +
                "<td>" + item.name + "</td>" +
                "<td>" + statusMenu + "</td>" +
                "<td>" + item.orderNum + "</td>" +
                "<td>" + parentedMenu + "</td>" +
                "</tr>"
            parentIdOption += `<option value=${item.menuId}>${item.name}</option>`

        })
        $('#menuList').html(items);
        $('#parentId').html(parentIdOption)
        $('#parentId2').html(parentIdOption)

    }, function(errorMsg) {
        alert("请求数据失败!");
    })
}

//部门树点击事件
$(".treeRole").on('click', function() {

    $('.treeRole').removeClass('selected')
    $(this).addClass('selected');

    getMenuListDataAjax({ "roleId": $(this).data('id') });

    if ($("#roleTree li:first span").hasClass('selected')) {
        $('.edit').show()
        $('.add').show()
        $('.updateAuth').hide()
    } else {
        $('.edit').hide()
        $('.add').hide()
        $('.updateAuth').show()
    }
})

/*新增 修改 关闭 弹框*/
var layer = layui.layer;
var layerCreateIndex = '';
var layerUpdateIndex = '';
var layerUpdateAuthIndex = '';

layui.use('layer', function() {

    //新增弹框
    $('.add').click(function() {
            layerCreateIndex = layer.open({
                type: 1,
                title: false,
                closeBtn: 0,
                shadeClose: true,
                skin: 'yourclass',
                area: ['400px', '450px'],
                content: $(".addMenuOut"),
                success: function() {
                    $('.clsBtn,.cancel').click(function() {
                        //alert(1)
                        layer.close(layerCreateIndex);
                    })
                }
            })
        }),
        //修改弹框信息
        $('.edit').click(function() {

            if (!$('.pure-table tr').has('.checked').length) {
                layer.msg('请选择一条需要修改的信息!', { icon: 5 });

            } else {
                //let dataId = $('.pure-table tr').find('.checked').data('id');

                let userInfo = $('.pure-table tr').find('.checked').data('user');
                let perm = $('.pure-table tr').find('.checked').data('perm');
                var reg = new RegExp('\r\n', 'g');

                $('.editMenuOut select[name=parented]').val(userInfo.parented)
                $('.editMenuOut select[name=parentId]').val(userInfo.parentId)
                $('.editMenuOut input[name=name]').val(userInfo.name)
                $('.editMenuOut input[name=url').val(userInfo.url)
                $('.editMenuOut textarea[name=perms').val(perm.replace(reg, '<br/>'))
                $('.editMenuOut select[name=type').val(userInfo.type)
                $('.editMenuOut input[name=icon').val(userInfo.icon)
                $('.editMenuOut input[name=orderNum').val(userInfo.orderNum)
                $('.editMenuOut input[name=menuId').val(userInfo.menuId)

                layerUpdateIndex = layer.open({
                    type: 1,
                    title: false,
                    closeBtn: 0,
                    shadeClose: true,
                    skin: 'yourclass',
                    area: ['410px', '500px'],
                    content: $(".editMenuOut"),
                    success: function() {
                        $('.clsBtn,.cancel').click(function() {
                            layer.close(layerUpdateIndex);
                        })
                    }
                });
            }
        })

    //新增权限弹框信息
    $('.updateAuth').click(function() {

        getMenuSelectAjax();

        //获取菜单列表 ajax请求
        function getMenuSelectAjax(queryParam = {}) {

            let parentIdOption = "<option value='0'>顶级菜单</option>";

            ajaxRequest(MENU_LIST, "POST", queryParam, function(result) {
                let data = result.data;
                data.forEach(function(item, key) {
                    parentIdOption += `<option value=${item.menuId}>${item.name}</option>`
                })
                $('#menuIdList').html(parentIdOption)

            }, function(errorMsg) {
                alert("请求数据失败!");
            })
        }

        layerUpdateAuthIndex = layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            shadeClose: true,
            skin: 'yourclass',
            area: ['410px', '300px'],
            content: $(".addAuthOut"),
            success: function() {
                $('.clsBtn,.cancel').click(function() {
                    layer.close(layerUpdateAuthIndex);
                })
            }
        });
    })

})

/* 新增发送请求 */
$('#addMenu').click(function() {

    //获取表单的值 并转换成对象
    let allParam = serializeArrayToObj($("#addMenuForm").serializeArray());

    //验证数据是否为空
    let res = validParamIsEmpty(allParam, {
        "name": "请输入菜单名称",
        "parentId": "请选择父级菜单id",
        "perms": "请输入菜单配置",
        "type": "请选择菜单类型",
    });

    if (res.code == -1) {
        alert(res.msg);
        return;
    }

    //验证通过 请求ajax
    ajaxRequest(MENU_ADD, "POST", allParam, function(result) {

        if (result.flag) {
            let data = result.data;
            layer.close(layerCreateIndex);
            getMenuListDataAjax()
        } else {
            //服务端返回报错
            alert(result.msg);
        }
    }, function(errorMsg) {
        alert("异常错误!");
    })
})

/* 修改发送请求 */
$('#dataUpdate').click(function() {

    //获取表单的值 并转换成对象
    let allParam = serializeArrayToObj($("#editMenuForm").serializeArray());

    //验证数据是否为空
    let res = validParamIsEmpty(allParam, {
        "name": "请输入菜单名称",
        "parentId": "请选择父级菜单id",
        "perms": "请输入菜单配置",
        "type": "请选择菜单类型",
    });

    if (res.code == -1) {
        alert(res.msg);
        return;
    }
    ajaxRequest(MENU_UPDATE, "POST", allParam, function(result) {
        layer.close(layerUpdateIndex);
        layer.msg('修改成功!', { icon: 6 });
        getMenuListDataAjax()
    }, function(errorMsg) {
        alert("数据修改失败!");
    })
})

/* 新增权限发送请求 */
$('#addAuth').click(function() {

    //获取表单的值 并转换成对象
    let allParam = serializeArrayToObj($("#addAuthForm").serializeArray());
    allParam.roleId = $("#roleTree li span.selected").data('id')
    ajaxRequest(ROLE_AUTH_UPDATA, "POST", allParam, function(result) {

        if (result.flag) {
            let data = result.data;
            layer.close(layerUpdateAuthIndex);
            getMenuListDataAjax(allParam)
        } else {
            //服务端返回报错
            alert(result.msg);
        }

    }, function(errorMsg) {
        alert("异常错误!");
    })


})