// 用户管理模块

class UsersManager {
  constructor(options = {}) {
    this.apiBaseUrl = options.apiBaseUrl || 'http://localhost:3000';
    this.tbody = options.tbody || null;
    
    this.users = [];
    
    this.init();
  }

  init() {
    this.bindEvents();
    this.loadUsers();
  }

  bindEvents() {
    // 刷新按钮
    const refreshBtn = document.getElementById('refreshUsersBtn');
    if (refreshBtn) {
      refreshBtn.addEventListener('click', () => {
        this.loadUsers();
      });
    }

    // 编辑用户表单
    const editForm = document.getElementById('editUserForm');
    if (editForm) {
      editForm.addEventListener('submit', (e) => this.handleEditUser(e));
    }

    // 关闭编辑弹窗
    const closeEditModal = document.getElementById('closeEditUserModal');
    if (closeEditModal) {
      closeEditModal.addEventListener('click', () => {
        document.getElementById('editUserModal').style.display = 'none';
      });
    }

    const cancelEdit = document.getElementById('cancelEditUser');
    if (cancelEdit) {
      cancelEdit.addEventListener('click', () => {
        document.getElementById('editUserModal').style.display = 'none';
      });
    }
  }

  // 加载用户列表
  async loadUsers() {
    if (!this.tbody) return;
    
    this.tbody.innerHTML = '<tr><td colspan="6" class="loading-text">加载中...</td></tr>';

    try {
      const apiUrl = `${this.apiBaseUrl}/api/admin/users`;
      console.log('[UsersManager] 请求用户列表，URL:', apiUrl);
      
      const response = await fetch(apiUrl);
      console.log('[UsersManager] 响应状态:', response.status, response.statusText);
      
      if (!response.ok) {
        throw new Error(`加载用户列表失败: ${response.status} ${response.statusText}`);
      }
      
      const result = await response.json();
      console.log('[UsersManager] 获取到的数据:', result);
      
      if (result.success && result.users) {
        this.users = result.users;
        console.log('[UsersManager] 用户数量:', this.users.length);
        this.renderUsers();
      } else {
        console.warn('[UsersManager] 返回数据格式不正确或没有用户:', result);
        this.tbody.innerHTML = '<tr><td colspan="6" class="loading-text">暂无用户数据</td></tr>';
      }
    } catch (error) {
      console.error('[UsersManager] 加载用户失败:', error);
      const errorMessage = error.message || '未知错误';
      this.tbody.innerHTML = `<tr><td colspan="6" class="loading-text" style="color: #ef4444;">加载失败: ${errorMessage}<br>请确保服务器正在运行 (http://localhost:3000)</td></tr>`;
    }
  }

  // 渲染用户列表
  renderUsers() {
    if (!this.tbody) return;
    
    if (this.users.length === 0) {
      this.tbody.innerHTML = '<tr><td colspan="6" class="loading-text">暂无用户数据</td></tr>';
      return;
    }

    this.tbody.innerHTML = this.users.map(user => `
      <tr>
        <td>${user.id}</td>
        <td>${user.username}</td>
        <td>${user.phone || '-'}</td>
        <td>${user.points || 0}</td>
        <td>${user.created_at ? new Date(user.created_at).toLocaleString('zh-CN') : '-'}</td>
        <td>
          <div class="action-buttons">
            <button class="btn-edit" onclick="window.usersManagerInstance.editUser(${user.id})">编辑</button>
          </div>
        </td>
      </tr>
    `).join('');
  }

  // 编辑用户
  editUser(userId) {
    const user = this.users.find(u => u.id === userId);
    if (!user) return;

    document.getElementById('editUserId').value = user.id;
    document.getElementById('editUsername').value = user.username;
    document.getElementById('editPhone').value = user.phone || '';
    document.getElementById('editPoints').value = user.points || 0;
    document.getElementById('editUserModal').style.display = 'flex';
  }

  // 处理编辑用户
  async handleEditUser(e) {
    e.preventDefault();
    
    const userId = document.getElementById('editUserId').value;
    const username = document.getElementById('editUsername').value;
    const phone = document.getElementById('editPhone').value;
    const points = parseInt(document.getElementById('editPoints').value);

    try {
      const response = await fetch(`${this.apiBaseUrl}/api/admin/users/update`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          id: userId,
          username: username,
          phone: phone,
          points: points
        })
      });

      const result = await response.json();
      
      if (result.success) {
        this.showSuccess('修改成功');
        document.getElementById('editUserModal').style.display = 'none';
        this.loadUsers();
      } else {
        this.showError('修改失败: ' + (result.message || '未知错误'));
      }
    } catch (error) {
      console.error('[UsersManager] 修改用户失败:', error);
      this.showError('修改失败，请稍后重试');
    }
  }

  // 显示错误/成功消息
  showError(message) {
    if (window.showCustomAlert) {
      window.showCustomAlert(message);
    } else {
      console.error('[UsersManager] 错误:', message);
    }
  }

  showSuccess(message) {
    if (window.showCustomAlert) {
      window.showCustomAlert(message, 'success');
    } else {
      console.log('[UsersManager] 成功:', message);
    }
  }
}

// 导出
if (typeof module !== 'undefined' && module.exports) {
  module.exports = UsersManager;
} else {
  window.UsersManager = UsersManager;
}

