layui.extend({
    admin: '../../js/admin'
});
layui.use(['form','layer','upload','admin'],function(){
    form = layui.form;
    $ = layui.jquery;
    var layer = parent.layer === undefined ? layui.layer : top.layer,
        upload = layui.upload;

    //上传头像
    var lastsrc = $("#userFace").attr("src");
    upload.render({
        elem: '.userFaceBtn',
        url: '/GoBlogApi/upload/?type=2&w=200&h=200&lastsrc='+lastsrc,
        method : "post",  //此处是为了演示之用，实际使用中请将此删除，默认用post方式提交
        done: function(res, index, upload){
            if (res.code == 0) {
                $('#userFace').attr('src', res.data.src);
            } else {
                top.layer.msg(res.msg, {icon: 2, time:3000});
            }
        }
    });

    //添加验证规则
    form.verify({
        newPwd : function(value, item){
            if (value.length>0){
                if(value.length < 6){
                    return "密码长度不能小于6位";
                }
            }
        },
        confirmPwd : function(value, item){
            if(!new RegExp($("#newPwd").val()).test(value)){
                return "两次输入密码不一致，请重新输入！";
            }
        }
    });

    //加载个人信息
    loaduserinfo = function(){
        var userInfo = JSON.parse(window.sessionStorage.getItem('userInfo'));
        //console.info(userInfo);
        $(".username").val(userInfo.username);
        $(".nickname").val(userInfo.nickname);
        $(".email").val(userInfo.email);
        $(".avatar").attr("src",userInfo.avatar);
    };

    loaduserinfo();


    //提交个人资料

    form.on("submit(editInfo)",function(data){
        $(this).text("提交中...").attr("disabled","disabled").addClass("layui-disabled");

        var data = {
            nickname : $(".nickname").val(),
            email    : $(".email").val(),
            avatar   : $(".avatar").attr("src"),
        };
        //用新的用户覆盖缓存中的信息
        var userInfo = JSON.parse(window.sessionStorage.getItem('userInfo'));
        userInfo = $.extend(userInfo,data);
        window.sessionStorage.setItem("userInfo",JSON.stringify(userInfo));

        var password = $("#newPwd").val();
        if (password!="") {
            data = $.extend(data,{password:password});
        }
        var successfun = function(){
            location.reload();
        };
        ZjqAdminAjax('/GoBlogApi/ajax/profile', "put", data, successfun);
        $(this).text("立即提交").removeAttr("disabled").removeClass("layui-disabled");
        return false;
    });

});