var trId = "";
var isAdd = true;

function EditUser(UserId) {    
    isAdd = false;

    $("#trPassword").hide();

    clearForm(isAdd);

    $.ajax({
        url: "/System/GetUser",
        type: 'GET',
        cache: false,
        data: { UserId: UserId },
        success: function (result) {
            if (result.code == 0) {
                $("#UserName").val(result.data.UserName);
                $("#Phone").val(result.data.Phone);
                $("#Mobile").val(result.data.Mobile);
                $("#Email").val(result.data.Email);
                $("#UserId").val(result.data.UserId);
                $("#LoginId").val(result.data.LoginId);
                $("#Memo").val(result.data.Memo);

                if (result.data.AutoGenerateUserId) {
                    $("#AutoGenerate").prop("checked", "checked");
                }
                else {
                    $("#AutoGenerate").prop("checked",false);
                }

                if (result.data.IsActive) {
                    $("#IsActive").prop("checked", false);
                }
                else {
                    $("#IsActive").prop("checked", true);
                }

                showUser();
            }
            else {
                alert(result.message);
            }

        },
        error: function (e) {
            alert("查找用户信息失败");
        }
    });

    return false;
}

function DeleteUser(UserId) {

    synConfirm("确定删除吗？", function () {
        $.ajax({
            url: "/System/DeleteUser",
            type: 'POST',
            cache: false,
            data: { UserId: UserId },
            success: function (result) {
                if (result.code == 0) {
                    location.href = '/System/User';
                }
                else {
                    alert(result.message);
                }

            },
            error: function (e) {
                alert('该用户已产生业务数据，无法删除。\n如果此用户已不再参与业务，可禁用该用户。');
            }
        });
    });

    return false;
}

function ResetPassword(UserId, UserName) {

    synConfirm('确定要为用户 [ ' + UserName + '] 重置密码吗？', function () {
        $.ajax({
            url: "/System/ResetPassword",
            type: 'POST',
            cache: false,
            data: { UserId: UserId },
            success: function (result) {
                if (result.code == 0) {
                    $('#divPassword').dialog('open')
                    $("#divPasswordContent").html(result.message);
                }
                else {
                    alert(result.message);
                }

            },
            error: function (e) {
                alert('密码重置失败');
            }
        });
    });

    return false;
}

