/**
 * 用户详情对话框(可用于添加和修改对话框)
 */
var UserInfoDlg = {
    userInfoData: {},
    validateFields: {
        account: {
            validators: {
                notEmpty: {
                    message: '账户不能为空'
                }
            }
        },
        name: {
            validators: {
                notEmpty: {
                    message: '姓名不能为空'
                }
            }
        },
        phone: {
            validators: {
                notEmpty: {
                    message: '电话号码不能为空'
                },
                regexp: {
                    regexp: /^1\d{10}$/,
                    message: '手机号码格式错误'
                }
            }
        },
        type: {
            validators: {
                notEmpty: {
                    message: '账号类型不能为空'
                }
            }
        },
        companyId: {
            validators: {
                notEmpty: {
                    message: '单位不能为空'
                }
            }
        },
        password: {
            validators: {
                notEmpty: {
                    message: '密码不能为空'
                },
                identical: {
                    field: 're_password',
                    message: '两次密码不一致'
                },
            }
        },
        re_password: {
            validators: {
                notEmpty: {
                    message: '密码不能为空'
                },
                identical: {
                    field: 'password',
                    message: '两次密码不一致'
                },
            }
        }
    }
};

/**
 * 清除数据
 */
UserInfoDlg.clearData = function () {
    this.userInfoData = {};
};

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
UserInfoDlg.set = function (key, value) {
    if (typeof value == "undefined") {
        if (typeof $("#" + key).val() == "undefined") {
            var str = "";
            var ids = "";
            $("input[name='" + key + "']:checkbox").each(function () {
                if (true == $(this).is(':checked')) {
                    str += $(this).val() + ",";
                }
            });
            if (str) {
                if (str.substr(str.length - 1) == ',') {
                    ids = str.substr(0, str.length - 1);
                }
            } else {
                $("input[name='" + key + "']:radio").each(function () {
                    if (true == $(this).is(':checked')) {
                        ids = $(this).val()
                    }
                });
            }
            this.userInfoData[key] = ids;
        } else {
            this.userInfoData[key] = $("#" + key).val();
        }
    }

    return this;
};

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
UserInfoDlg.get = function (key) {
    return $("#" + key).val();
};

/**
 * 关闭此对话框
 */
UserInfoDlg.close = function () {
    parent.layer.close(window.parent.MgrUser.layerIndex);
};

// /**
//  * 点击部门input框时
//  *
//  * @param e
//  * @param treeId
//  * @param treeNode
//  * @returns
//  */
// UserInfoDlg.onClickDept = function (e, treeId, treeNode) {
//     $("#citySel").attr("value", instance.getSelectedVal());
//     $("#deptid").attr("value", treeNode.id);
// };
//
// /**
//  * 显示部门选择的树
//  *
//  * @returns
//  */
// UserInfoDlg.showDeptSelectTree = function () {
//     var cityObj = $("#citySel");
//     var cityOffset = $("#citySel").offset();
//     $("#menuContent").css({
//         left: cityOffset.left + "px",
//         top: cityOffset.top + cityObj.outerHeight() + "px"
//     }).slideDown("fast");
//
//     $("body").bind("mousedown", onBodyDown);
// };
//
// /**
//  * 显示用户详情部门选择的树
//  *
//  * @returns
//  */
// UserInfoDlg.showInfoDeptSelectTree = function () {
//     var cityObj = $("#citySel");
//     var cityPosition = $("#citySel").position();
//     $("#menuContent").css({
//         left: cityPosition.left + "px",
//         top: cityPosition.top + cityObj.outerHeight() + "px"
//     }).slideDown("fast");
//
//     $("body").bind("mousedown", onBodyDown);
// };
//
// /**
//  * 隐藏部门选择的树
//  */
// UserInfoDlg.hideDeptSelectTree = function () {
//     $("#menuContent").fadeOut("fast");
//     $("body").unbind("mousedown", onBodyDown);// mousedown当鼠标按下就可以触发,不用弹起
// };

/**
 * 收集数据
 */
UserInfoDlg.collectData = function () {
    this.set('id')
            .set('account')
            .set('sex')
            .set('type')
            .set('password')
            .set('avatar')
            .set('email')
            .set('name')
            .set('birthday')
            .set('re_password')
            .set('deptid')
            .set('phone')
            .set('companyId')
            .set("groupCode");
};

/**
 * 验证两个密码是否一致
 */
