$(function() {
    validateKickout();

    // 根据开关初始化不同的验证规则
    if (smsLoginEnabled) {
        validateSmsRule();
    } else {
        validateRule();
    }

    $('.imgcode').click(function() {
        var url = ctx + "captcha/captchaImage?type=" + captchaType + "&s=" + Math.random();
        $(".imgcode").attr("src", url);
    });

    // 使用一次性事件绑定，避免重复绑定
    bindLoginEvents();
});

// 绑定登录相关事件 - 确保只绑定一次
function bindLoginEvents() {
    // 解绑之前的事件，避免重复绑定
    $('#btnSendSms').off('click').on('click', function(e) {
        e.preventDefault(); // 阻止默认行为
        e.stopPropagation(); // 阻止事件冒泡
        sendSmsCode();
    });

    // 短信登录按钮
    $('#btnSmsSubmit').off('click').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        smsLogin();
    });

    // 密码登录按钮
    $('#btnSubmit').off('click').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        login();
    });

    // 回车提交
    $(document).off('keypress').on('keypress', function(e) {
        if (e.which == 13) {
            e.preventDefault();
            if (smsLoginEnabled) {
                smsLogin();
            } else {
                login();
            }
        }
    });
}

// 密码登录
function login() {
    // 防止重复点击
    if ($('#btnSubmit').prop('disabled')) {
        return;
    }

    var username = $.common.trim($("input[name='username']").val());
    var password = $.common.trim($("input[name='password']").val());
    var validateCode = $("input[name='validateCode']").val();
    var rememberMe = $("input[name='rememberme']").is(':checked');

    if($.common.isEmpty(validateCode) && captchaEnabled) {
        $.modal.msg("请输入验证码");
        return false;
    }

    var $btn = $('#btnSubmit');
    $btn.prop('disabled', true).text('登录中...');

    $.ajax({
        type: "post",
        url: ctx + "login",
        data: {
            "username": username,
            "password": password,
            "validateCode": validateCode,
            "rememberMe": rememberMe
        },
        beforeSend: function () {
            $.modal.loading("正在验证登录，请稍候...");
        },
        success: function(r) {
            if (r.code == web_status.SUCCESS) {
                // 登录成功，设置标记表示需要显示免责声明
                sessionStorage.setItem('showDisclaimer', 'true');
                location.href = ctx + 'index';
            } else {
                $('.imgcode').click();
                $(".code").val("");
                $.modal.msg(r.msg);
                $btn.prop('disabled', false).text('登 录');
            }
            $.modal.closeLoading();
        },
        error: function() {
            $.modal.closeLoading();
            $.modal.msgError("登录请求失败");
            $btn.prop('disabled', false).text('登 录');
        }
    });
}

// 短信登录
function smsLogin() {
    // 防止重复点击
    if ($('#btnSmsSubmit').prop('disabled')) {
        return;
    }

    var phone = $.common.trim($("input[name='phone']").val());
    var smsCode = $.common.trim($("input[name='smsCode']").val());
    var rememberMe = $('#smsRememberme').is(':checked');

    if(!phone) {
        $.modal.msgWarning('请输入手机号码');
        return;
    }

    if(!/^1[3-9]\d{9}$/.test(phone)) {
        $.modal.msgWarning('请输入正确的手机号码');
        return;
    }

    if(!smsCode) {
        $.modal.msgWarning('请输入验证码');
        return;
    }

    var $btn = $('#btnSmsSubmit');
    $btn.prop('disabled', true).text('登录中...');

    $.ajax({
        type: "post",
        url: ctx + "smsLogin",
        data: {
            "phone": phone,
            "smsCode": smsCode,
            "rememberMe": rememberMe
        },
        beforeSend: function () {
            $.modal.loading("正在验证登录，请稍候...");
        },
        success: function(r) {
            if (r.code == web_status.SUCCESS) {
                $.modal.msgSuccess('登录成功');
                sessionStorage.setItem('showDisclaimer', 'true');
                setTimeout(function(){
                    location.href = ctx + 'index';
                }, 1000);
            } else {
                $.modal.msgError(r.msg);
                $btn.prop('disabled', false).text('登 录');
            }
            $.modal.closeLoading();
        },
        error: function(xhr, status, error) {
            $.modal.closeLoading();
            $.modal.msgError("登录请求失败");
            $btn.prop('disabled', false).text('登 录');
        }
    });
}