$(function () {

    setOperationBtns();

    //$("#LoginId").attr('title', '登录账号创建后不可更改');
    //$("#LoginId").tooltip();

    TdRowOverOut("tUser");

    $('#divUser').dialog({
        width: 500,
        autoOpen: false,
        modal: true,
        buttons: {
        }
    });

    $('#divPassword').dialog({
        width: 180,
        autoOpen: false,
        modal: true,
        buttons: {
        }
    });

    $('#divPermission').dialog({
        width: 640,
        autoOpen: false,
        modal: true,
        buttons: {
        }
    });

    $('#btnNew').click(function () {
        isAdd = true;
        $("#trPassword").show();
        clearForm(isAdd);
        showUser();
    });

    $('#btnCancel').click(function () {
        $('#divUser').dialog('close');
    });

    $("#btnAddDepartment").click(function () {
        MoveOptions("adepartment", "bdepartment");
    });

    $("#btnRemoveDepartment").click(function () {
        MoveOptions("bdepartment", "adepartment");
    });

    $("#btnSavePermission").click(function () {

        synConfirm("确定要保存吗？", function () {

            var permissions = [];
            $("#divPermission").find("input[type=checkbox]").each(function () {
                if ($(this).prop("checked")) {
                    permissions.push(this.id);
                }
            });

            $.ajax({
                url: "/System/UpdateUserPermission",
                type: 'POST',
                cache: false,
                data: { UserId: $("#UserId").val(), Permission: JSON.stringify(permissions) },
                success: function (result) {
                    if (result.code == 0) {
                        closePermission();
                        location.href = "/System/User";
                    }
                    else {                       
                        SetErrorMsg(result.message, "divPermission");                         
                    }
                },
                error: function (e) {
                    SetErrorMsg("保存失败", "divPermission");                     
                }
            });
        });
   
    });

    $('#btnSave').click(function () {

        if (isAdd) {
            if (checkRequired('divUser', 'errorMessage') == false) {
                return;
            }
  
            if (!IsEmail($.trim($("#LoginId").val()))) {
                $("#LoginId").addClass("redBorder");
                SetErrorMsg("登录账号必须为Email地址", "divUser");
                return;
            }

            if ($("#Password").val()=="") {
                $("#Password").addClass("redBorder");
                SetErrorMsg("请填写初始密码", "divUser");
                return;
            }            
            
            $.ajax({
                url: "/System/AddUser",
                type: 'POST',
                cache: false,
                data: {
                    LoginId: $.trim($("#LoginId").val()), UserName: $("#UserName").val(), Phone: $("#Phone").val(),
                    Email: $.trim($("#LoginId").val()), Mobile: $("#Mobile").val(), Memo: $("#Memo").val(), IsActive: $("#IsActive").prop("checked"), Password: $("#Password").val()
                },
                success: function (result) {
                    if (result.code == 0) {
                        closeUser();
                        location.href = "/System/User";
                    }
                    else {
                        SetErrorMsg(result.message, "divUser");                         
                    }
                },
                error: function (e) {
                    SetErrorMsg("保存失败", "divUser");                    
                }
            });
        }
        else {
            if (!checkRequired('divUser', 'errorMessage')) {
                return;
            }

            synConfirm("确定保存修改吗？", function () {
                $.ajax({
                    url: "/System/UpdateUser",
                    type: 'POST',
                    cache: false,
                    data: {
                        UserId: $("#UserId").val(), LoginId: $("#LoginId").val(), UserName: $("#UserName").val(), Phone: $("#Phone").val(),
                        Email: $("#Email").val(), Mobile: $("#Mobile").val(), Memo: $("#Memo").val(), IsActive: $("#IsActive").prop("checked")
                    },
                    success: function (result) {
                        if (result.code == 0) {
                            closeUser();
                            location.href = "/System/User";
                        }
                        else {
                            SetErrorMsg(result.message, "divUser");
                        }
                    },
                    error: function (e) {
                        SetErrorMsg("保存失败", "divUser");
                    }
                });
            });            
        }
    });
});

function showUser() {
    $('#divUser').dialog('open');
}

function closeUser() {
    $('#divUser').dialog('close');
}

function showDepartment() {
    $('#divDepartment').dialog('open');
}

function closeDepartment() {
    $('#divDepartment').dialog('close');
}

function showPermission() {
    $('#divPermission').dialog('open');
}

function closePermission() {
    $('#divPermission').dialog('close');
}

function EditPermission(UserId) {
    $("#UserId").val(UserId);
    $.ajax({
        url: "/System/GetUserPermission",
        type: 'GET',
        cache: false,
        data: { UserId: UserId },
        success: function (result) {
            if (result.code == 0) {
               
                $("#divPermission").find("input[type=checkbox]").prop("checked", false);
                for (var i in result.data) {
                    console.log(result.data[i] );
                    $("#divPermission").find("input[id=" + result.data[i] + "]").prop("checked", true);
                }
                showPermission();
            }
            else {
                alert(result.message);
            }

        },
        error: function (e) {
            alert("查找用户信息失败");
        }
    });
}

function clearForm(isAdd) {
    $("input").removeClass("redBorder");  
    $("input[type=text]").val("");

    ClearErrorMsg();

    $("#AutoGenerate").prop("checked",false);
    $("#IsActive").prop("checked",false);
    if (isAdd) {
        $("#LoginId").val("");
        $("#LoginId").removeAttr("readonly");
        $("#AutoGenerate").removeAttr("disabled");       
    }
    else {
        $("#LoginId").attr("readonly", "readonly");
        $("#AutoGenerate").attr("disabled", "disabled");
    }
    
}

function MoveOptions(sourceId, destinationId) {
    var x = $("#" + sourceId+" option");
    var aDepartmentList = $("#" + sourceId);
    var departmentList = $("#"+destinationId);
    var msgs = "";
    x.each(function () {
        if (this.selected) {
            departmentList.prepend(this.outerHTML);
            $("#"+ sourceId + " option[value='" + this.value + "']").remove();
        }
    });
}