<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org" th:replace="~{layout :: layout(~{::title}, ~{::content})}">
<head>
    <title th:text="${user.id} != null ? '编辑用户' : '新增用户'">用户表单</title>
</head>
<body>
    <div th:fragment="content">
        <!-- Breadcrumb -->
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a th:href="@{/}">首页</a></li>
                <li class="breadcrumb-item"><a th:href="@{/users}">用户管理</a></li>
                <li class="breadcrumb-item active" th:text="${user.id} != null ? '编辑用户' : '新增用户'">用户表单</li>
            </ol>
        </nav>
        
        <!-- User Form -->
        <div class="row justify-content-center">
            <div class="col-md-8 col-lg-6">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-user me-2"></i>
                            <span th:text="${user.id} != null ? '编辑用户' : '新增用户'">用户表单</span>
                        </h5>
                    </div>
                    
                    <div class="card-body">
                        <form th:action="${user.id} != null ? @{|/users/${user.id}|} : @{/users}" 
                              method="post" th:object="${user}" id="userForm">
                            
                            <!-- Username -->
                            <div class="mb-3">
                                <label for="username" class="form-label">
                                    <i class="fas fa-user me-2"></i>用户名
                                </label>
                                <input type="text" class="form-control" id="username" name="username" 
                                       th:value="${user.username}" required minlength="3" maxlength="50" 
                                       autocomplete="username" placeholder="请输入用户名">
                                <div class="form-text">用户名长度3-50个字符，支持字母、数字、下划线</div>
                            </div>
                            
                            <!-- Email -->
                            <div class="mb-3">
                                <label for="email" class="form-label">
                                    <i class="fas fa-envelope me-2"></i>邮箱地址
                                </label>
                                <input type="email" class="form-control" id="email" name="email" 
                                       th:value="${user.email}" required autocomplete="email" 
                                       placeholder="请输入邮箱地址">
                                <div class="form-text">请输入有效的邮箱地址</div>
                            </div>
                            
                            <!-- Password -->
                            <div class="mb-3">
                                <label for="password" class="form-label">
                                    <i class="fas fa-lock me-2"></i>密码
                                </label>
                                <div class="input-group">
                                    <input type="password" class="form-control" id="password" name="password" 
                                           minlength="6" maxlength="100" autocomplete="new-password" 
                                           placeholder="请输入密码">
                                    <button class="btn btn-outline-secondary" type="button" id="togglePassword">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </div>
                                <div class="form-text">
                                    <span th:if="${user.id} != null">留空则不修改密码</span>
                                    <span th:if="${user.id} == null">密码长度6-100个字符</span>
                                </div>
                                
                                <!-- Password Strength Indicator -->
                                <div class="password-strength mt-2" th:if="${user.id} == null">
                                    <div class="strength-bar">
                                        <div class="strength-fill" id="strengthFill"></div>
                                    </div>
                                    <small class="text-muted" id="strengthText">密码强度</small>
                                </div>
                            </div>
                            
                            <!-- Role -->
                            <div class="mb-4">
                                <label for="role" class="form-label">
                                    <i class="fas fa-shield-alt me-2"></i>用户角色
                                </label>
                                <select class="form-select" id="role" name="role" th:value="${user.role}">
                                    <option value="ROLE_USER">普通用户</option>
                                    <option value="ROLE_MEMBER">会员用户</option>
                                    <option value="ROLE_ADMIN">管理员</option>
                                </select>
                                <div class="form-text">选择用户的权限级别</div>
                            </div>
                            
                            <!-- Form Actions -->
                            <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                <a th:href="@{/users}" class="btn btn-secondary me-md-2">
                                    <i class="fas fa-times me-2"></i>取消
                                </a>
                                <button type="submit" class="btn btn-primary" id="submitBtn">
                                    <span class="loading">
                                        <i class="fas fa-spinner fa-spin me-2"></i>保存中...
                                    </span>
                                    <span class="submit-text">
                                        <i class="fas fa-save me-2"></i>保存
                                    </span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- User Info Card (for edit mode) -->
                <div class="card mt-4" th:if="${user.id} != null">
                    <div class="card-header">
                        <h6 class="mb-0">
                            <i class="fas fa-info-circle me-2"></i>用户信息
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <small class="text-muted">用户ID</small>
                                <div th:text="${user.id}">1</div>
                            </div>
                            <div class="col-md-6">
                                <small class="text-muted">创建时间</small>
                                <div>2024-01-01 10:00:00</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <style>
        .password-strength {
            margin-top: 0.5rem;
        }
        
        .strength-bar {
            height: 4px;
            background: #e9ecef;
            border-radius: 2px;
            overflow: hidden;
            margin-top: 0.25rem;
        }
        
        .strength-fill {
            height: 100%;
            transition: all 0.3s ease;
            border-radius: 2px;
        }
        
        .strength-weak { background: #dc3545; width: 25%; }
        .strength-fair { background: #ffc107; width: 50%; }
        .strength-good { background: #17a2b8; width: 75%; }
        .strength-strong { background: #28a745; width: 100%; }
        
        .loading {
            display: none;
        }
        
        .loading.show {
            display: inline-block;
        }
        
        .form-label {
            font-weight: 600;
            color: #495057;
        }
        
        .form-text {
            font-size: 0.875rem;
            color: #6c757d;
        }
        
        .card-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
        }
    </style>
    
    <script>
        // Password strength checker
        function checkPasswordStrength(password) {
            let strength = 0;
            let strengthText = '';
            let strengthClass = '';
            
            if (password.length >= 6) strength++;
            if (password.match(/[a-z]/)) strength++;
            if (password.match(/[A-Z]/)) strength++;
            if (password.match(/[0-9]/)) strength++;
            if (password.match(/[^a-zA-Z0-9]/)) strength++;
            
            switch (strength) {
                case 0:
                case 1:
                    strengthText = '密码强度：弱';
                    strengthClass = 'strength-weak';
                    break;
                case 2:
                    strengthText = '密码强度：一般';
                    strengthClass = 'strength-fair';
                    break;
                case 3:
                case 4:
                    strengthText = '密码强度：良好';
                    strengthClass = 'strength-good';
                    break;
                case 5:
                    strengthText = '密码强度：强';
                    strengthClass = 'strength-strong';
                    break;
            }
            
            return { strengthText, strengthClass };
        }
        
        // Password strength indicator (only for new users)
        const passwordField = document.getElementById('password');
        const strengthFill = document.getElementById('strengthFill');
        const strengthText = document.getElementById('strengthText');
        
        if (strengthFill && strengthText) {
            passwordField.addEventListener('input', function() {
                const password = this.value;
                
                if (password.length > 0) {
                    const { strengthText: text, strengthClass: className } = checkPasswordStrength(password);
                    strengthFill.className = 'strength-fill ' + className;
                    strengthText.textContent = text;
                } else {
                    strengthFill.className = 'strength-fill';
                    strengthText.textContent = '密码强度';
                }
            });
        }
        
        // Toggle password visibility
        document.getElementById('togglePassword').addEventListener('click', function() {
            const passwordField = document.getElementById('password');
            const icon = this.querySelector('i');
            
            if (passwordField.type === 'password') {
                passwordField.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                passwordField.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        });
        
        // Form submission with loading state
        document.getElementById('userForm').addEventListener('submit', function(e) {
            const submitBtn = document.getElementById('submitBtn');
            const loading = submitBtn.querySelector('.loading');
            const submitText = submitBtn.querySelector('.submit-text');
            
            // Show loading state
            loading.classList.add('show');
            submitText.style.display = 'none';
            submitBtn.disabled = true;
        });
        
        // Form validation
        document.getElementById('userForm').addEventListener('submit', function(e) {
            const username = document.getElementById('username').value.trim();
            const email = document.getElementById('email').value.trim();
            const password = document.getElementById('password').value.trim();
            const isEdit = document.querySelector('form').action.includes('/edit');
            
            if (!username || !email) {
                e.preventDefault();
                alert('请填写用户名和邮箱');
                return false;
            }
            
            if (!isEdit && !password) {
                e.preventDefault();
                alert('新用户必须设置密码');
                return false;
            }
            
            if (password && password.length < 6) {
                e.preventDefault();
                alert('密码长度至少6位');
                return false;
            }
            
            // Email validation
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(email)) {
                e.preventDefault();
                alert('请输入有效的邮箱地址');
                return false;
            }
        });
        
        // Auto-save draft (for new users)
        if (!document.querySelector('form').action.includes('/edit')) {
            const formData = {};
            
            ['username', 'email', 'password'].forEach(function(fieldName) {
                const field = document.getElementById(fieldName);
                if (field) {
                    field.addEventListener('input', function() {
                        formData[fieldName] = this.value;
                        localStorage.setItem('userFormDraft', JSON.stringify(formData));
                    });
                }
            });
            
            // Restore draft on page load
            const savedDraft = localStorage.getItem('userFormDraft');
            if (savedDraft) {
                try {
                    const draft = JSON.parse(savedDraft);
                    Object.keys(draft).forEach(function(key) {
                        const field = document.getElementById(key);
                        if (field && draft[key]) {
                            field.value = draft[key];
                        }
                    });
                } catch (e) {
                    console.error('Failed to restore form draft:', e);
                }
            }
            
            // Clear draft on successful submission
            document.getElementById('userForm').addEventListener('submit', function() {
                localStorage.removeItem('userFormDraft');
            });
        }
    </script>
</body>
</html>