// 发送短信验证码
function sendSmsCode() {
    // 防止重复点击
    if ($('#btnSendSms').prop('disabled')) {
        return;
    }

    var phone = $.common.trim($("input[name='phone']").val());
    var captchaCode = $.common.trim($("input[name='captchaCode']").val());

    if(!phone) {
        $.modal.msgWarning('请输入手机号码');
        return;
    }

    if(!/^1[3-9]\d{9}$/.test(phone)) {
        $.modal.msgWarning('请输入正确的手机号码');
        return;
    }

    // 如果开启了图形验证码，检查图形验证码
    if (smsCaptchaEnabled) {
        if(!captchaCode) {
            $.modal.msgWarning('请输入图形验证码');
            return;
        }
    }

    var $btn = $("#btnSendSms");
    $btn.prop('disabled', true);
    var countdown = 60;

    // 构建请求数据
    var requestData = {
        "phone": phone
    };

    // 如果开启了图形验证码，添加图形验证码参数
    if (smsCaptchaEnabled) {
        requestData.captchaCode = captchaCode;
    }

    $.ajax({
        type: "post",
        url: ctx + "sendSmsCode",
        data: requestData,
        beforeSend: function () {
            $.modal.loading("正在发送验证码...");
        },
        success: function(r) {
            $.modal.closeLoading();
            if (r.code == web_status.SUCCESS) {
                $.modal.msgSuccess("验证码发送成功");

                // 开始倒计时
                var timer = setInterval(function(){
                    if (countdown <= 0) {
                        clearInterval(timer);
                        $btn.text('获取验证码').prop('disabled', false);
                        // 倒计时结束后刷新图形验证码（如果开启了）
                        if (smsCaptchaEnabled) {
                            refreshSmsCaptcha();
                        }
                    } else {
                        $btn.text(countdown + '秒后重新发送');
                        countdown--;
                    }
                }, 1000);
            } else {
                $.modal.msgError(r.msg);
                $btn.prop('disabled', false);
                // 发送失败时刷新图形验证码（如果开启了）
                if (smsCaptchaEnabled) {
                    refreshSmsCaptcha();
                }
            }
        },
        error: function(xhr, status, error) {
            $.modal.closeLoading();
            $.modal.msgError("验证码发送失败");
            $btn.prop('disabled', false);
            // 发送失败时刷新图形验证码（如果开启了）
            if (smsCaptchaEnabled) {
                refreshSmsCaptcha();
            }
        }
    });
}

// 刷新短信登录的图形验证码
function refreshSmsCaptcha() {
    $('#smsCaptchaImg').attr('src', ctx + 'captcha/captchaImage?type=' + captchaType + '&t=' + new Date().getTime());
    $('input[name="captchaCode"]').val('');
}

// 密码登录表单验证规则
function validateRule() {
    var icon = "<i class='fa fa-times-circle'></i> ";
    $("#passwordLoginForm").validate({
        rules: {
            username: {
                required: true
            },
            password: {
                required: true
            }
        },
        messages: {
            username: {
                required: icon + "请输入您的用户名",
            },
            password: {
                required: icon + "请输入您的密码",
            }
        }
        // 移除 submitHandler，避免自动提交
    });
}

// 短信登录表单验证规则
function validateSmsRule() {
    var icon = "<i class='fa fa-times-circle'></i> ";

    // 定义基础规则
    var rules = {
        phone: {
            required: true,
            minlength: 11,
            maxlength: 11,
            digits: true
        },
        smsCode: {
            required: true,
            minlength: 4,
            maxlength: 6,
            digits: true
        }
    };

    var messages = {
        phone: {
            required: icon + "请输入手机号码",
            minlength: icon + "手机号码格式不正确",
            maxlength: icon + "手机号码格式不正确",
            digits: icon + "手机号码只能包含数字"
        },
        smsCode: {
            required: icon + "请输入短信验证码",
            minlength: icon + "验证码格式不正确",
            maxlength: icon + "验证码格式不正确",
            digits: icon + "验证码只能包含数字"
        }
    };

    // 如果开启了图形验证码，添加图形验证码验证规则
    if (smsCaptchaEnabled) {
        rules.captchaCode = {
            required: true/*,
            minlength: 4,
            maxlength: 5*/
        };
        messages.captchaCode = {
            required: icon + "请输入图形验证码",
            // minlength: icon + "图形验证码格式不正确",
            // maxlength: icon + "图形验证码格式不正确"
        };
    }

    // 只调用一次 validate
    $("#smsLoginForm").validate({
        rules: rules,
        messages: messages
        // 移除 submitHandler，避免自动提交
    });
}

function validateKickout() {
    if (getParam("kickout") == 1) {
        layer.alert("<font color='red'>您已在别处登录，请您修改密码或重新登录</font>", {
                icon: 0,
                title: "系统提示"
            },
            function(index) {
                //关闭弹窗
                layer.close(index);
                if (top != self) {
                    top.location = self.location;
                } else {
                    var url = location.search;
                    if (url) {
                        var oldUrl = window.location.href;
                        var newUrl = oldUrl.substring(0, oldUrl.indexOf('?'));
                        self.location = newUrl;
                    }
                }
            });
    }
}

function getParam(paramName) {
    var reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null;
}

// 确保函数在全局作用域中可用
window.login = login;
window.smsLogin = smsLogin;
window.sendSmsCode = sendSmsCode;
window.validateRule = validateRule;
window.validateSmsRule = validateSmsRule;
window.validateKickout = validateKickout;
window.getParam = getParam;
window.bindLoginEvents = bindLoginEvents;
window.refreshSmsCaptcha = refreshSmsCaptcha;