/**
 * 后台管理相关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);
                }
            }
        });
    });

    // 编辑权限组权限
    $('.edit_permission').on('click', function () {
        // 清空权限列表
        $('#id').val('');
        $('#title1').val('');
        $("input[type='checkbox']").prop('checked', false);
        let group_id = $(this).attr('data-permission-id');
        let group_name = $(this).attr('data-permission-name');
        $('#id').val(group_id);
        $('#title1').val(group_name);
        if ($(this).attr('data-permission') !== '') {
            let group_permission = JSON.parse($(this).attr('data-permission'));
            for (let gp in group_permission) {
                let plist = group_permission[gp];
                for (let p of plist) {
                    $("input[value='"+p+"'").prop('checked', true);
                }
            }
        }
    });

    // 一级权限选中或取消
    $("input[name='topPermission[]']").on('click', function () {
        let id = $(this).attr('id');
        if($(this).is(':checked')) {
            // 选中
            $("input[name='permission_"+id+"[]']").prop('checked', true);
        } else {
            // 取消选中
            $("input[name='permission_"+id+"[]']").prop('checked', false);
        }
    });

    // 二级权限选中或取消
    $("input[name^='permission_']").on('click', function () {
        let topid = $(this).attr('data-controller');
        if($(this).is(':checked')) {
            // 选中
            $('#'+ topid).prop('checked', true);
        } else {
            // 取消选中（排除工具这个独立分离的url）
            if (topid !== 'tool') {
                // 不存在选中权限
                if (!$("input[name='permission_"+ topid +"[]']").is(':checked')) {
                    $('#'+ topid).prop('checked', false);
                }
            }
        }
    });

    // 删除权限组传值
    $('.del_permission').on('click', function () {
        let id = $(this).data('id');
        $('#delete_id').val(id);
    });

    // 账号管理权限组选择
    $('.edit_group').on('click', function () {
        let name = $(this).attr('data-name');
        let id = $(this).attr('data-id');
        let permission = $(this).attr('data-permission');
        if (name !== '') {
            $('#group_name').text(name);
        } else {
            $('#group_name').text('未分配');
        }
        $('#manager_id').val(id);
        if (permission !== '') {
            $('#group_permission').val(permission);
        } else {
            $('#group_permission').val(0);
        }
        let groupInfo = permissionGroupList.find(function (item) {
            return item._id === permission;
        });
        let top_name = groupInfo !== undefined ? groupInfo.top_name : '';
        $('#group_permission_name').text(top_name);
    });

    // 权限组变更时改变
    $('#group_permission').change(function () {
        let permission = $(this).val();
        let groupInfo = permissionGroupList.find(function (item) {
            return item._id === permission;
        });
        let top_name = groupInfo !== undefined ? groupInfo.top_name : '';
        $('#group_permission_name').text(top_name);
    });

    // 选择框
    $(".selector > li > a").click(function() {
        let value = $(this).data("value");
        let string = $(this).text();
        let selector = $(this).parent().parent();
        selector.next("input:hidden").val(value);
        selector.prev("button").children("span").eq(0).html(string);

        // 筛选结果跳转
        console.log($('#office_select').val());
        console.log($('#permission_select').val());
        let query = [];
        if ($('#office_select').val() !== 'all' && $('#office_select').val() !== '') {
            query.push('office=' + $('#office_select').val());
        }
        if ($('#permission_select').val() !== 'all' && $('#permission_select').val() !== '') {
            query.push('permission=' + $('#permission_select').val());
        }
        let requestUrl = query.join('&');
        window.location.href = requestUrl !== '' ? '/manager?' + requestUrl :  '/manager';
    });
});
