// 用户编辑页面交互
document.addEventListener('DOMContentLoaded', function() {
    const passwordField = document.getElementById('password');
    const confirmPasswordGroup = document.getElementById('confirmPasswordGroup');
    const confirmPasswordField = document.getElementById('confirm_password');
    const userEditForm = document.getElementById('userEditForm');

    // 如果输入密码，显示确认密码字段
    passwordField.addEventListener('input', function() {
        if (this.value.trim() !== '') {
            confirmPasswordGroup.style.display = 'block';
        } else {
            confirmPasswordGroup.style.display = 'none';
            confirmPasswordField.value = '';
        }
    });

    // 表单提交验证
    userEditForm.addEventListener('submit', function(event) {
        let valid = true;

        // 清除之前的错误提示
        const invalidFields = document.querySelectorAll('.is-invalid');
        const feedbackElements = document.querySelectorAll('.invalid-feedback');

        invalidFields.forEach(field => {
            field.classList.remove('is-invalid');
        });

        feedbackElements.forEach(element => {
            element.parentNode.removeChild(element);
        });

        // 邮箱格式验证
        const emailField = document.getElementById('email');
        if (emailField.value.trim() !== '') {
            const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailPattern.test(emailField.value.trim())) {
                showError(emailField, '请输入有效的邮箱地址');
                valid = false;
            }
        }

        // 手机号码格式验证
        const phoneField = document.getElementById('phone');
        if (phoneField.value.trim() !== '') {
            const phonePattern = /^1[3456789]\d{9}$/;
            if (!phonePattern.test(phoneField.value.trim())) {
                showError(phoneField, '请输入有效的手机号码');
                valid = false;
            }
        }

        // 密码验证
        if (passwordField.value.trim() !== '') {
            if (passwordField.value.length < 6) {
                showError(passwordField, '密码长度至少为6个字符');
                valid = false;
            }

            if (passwordField.value !== confirmPasswordField.value) {
                showError(confirmPasswordField, '两次输入的密码不一致');
                valid = false;
            }
        }

        if (!valid) {
            event.preventDefault();
        }
    });

    // 显示表单字段错误
    function showError(field, message) {
        field.classList.add('is-invalid');

        const feedback = document.createElement('div');
        feedback.className = 'invalid-feedback';
        feedback.innerText = message;

        field.parentNode.appendChild(feedback);
    }

    // 处理表单提交后的成功反馈
    const successAlert = document.querySelector('.alert-success');
    if (successAlert) {
        // 如果有成功消息，显示成功对话框
        setTimeout(() => {
            $('#successModal').modal('show');
        }, 500);
    }
});