UserInfoDlg.validatePwd = function () {
    var password = this.get("password");
    var re_password = this.get("re_password");
    if (password == re_password) {
        return true;
    } else {
        return false;
    }
};

/**
 * 验证数据是否为空
 */
UserInfoDlg.validate = function () {
    $('#userInfoForm').data("bootstrapValidator").resetForm();
    $('#userInfoForm').bootstrapValidator('validate');
    return $("#userInfoForm").data('bootstrapValidator').isValid();
};

/**
 * 提交添加用户
 */
UserInfoDlg.addSubmit = function () {
    this.clearData();
    this.collectData();
    if (!this.validate()) {
        return;
    }
    if (!this.validatePwd()) {
        Feng.error("两次密码输入不一致");
        return;
    }
    //提交信息
    var ajax = new $ax("/admin/user/add", function (data) {
        Feng.success(data.msg);
        window.parent.MgrUser.table.refresh();
        UserInfoDlg.close();
    }, function (data) {
        Feng.error(data.responseJSON.msg);
    });
    ajax.set(this.userInfoData);
    ajax.start();
};

/**
 * 提交修改
 */
UserInfoDlg.editSubmit = function () {
    this.clearData();
    this.collectData();
    if (!this.validate()) {
        return;
    }
    //提交信息
    var ajax = new $ax("/admin/user/edit", function (data) {
        Feng.success(data.msg);
        if (window.parent.MgrUser != undefined) {
            window.parent.MgrUser.table.refresh();
            UserInfoDlg.close();
        }
    }, function (data) {
        Feng.error(data.responseJSON.msg);
    });
    ajax.set(this.userInfoData);
    ajax.start();
};
/**
 * 提交修改
 */
UserInfoDlg.editInfo = function () {
    this.clearData();
    this.collectData();
    if (!this.validate()) {
        return;
    }
    //提交信息
    var ajax = new $ax("/admin/user/info", function (data) {
        Feng.success(data.msg);
        if (window.parent.MgrUser != undefined) {
            window.parent.MgrUser.table.refresh();
            UserInfoDlg.close();
        }
    }, function (data) {
        Feng.error(data.responseJSON.msg);
    });
    ajax.set(this.userInfoData);
    ajax.start();
};

UserInfoDlg.companyChange = function () {
    var companyId = $("#companyId").val()
    if (Feng.isNotEmptyStr(companyId)) {
        var ajax = new $ax("/admin/company/detail/id/" + companyId, function (data) {
            if (data.code == CONFIG.COM_VISITGROUP) {
                $("#groupCode").parent().parent().css("display", "block");
            } else {
                $("#groupCode").val("")
                $("#groupCode").parent().parent().css("display", "none");
            }
        }, function (data) {
            Feng.error("查询失败!" + data.responseJSON.message + "!");
        });
        ajax.start();
    } else {
        $("#groupCode").val("")
        $("#groupCode").parent().parent().css("display", "none");
    }
}

/**
 * 修改密码
 */
UserInfoDlg.chPwd = function () {
    var ajax = new $ax("/admin/user/change_pwd", function (data) {
        Feng.success(data.msg);
    }, function (data) {
        Feng.error(data.responseJSON.msg);
    });
    ajax.set("old_password");
    ajax.set("password");
    ajax.set("re_password");
    ajax.start();

};

function onBodyDown(event) {
    if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(
            event.target).parents("#menuContent").length > 0)) {
        UserInfoDlg.hideDeptSelectTree();
    }
}

$(function () {
    Feng.initValidatorTip("userInfoForm", UserInfoDlg.validateFields);
    Feng.addAjaxSelect({
        "id": "companyId",
        "displayCode": "id",
        "displayName": "name",
        "type": "GET",
        "url": "/admin/company/selectAll"
    });
    var arr = [{"name": "groupCode", "code": "un_visit_group"}];
    Feng.findChildDictBatch(JSON.stringify(arr));
    //批量加载时间控件
    laydate.render({elem: "#birthday", type: "date", trigger: 'click', format: 'yyyy-MM-dd', value: new Date($("#birthday").val())});
    $("select").each(function () {
        $(this).val($(this).attr("value")).trigger("change");
    });
    // var ztree = new $ZTree("treeDemo", "/dept/tree");
    // ztree.bindOnClick(UserInfoDlg.onClickDept);
    // ztree.init();
    // instance = ztree;

    // 初始化头像上传
    var avatarUp = new $WebUpload("avatar");
    avatarUp.setUploadBarId("progressBar");
    avatarUp.init();

});