<template>
  <div class="user-list">
    <h1>用户管理</h1>
    <div class="actions">
      <router-link to="/user/add">
        <button class="add-btn">添加用户</button>
      </router-link>
    </div>
    <table class="user-table">
      <thead>
        <tr>
          <th>ID</th>
          <th>用户名</th>
          <th>昵称</th>
          <th>邮箱</th>
          <th>电话</th>
          <th>状态</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in users" :key="user.id">
          <td>{{ user.id }}</td>
          <td>{{ user.username }}</td>
          <td>{{ user.nickname }}</td>
          <td>{{ user.email }}</td>
          <td>{{ user.phone }}</td>
          <td>{{ user.status === 1 ? '启用' : '禁用' }}</td>
          <td>
            <button @click="editUser(user.id)">编辑</button>
            <button @click="deleteUser(user.id)" class="delete-btn">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getUsers, deleteUserById } from '../api/userApi'

const router = useRouter()
const users = ref([])

const loadUsers = async () => {
  try {
    const response = await getUsers()
    users.value = response.data
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

const editUser = (id) => {
  router.push(`/user/edit/${id}`)
}

const deleteUser = async (id) => {
  if (confirm('确定要删除该用户吗？')) {
    try {
      await deleteUserById(id)
      loadUsers()
    } catch (error) {
      console.error('删除用户失败:', error)
    }
  }
}

onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.user-list {
  padding: 2rem;
}

.actions {
  margin-bottom: 1rem;
  text-align: right;
}

.add-btn {
  background-color: #646cff;
  color: white;
}

.user-table {
  width: 100%;
  border-collapse: collapse;
}

.user-table th,
.user-table td {
  padding: 0.75rem;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.delete-btn {
  background-color: #ff4444;
  color: white;
}

button {
  margin-right: 0.5rem;
}
</style>
