// 注册页面JS
var countdown = 0;
var countdownTimer = null;

function sendRegisterCode() {
    if(!emailEnabled){
        layer.msg('邮件功能未启用', {icon: 2});
        return;
    }
    
    var email = $('input[name="email"]').val();
    
    if(!email){
        layer.msg('请输入邮箱地址', {icon: 2});
        return;
    }
    
    if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)){
        layer.msg('邮箱格式不正确', {icon: 2});
        return;
    }
    
    var btn = $('#btnSendCode');
    btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> 发送中...');
    
    $.ajax({
        type: 'POST',
        url: 'register.php',
        data: {action: 'send_code', email: email},
        dataType: 'json',
        success: function(response) {
            if(response.code === 0){
                layer.msg(response.msg, {icon: 1});
                startCountdown();
            } else {
                layer.msg(response.msg, {icon: 2});
                btn.prop('disabled', false).html('获取验证码');
            }
        },
        error: function() {
            layer.msg('网络错误，请稍后重试', {icon: 2});
            btn.prop('disabled', false).html('获取验证码');
        }
    });
}

function startCountdown() {
    countdown = 60;
    var btn = $('#btnSendCode');
    
    countdownTimer = setInterval(function(){
        countdown--;
        if(countdown <= 0){
            clearInterval(countdownTimer);
            btn.prop('disabled', false).html('获取验证码');
        } else {
            btn.html(countdown + '秒后重试');
        }
    }, 1000);
}

$(document).ready(function(){
    // 注册表单提交
    $('#registerForm').on('submit', function(e){
        e.preventDefault();
        
        var formData = $(this).serialize();
        var submitBtn = $(this).find('button[type="submit"]');
        var originalText = submitBtn.html();
        
        // 验证用户名
        var username = $('input[name="username"]').val();
        if(!/^[a-zA-Z0-9_]{4,20}$/.test(username)){
            layer.msg('用户名必须为4-20位字母、数字或下划线', {icon: 2});
            return;
        }
        
        // 验证密码
        var password = $('input[name="password"]').val();
        var confirmPassword = $('input[name="confirm_password"]').val();
        if(password.length < 6){
            layer.msg('密码长度不能少于6位', {icon: 2});
            return;
        }
        if(password !== confirmPassword){
            layer.msg('两次输入的密码不一致', {icon: 2});
            return;
        }
        
        // 验证邮箱（邮件功能启用时才校验）
        if(emailEnabled){
            var email = $('input[name="email"]').val();
            if(!email){
                layer.msg('请输入邮箱地址', {icon: 2});
                return;
            }
            if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)){
                layer.msg('邮箱格式不正确', {icon: 2});
                return;
            }
            
            // 验证验证码
            var emailCode = $('input[name="email_code"]').val();
            if(!emailCode){
                layer.msg('请输入邮箱验证码', {icon: 2});
                return;
            }
        }
        
        // 禁用提交按钮
        submitBtn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> 注册中...');
        
        $.ajax({
            type: 'POST',
            url: 'register.php',
            data: formData,
            dataType: 'json',
            success: function(response) {
                if(response.code === 0) {
                    layer.alert(response.msg, {icon: 1}, function(){
                        window.location.href = 'login.php';
                    });
                } else {
                    layer.alert(response.msg, {icon: 2});
                    submitBtn.prop('disabled', false).html(originalText);
                }
            },
            error: function() {
                layer.alert('网络错误，请稍后重试', {icon: 2});
                submitBtn.prop('disabled', false).html(originalText);
            }
        });
    });
    
    // 实时验证用户名
    $('input[name="username"]').on('blur', function(){
        var username = $(this).val();
        if(username.length >= 4 && /^[a-zA-Z0-9_]+$/.test(username)){
            checkUsername(username);
        }else{
            $('#usernameHint').removeClass('text-danger text-success').text('4-20位字母、数字或下划线');
        }
    });
});

function checkUsername(username) {
    $.ajax({
        type: 'POST',
        url: 'register.php',
        data: {check_username: username},
        dataType: 'json',
        success: function(response) {
            if(response.available === false) {
                $('#usernameHint').removeClass('text-success').addClass('text-danger').text('用户名已存在');
            } else {
                $('#usernameHint').removeClass('text-danger').addClass('text-success').text('用户名可用');
            }
        }
    });
}

function quickRegister(type) {
    var typename = type == 'wx' ? '微信' : 'QQ';
    layer.confirm('确定要使用' + typename + '快速注册吗？将自动生成账号密码', {btn: ['确定', '取消'], icon: 3}, function(){
        var ii = layer.load(2, {shade:[0.1,'#fff']});
        $.ajax({
            type: 'POST',
            url: 'login.php',
            data: { type: type, bind_mode: 'bind' },
            dataType: 'json',
            success: function(data) {
                layer.close(ii);
                if(data.code == 0){
                    window.location.href = data.url;
                } else {
                    layer.alert('获取跳转链接失败: ' + data.msg, {icon: 2});
                }
            },
            error: function(xhr) {
                layer.close(ii);
                var msg = '网络错误';
                try {
                    var res = JSON.parse(xhr.responseText);
                    if(res.msg) msg = res.msg;
                } catch(e) {}
                layer.alert('连接快捷登录服务失败: ' + msg, {icon: 2});
            }
        });
    });
}
