<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>车主信息查询系统 - 用户管理</title>
    <!-- 引入Layui CSS -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/layui.css') }}">
    <!-- 引入Font Awesome -->
    <link href="{{ url_for('static', filename='css/font-awesome.min.css') }}" rel="stylesheet">
    <!-- 引入自定义CSS -->
    <link href="{{ url_for('static', filename='css/custom.css') }}" rel="stylesheet">
    
    <!-- 引入Layui JS -->
    <script src="{{ url_for('static', filename='layui.js') }}"></script>
    
    <!-- 初始化Layui组件 -->
    <script>
        layui.use(['layer', 'form', 'table'], function(){
            var layer = layui.layer;
            var form = layui.form;
            var table = layui.table;
            
            // 渲染所有表单元素
            form.render();
        });
    </script>
    
    <!-- 引入通用工具函数 -->
    <script src="{{ url_for('static', filename='js/utils.js') }}"></script>
</head>
<body>
    <!-- 引入统一的顶部导航栏 -->
    {% include 'header.html' %}
    
    <!-- 主要内容区域 -->
    <div class="content-container">
        <div class="content-wrapper">
            <div class="card">
                <div class="card-header">
                    <i class="fa fa-users"></i> 用户管理
                    <a href="{{ url_for('query') }}" class="layui-btn layui-btn-xs layui-btn-primary" style="float: right;">
                        <i class="fa fa-arrow-left"></i> 返回主页面
                    </a>
                </div>
                <div class="card-body">
                    <!-- 消息提示区域 -->
                    <div id="messageContainer" class="mb-6 hidden">


                    </div>
                      
                    <div class="layui-text" style="text-align: center; margin-bottom: 20px;">
                        <div style="width: 80px; height: 80px; background-color: #f2f2f2; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; margin-bottom: 15px;">
                            <i class="fa fa-users" style="font-size: 40px; color: #009688;"></i>
                        </div>
                        <p style="color: #666;">管理系统用户、审核登录权限、修改部门信息和初始化密码</p>
                    </div>

                    <!-- 搜索框 -->
                    <div class="mb-6">
                        <div class="layui-form" style="margin-bottom: 15px;">
                            <div class="layui-form-item">
                                <label class="layui-form-label">用户名</label>
                                <div class="layui-input-inline" style="width: 180px;">
                                    <input type="text" id="searchUsername" placeholder="输入用户名搜索" class="layui-input">
                                </div>
                                <label class="layui-form-label">部门</label>
                                <div class="layui-input-inline" style="width: 120px;">
                                    <select id="filterDepartment" class="layui-select" lay-search>
                                        <option value="">所有部门</option>
                                        {% for dept in departments %}
                                        <option value="{{ dept }}">{{ dept }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <label class="layui-form-label">状态</label>
                                <div class="layui-input-inline" style="width: 100px;">
                                    <select id="filterStatus" class="layui-select">
                                        <option value="">所有状态</option>
                                        <option value="active">已启用</option>
                                        <option value="inactive">已禁用</option>
                                    </select>
                                </div>
                                <div class="layui-input-inline">
                                    <button id="searchButton" onclick="searchUsers()" class="layui-btn layui-btn-normal">
                                        <i class="fa fa-search mr-1"></i> 搜索
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 用户列表表格 -->
                    <div class="overflow-x-auto">
                        <table class="layui-table">
                            <thead>
                                <tr>
                                    <th>用户名</th>
                                    <th>姓名</th>
                                    <th>部门</th>
                                    <th>状态</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="usersTableBody">
                                <!-- 用户数据将通过JavaScript动态加载 -->

                            </tbody>
                        </table>
                    </div>
                    <!-- 分页控制 -->
                    <div class="layui-form-item" style="text-align: center; margin-top: 20px;">
                        <div class="layui-input-block">
                            <span id="paginationInfo" class="layui-btn layui-btn-primary layui-btn-radius" style="margin-right: 20px;">
                                显示 <span id="startItem" style="color: #1E9FFF;">1</span> 至 <span id="endItem" style="color: #1E9FFF;">10</span> 条，共 <span id="totalItems" style="color: #1E9FFF;">0</span> 条记录
                            </span>
                            <button id="prevPage" class="layui-btn layui-btn-radius" disabled>
                                <i class="fa fa-chevron-left"></i> 上一页
                            </button>
                            <button id="nextPage" class="layui-btn layui-btn-radius">
                                下一页 <i class="fa fa-chevron-right"></i>
                            </button>
                        </div>
                    </div>

</div>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    {% include 'footer.html' %}

            <!-- 用于存储弹窗数据的隐藏字段 -->
            <input type="hidden" id="editUserId">
            <input type="hidden" id="editUsername">
            <input type="hidden" id="resetUserId">
            <input type="hidden" id="resetUsername">
            
            <!-- 部门选项数据 -->
            <script id="departmentOptions" type="application/json">
                [{% for dept in departments %}{{ dept | tojson }}{% if not loop.last %},{% endif %}{% endfor %}]
            </script>

    <!-- 安全转义函数 -->
    <script>
        // HTML转义函数，防止XSS攻击
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    </script>
    
    <!-- 用户管理相关JavaScript -->
    <script>
        // 当前页码和每页显示数量
        let currentPage = 1;
        const pageSize = 10;
        let totalUsers = 0;
        let usersData = [];
        let isLoading = false; // 添加加载状态标志
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadUsers();
            
            // 绑定搜索按钮点击事件
            document.getElementById('searchUsername').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    searchUsers();
                }
            });
            
            // 绑定分页按钮点击事件
            document.getElementById('prevPage').addEventListener('click', function() {
                if (currentPage > 1) {
                    currentPage--;
                    renderUsersTable();
                }
            });
            
            document.getElementById('nextPage').addEventListener('click', function() {
                if (currentPage < Math.ceil(totalUsers / pageSize)) {
                    currentPage++;
                    renderUsersTable();
                }
            });
            
            // 使用layui弹窗，不再需要绑定模态框点击外部关闭事件
        });
        
        // 加载用户列表
        function loadUsers() {
            if (isLoading) return;
            
            isLoading = true;
            // 显示加载状态
            const loadingRow = document.getElementById('loadingRow');
            if (loadingRow) {
                loadingRow.classList.remove('hidden');
            }
            
            // 清空表格内容
            const tableBody = document.getElementById('usersTableBody');
            if (tableBody) {
                // 只保留loadingRow元素
                const children = Array.from(tableBody.children);
                children.forEach(child => {
                    if (child.id !== 'loadingRow') {
                        tableBody.removeChild(child);
                    }
                });
            }
            
            apiRequest('/api/users')
                .then(data => {
                    if (data.success) {
                        usersData = data.data;
                        totalUsers = data.total;
                        renderUsersTable();
                    } else {
                        showMessage('加载用户列表失败：' + (data.error || '未知错误'), false);
                    }
                })
                .catch(error => {
                    console.error('加载用户列表时发生错误:', error);
                    showMessage('网络错误，请稍后重试', false);
                })
                .finally(() => {
                    isLoading = false;
                    // 隐藏加载状态
                    if (loadingRow) {
                        loadingRow.classList.add('hidden');
                    }
                });
        }
        
        // 渲染用户表格
        function renderUsersTable() {
            const tableBody = document.getElementById('usersTableBody');
            if (!tableBody) return;
            
            // 清空表格内容，但保留loadingRow
            const children = Array.from(tableBody.children);
            children.forEach(child => {
                if (child.id !== 'loadingRow') {
                    tableBody.removeChild(child);
                }
            });
            
            // 计算当前页的用户数据
            const startIndex = (currentPage - 1) * pageSize;
            const endIndex = Math.min(startIndex + pageSize, totalUsers);
            const currentUsers = usersData.slice(startIndex, endIndex);
            
            // 更新分页信息
            const startItemEl = document.getElementById('startItem');
            const endItemEl = document.getElementById('endItem');
            const totalItemsEl = document.getElementById('totalItems');
            if (startItemEl) startItemEl.textContent = startIndex + 1;
            if (endItemEl) endItemEl.textContent = endIndex;
            if (totalItemsEl) totalItemsEl.textContent = totalUsers;
            
            // 更新分页按钮状态
            const prevPageBtn = document.getElementById('prevPage');
            const nextPageBtn = document.getElementById('nextPage');
            if (prevPageBtn) prevPageBtn.disabled = currentPage === 1;
            if (nextPageBtn) nextPageBtn.disabled = currentPage === Math.ceil(totalUsers / pageSize);
            
            // 渲染用户行
            currentUsers.forEach((user) => {
                const row = document.createElement('tr');
                
                // 状态样式 - 使用layui风格
                const statusClass = user.status === 'active' ? 'layui-bg-green' : 'layui-bg-red';
                const statusText = user.status === 'active' ? '已启用' : '已禁用';
                
                // 转义用户输入以防止XSS
                const safeUsername = escapeHtml(user.username);
                const safeName = escapeHtml(user.name);
                const safeDepartment = escapeHtml(user.department);
                
                row.innerHTML = `
                    <td>${safeUsername}</td>
                    <td>${safeName}</td>
                    <td>${safeDepartment}</td>
                    <td>
                        <span class="layui-badge ${statusClass}" style="padding: 0 10px;">
                            <i class="fa ${user.status === 'active' ? 'fa-check-circle mr-1' : 'fa-times-circle mr-1'}"></i>
                            ${statusText}
                        </span>
                    </td>
                    <td>
                        <button onclick="toggleUserStatus(${user.id}, '${safeUsername}', '${user.status}')" 
                                class="layui-btn layui-btn-xs layui-btn-primary">
                            <i class="fa ${user.status === 'active' ? 'fa-lock mr-1' : 'fa-unlock mr-1'}"></i>
                            ${user.status === 'active' ? '禁用' : '启用'}
                        </button>
                        <button onclick="showEditDepartmentModal(${user.id}, '${safeUsername}', '${safeName}', '${safeDepartment}')" 
                                class="layui-btn layui-btn-xs layui-btn-normal">
                            <i class="fa fa-building mr-1"></i>
                            修改部门
                        </button>
                        <button onclick="showResetPasswordModal(${user.id}, '${safeUsername}')" 
                                class="layui-btn layui-btn-xs layui-btn-warm">
                            <i class="fa fa-key mr-1"></i>
                            初始化密码
                        </button>
                    </td>
                `;
                
                tableBody.appendChild(row);
            });
            
            // 如果没有数据，显示空状态 - 使用layUI风格
            if (totalUsers === 0) {
                const emptyRow = document.createElement('tr');
                emptyRow.innerHTML = `
                    <td colspan="5" style="text-align: center; padding: 40px 0; color: #999;">
                        <div class="layui-none">
                            <i class="fa fa-user-circle-o text-5xl mb-4" style="opacity: 0.3;"></i>
                            <p class="layui-text" style="font-size: 16px;">暂无用户数据</p>
                            <p style="color: #ccc; margin-top: 10px;">请添加新用户或等待其他用户注册</p>
                        </div>
                    </td>
                `;
                tableBody.appendChild(emptyRow);
            }
        }
        
        // 搜索用户
        function searchUsers() {
            if (isLoading) return;
            
            const searchButton = document.getElementById('searchButton');
            const originalText = searchButton.innerHTML;
            
            isLoading = true;
            searchButton.disabled = true;
            searchButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i> 搜索中...';
            
            const searchUsername = document.getElementById('searchUsername').value.toLowerCase().trim();
            const filterDepartment = document.getElementById('filterDepartment').value;
            const filterStatus = document.getElementById('filterStatus').value;
            
            apiRequest('/api/users')
                .then(data => {
                    if (data.success) {
                        // 应用过滤条件
                        usersData = data.data.filter(user => {
                            const matchesUsername = user.username.toLowerCase().includes(searchUsername);
                            const matchesDepartment = !filterDepartment || user.department === filterDepartment;
                            const matchesStatus = !filterStatus || user.status === filterStatus;
                            return matchesUsername && matchesDepartment && matchesStatus;
                        });
                        
                        totalUsers = usersData.length;
                        currentPage = 1; // 重置到第一页
                        renderUsersTable();
                    } else {
                        showMessage('搜索用户失败：' + (data.error || '未知错误'), false);
                    }
                })
                .catch(error => {
                    console.error('搜索用户时发生错误:', error);
                    showMessage('网络错误，请稍后重试', false);
                })
                .finally(() => {
                    isLoading = false;
                    searchButton.disabled = false;
                    searchButton.innerHTML = originalText;
                });
        }
        
        // 切换用户状态
        function toggleUserStatus(userId, username, currentStatus) {
            if (isLoading) return;
            
            const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
            const confirmMessage = `确定要${newStatus === 'active' ? '启用' : '禁用'}用户 ${username} 吗？`;
            
            if (confirm(confirmMessage)) {
                isLoading = true;
                
                apiRequest('{{ url_for('user.update_user_status') }}', 'POST', {
                    user_id: userId,
                    status: newStatus
                }, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(data => {
                    if (data.success) {
                        showMessage(data.message || '用户状态更新成功', true);
                        loadUsers(); // 重新加载用户列表
                    } else {
                        showMessage(data.error || '用户状态更新失败', false);
                    }
                })
                .catch(error => {
                    console.error('更新用户状态时发生错误:', error);
                    showMessage('网络错误，请稍后重试', false);
                })
                .finally(() => {
                    isLoading = false;
                });
            }
        }
        
        // 显示修改部门弹窗（使用layui）
        function showEditDepartmentModal(userId, username, name, department) {
            // 存储用户数据
            document.getElementById('editUserId').value = userId;
            document.getElementById('editUsername').value = username;
            
            // 获取部门选项
            const departments = JSON.parse(document.getElementById('departmentOptions').textContent);
            let departmentOptionsHtml = '';
            departments.forEach(dept => {
                const selected = dept === department ? 'selected' : '';
                departmentOptionsHtml += `<option value="${dept}" ${selected}>${dept}</option>`;
            });
            
            // 创建美化后的弹窗内容 - 参照初始化密码弹窗样式
            const content = `
                <div class="layui-text">
                    <!-- 表单主体 - 使用layUI风格 -->
                    <form class="layui-form" style="padding: 20px;">
                        <!-- 用户名列 -->
                        <div class="layui-form-item">
                            <label class="layui-form-label">用户名</label>
                            <div class="layui-input-block" style="max-width: 300px;">
                                <input type="text" value="${username}" readonly class="layui-input layui-disabled">
                            </div>
                        </div>
                        
                        <!-- 姓名列 -->
                        <div class="layui-form-item">
                            <label class="layui-form-label">姓名</label>
                            <div class="layui-input-block" style="max-width: 300px;">
                                <input type="text" id="layuiEditName" value="${name}" class="layui-input" lay-affix="clear">
                            </div>
                        </div>
                        
                        <!-- 部门选择 -->
                        <div class="layui-form-item">
                            <label class="layui-form-label">部门</label>
                            <div class="layui-input-block" style="max-width: 300px;">
                                <input type="text" id="layuiEditDepartment" value="${department}" class="layui-input">
                            </div>
                            <div class="layui-form-mid layui-word-aux" style="color: #666; margin-top: 5px;">输入新的部门名称后点击保存</div>
                        </div>
                    </form>
                </div>
            `;
            
            // 打开美化后的layui弹窗 - 参照初始化密码弹窗样式
            layer.open({
                type: 1,
                title: '<i class="fa fa-building-o"></i> 修改部门信息',
                area: ['500px', '380px'],
                offset: '10%',
                shade: 0.3,
                shadeClose: false,
                anim: 2,
                content: content,
                btn: ['保存修改', '取消'],
                btnAlign: 'c',
                btnClass: ['layui-btn layui-btn-normal', 'layui-btn layui-btn-primary'],
                skin: 'layui-layer-molv',
                success: function(layero, index) {
                    // 确保部门输入框在弹窗中可以正常交互
                    const inputElement = layero.find('#layuiEditDepartment')[0];
                    if (inputElement) {
                        // 移除可能阻止交互的属性
                        inputElement.removeAttribute('disabled');
                        inputElement.style.pointerEvents = 'auto';
                        // 聚焦到输入框
                        inputElement.focus();
                    }
                },
                btn1: function(index, layero) {
                    const newDepartment = document.getElementById('layuiEditDepartment').value;
                    // 获取修改后的姓名值
                    const newName = layero.find('input[type="text"]')[1].value;
                    saveDepartmentChanges(userId, username, newName, newDepartment, index);
                },
                btn2: function(index, layero) {
                    layer.close(index);
                    return false;
                }
            });
            

        }
        
        // 保存部门和姓名修改
        function saveDepartmentChanges(userId, username, newName, newDepartment, layerIndex) {
            fetch('{{ url_for('user.update_user_department') }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    user_id: userId,
                    name: newName,
                    department: newDepartment
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 关闭弹窗
                    layer.close(layerIndex);
                    
                    // 显示成功消息，带图标和动画效果
                    layer.msg(data.message || '部门信息更新成功', {
                        icon: 1,
                        anim: 0,
                        time: 2000,
                        end: function() {
                            // 重新加载用户列表
                            loadUsers();
                        }
                    });
                } else {
                    // 显示错误消息，带图标和动画效果
                    layer.msg(data.error || '部门信息更新失败', {
                        icon: 5,
                        anim: 6,
                        time: 2000
                    });
                }
            })
            .catch(error => {
                console.error('更新部门信息时发生错误:', error);
                
                // 显示网络错误消息，带图标和动画效果
                layer.msg('网络错误，请稍后重试', {
                    icon: 5,
                    anim: 6,
                    time: 2000
                });
            });
        }
        
        // 显示初始化密码弹窗（使用layui）
        function showResetPasswordModal(userId, username) {
            // 存储用户数据
            document.getElementById('resetUserId').value = userId;
            document.getElementById('resetUsername').value = username;
            
            // 打开layui确认弹窗
            layer.confirm(
                `<div class="layui-text">
                    <p>确定要初始化用户 <span style="font-weight: 500;">${username}</span> 的密码吗？</p>
                    <p style="color: #666; margin-top: 10px;">初始化后，密码将重置为默认值：<code class="layui-code">default123</code></p>
                 </div>`,
                {
                    title: '初始化密码',
                    btn: ['确定初始化', '取消'],
                    area: ['450px', '200px'],
                    btn1: function(index) {
                        confirmResetPassword(userId, username, index);
                    },
                    skin: 'layui-layer-molv'
                }
            );
        }
        
        // 确认初始化密码
        function confirmResetPassword(userId, username, layerIndex) {
            fetch('{{ url_for('user.reset_user_password') }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    user_id: userId,
                    username: username
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage(data.message || '密码初始化成功', true);
                    layer.close(layerIndex); // 关闭弹窗
                } else {
                    showMessage(data.error || '密码初始化失败', false);
                }
            })
            .catch(error => {
                console.error('初始化密码时发生错误:', error);
                showMessage('网络错误，请稍后重试', false);
            });
        }
    </script>
</body>
</html>