<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 用户列表
const userList = ref([])

// 加载状态
const loading = ref(false)

// 分页信息
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 搜索关键字
const searchKeyword = ref('')

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    // 实际应用中，这里应该调用API获取用户列表
    // 模拟获取用户列表
    setTimeout(() => {
      const mockUsers = []
      const total = 100
      const { currentPage, pageSize } = pagination.value
      const start = (currentPage - 1) * pageSize
      const end = Math.min(start + pageSize, total)
      
      for (let i = start + 1; i <= end; i++) {
        mockUsers.push({
          id: i,
          username: `user${i}`,
          nickname: `用户${i}`,
          email: `user${i}@example.com`,
          phone: `1380000${i.toString().padStart(4, '0')}`,
          gender: i % 3, // 0-未知，1-男，2-女
          role: i % 10 === 0 ? 1 : 0, // 0-普通用户，1-管理员
          status: i % 20 === 0 ? 0 : 1, // 0-禁用，1-正常
          createTime: new Date(Date.now() - i * 86400000).toISOString().split('T')[0]
        })
      }
      
      userList.value = mockUsers
      pagination.value.total = total
      loading.value = false
    }, 500)
  } catch (error) {
    ElMessage.error('获取用户列表失败')
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
  fetchUserList()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  pagination.value.currentPage = 1
  fetchUserList()
}

// 搜索用户
const searchUser = () => {
  pagination.value.currentPage = 1
  fetchUserList()
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''
  pagination.value.currentPage = 1
  fetchUserList()
}

// 查看用户详情
const viewUserDetail = (row) => {
  ElMessage.info(`查看用户详情：${row.username}`)
}

// 编辑用户
const editUser = (row) => {
  ElMessage.info(`编辑用户：${row.username}`)
}

// 删除用户
const deleteUser = (row) => {
  ElMessageBox.confirm(`确定要删除用户 ${row.username} 吗？此操作不可恢复`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际应用中，这里应该调用API删除用户
    userList.value = userList.value.filter(item => item.id !== row.id)
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 更新用户状态
const updateUserStatus = (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '启用' : '禁用'
  
  ElMessageBox.confirm(`确定要${statusText}用户 ${row.username} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际应用中，这里应该调用API更新用户状态
    const index = userList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      userList.value[index].status = newStatus
      ElMessage.success(`${statusText}成功`)
    }
  }).catch(() => {})
}

// 格式化性别
const formatGender = (gender) => {
  const genderMap = {
    0: '未知',
    1: '男',
    2: '女'
  }
  return genderMap[gender] || '未知'
}

// 格式化角色
const formatRole = (role) => {
  const roleMap = {
    0: '普通用户',
    1: '管理员'
  }
  return roleMap[role] || '未知'
}

// 格式化状态
const formatStatus = (status) => {
  const statusMap = {
    0: '禁用',
    1: '正常'
  }
  return statusMap[status] || '未知'
}

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

<template>
  <div class="admin-user-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入用户名/昵称/邮箱"
        clearable
        @clear="resetSearch"
        @keyup.enter="searchUser"
      >
        <template #append>
          <el-button @click="searchUser">
            <el-icon><search /></el-icon>
            搜索
          </el-button>
        </template>
      </el-input>
    </div>
    
    <!-- 用户列表 -->
    <el-table
      :data="userList"
      stripe
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      
      <el-table-column prop="username" label="用户名" width="120"></el-table-column>
      
      <el-table-column prop="nickname" label="昵称" width="120"></el-table-column>
      
      <el-table-column prop="email" label="邮箱" min-width="180"></el-table-column>
      
      <el-table-column prop="phone" label="手机号" width="120"></el-table-column>
      
      <el-table-column prop="gender" label="性别" width="80">
        <template #default="scope">
          {{ formatGender(scope.row.gender) }}
        </template>
      </el-table-column>
      
      <el-table-column prop="role" label="角色" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.role === 1 ? 'danger' : 'info'">
            {{ formatRole(scope.row.role) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ formatStatus(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="createTime" label="注册时间" width="120"></el-table-column>
      
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            @click="viewUserDetail(scope.row)"
          >
            查看
          </el-button>
          
          <el-button
            size="small"
            type="primary"
            @click="editUser(scope.row)"
          >
            编辑
          </el-button>
          
          <el-button
            size="small"
            :type="scope.row.status === 1 ? 'warning' : 'success'"
            @click="updateUserStatus(scope.row)"
          >
            {{ scope.row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          
          <el-button
            size="small"
            type="danger"
            @click="deleteUser(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style scoped>
.admin-user-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;
  max-width: 500px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table :deep(.el-button) {
  margin-left: 0;
  margin-right: 5px;
  padding: 4px 8px;
}
</style>
