/**
 * 后台管理相关js
 *
 * @author CaiAoLin
 * @date 2017/7/25
 * @version
 */
$(document).ready(function() {
    let selectId = '';
    // 编辑用户
    $(".edit").click(function() {
        // 获取当前点击的数据
        let canLogin = $(this).data('login');
        if (!canLogin) {
            $("input[name='can_login']").attr('checked', 'checked');
        } else {
            $("input[name='can_login']").removeAttr('checked');
        }

        // 获取权限
        let permission = $(this).data('permission');
        permission = permission.split(',');

        $("input[name='permission[]']").each(function(index) {
            let permissionName = $(this).data('permission');

            if (permission.indexOf(permissionName) < 0) {
                $(this).removeAttr('checked');
                return true;
            }
            $(this).attr('checked', 'checked');
        });

        selectId = $(this).data('id');
        $('#edit-account').modal('show');
    });


    // 编辑后保存
    let isSaving = false;
    $("#save-manager").click(function() {
        if (selectId === '' || isSaving) {
            return false;
        }

        // 获取权限
        let permission = [];
        $("input[name='permission[]']:checked").each(function(index) {
            let permissionName = $(this).data('permission');
            permission.push(permissionName);
        });
        permission = permission.join(',');

        // 获取是否可登录
        let login = $("input[name='can_login']").is(':checked');

        $.ajax({
            url: '/manager/modify/' + selectId,
            type: 'post',
            data: {permission: permission, login: login ? 0 : 1},
            dataType: 'json',
            error: function() {
                isSaving = false;
            },
            beforeSend: function() {
                isSaving = true;
            },
            success: function(response) {
                isSaving = false;
                if (response.err === 0) {
                    $('#edit-account').modal('hide');
                } else {
                    let msg = response.msg === undefined ? '未知错误' : response.msg;
                    alert(msg);
                }
            }
        });
    });

});
