<template>
  <div class="admin-users">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-icon">
        <el-icon><User /></el-icon>
      </div>
      <h2>用户管理</h2>
    </div>
    <div class="users-actions">
      <el-button type="primary" @click="showCreateDialog">创建用户</el-button>
    </div>
    <el-table :data="users" style="width: 100%" class="users-table">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="role" label="角色" width="120">
        <template #default="scope">
          <el-tag :type="getRoleType(scope.row.role?.name || scope.row.role)">{{ scope.row.role?.name || scope.row.role }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" type="primary" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建用户对话框 -->
    <el-dialog v-model="createDialogVisible" title="创建用户">
      <el-form :model="createForm" label-width="100px">
        <el-form-item label="用户名" required>
          <el-input v-model="createForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" required>
          <el-input v-model="createForm.email" type="email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码" required>
          <el-input v-model="createForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="确认密码" required>
          <el-input v-model="createForm.confirmPassword" type="password" placeholder="请再次输入密码" />
        </el-form-item>
        <el-form-item label="角色" required>
          <el-select v-model="createForm.role_id" placeholder="请选择角色">
            <el-option v-for="role in roles" :key="role.id" :label="role.name" :value="role.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createUser">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑用户">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="用户名" required>
          <el-input v-model="editForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" required>
          <el-input v-model="editForm.email" type="email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="editForm.password" type="password" placeholder="请输入密码（留空表示不修改）" />
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="editForm.confirmPassword" type="password" placeholder="请再次输入密码（留空表示不修改）" />
        </el-form-item>
        <el-form-item label="角色" required>
          <el-select v-model="editForm.role_id" placeholder="请选择角色">
            <el-option v-for="role in roles" :key="role.id" :label="role.name" :value="role.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { User } from '@element-plus/icons-vue'

const users = ref<any[]>([])
const loading = ref(false)
const error = ref('')

const createDialogVisible = ref(false)
const editDialogVisible = ref(false)

const roles = ref<any[]>([])
const createForm = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  role_id: ''
})

const editForm = ref({
  id: '',
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  role_id: ''
})

const formatDate = (dateString?: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

const getRoleType = (role?: string) => {
  switch (role) {
    case 'admin':
      return 'danger'
    case 'user':
      return 'primary'
    default:
      return 'default'
  }
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    const response = await axios.get('/api/users/roles')
    roles.value = response.data
  } catch (err) {
    console.error('获取角色列表失败:', err)
  }
}

// 获取用户列表
const fetchUsers = async () => {
  // 检查用户是否已登录
  const token = localStorage.getItem('token')
  if (!token) {
    console.log('用户未登录，跳过加载用户列表')
    error.value = '请先登录'
    return
  }

  loading.value = true
  error.value = ''
  try {
    const response = await axios.get('/api/users/')
    users.value = response.data.users
  } catch (err: any) {
    console.error('获取用户列表失败:', err)
    if (err.response?.status === 401 || err.response?.status === 403) {
      error.value = '权限不足，请重新登录'
    } else {
      error.value = '获取用户列表失败'
    }
  } finally {
    loading.value = false
  }
}

// 创建用户
const createUser = async () => {
  // 验证密码一致性
  if (createForm.value.password !== createForm.value.confirmPassword) {
    error.value = '两次输入的密码不一致'
    return
  }
  
  loading.value = true
  error.value = ''
  try {
    // 移除confirmPassword字段，因为后端API不需要
    const { confirmPassword, ...userData } = createForm.value
    await axios.post('/api/users/register', userData)
    await fetchUsers()
    createDialogVisible.value = false
  } catch (err) {
    console.error('创建用户失败:', err)
    error.value = '创建用户失败'
  } finally {
    loading.value = false
  }
}

// 更新用户
const updateUser = async () => {
  // 验证密码一致性（如果密码不为空）
  if (editForm.value.password !== '' && editForm.value.password !== editForm.value.confirmPassword) {
    error.value = '两次输入的密码不一致'
    return
  }
  
  loading.value = true
  error.value = ''
  try {
    const updateData = { ...editForm.value }
    // 移除不需要的字段
    if (!updateData.password) {
      delete updateData.password
    }
    delete updateData.confirmPassword
    await axios.put(`/api/users/${editForm.value.id}`, updateData)
    await fetchUsers()
    editDialogVisible.value = false
  } catch (err) {
    console.error('更新用户失败:', err)
    error.value = '更新用户失败'
  } finally {
    loading.value = false
  }
}

// 删除用户
const deleteUser = async (id: string) => {
  loading.value = true
  error.value = ''
  try {
    await axios.delete(`/api/users/${id}`)
    await fetchUsers()
  } catch (err) {
    console.error('删除用户失败:', err)
    error.value = '删除用户失败'
  } finally {
    loading.value = false
  }
}

const showCreateDialog = () => {
  createForm.value = {
    username: '',
    email: '',
    password: '',
    confirmPassword: '',
    role_id: roles.value.length > 0 ? roles.value.find(r => r.name === 'user')?.id || roles.value[0].id : ''
  }
  createDialogVisible.value = true
}

const showEditDialog = (user: any) => {
  editForm.value = {
    id: user.id,
    username: user.username,
    email: user.email,
    password: '',
    confirmPassword: '',
    role_id: user.role_id || user.role?.id || ''
  }
  editDialogVisible.value = true
}

// 组件挂载时获取用户列表和角色列表
onMounted(async () => {
  await fetchRoles()
  await fetchUsers()
})
</script>

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

.page-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.header-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  border-radius: 12px;
  background: linear-gradient(135deg, #909399 0%, #c0c4cc 100%);
  color: white;
  font-size: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.users-actions {
  margin-bottom: 20px;
}

.users-table {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .admin-users {
    padding: 10px;
  }

  .users-actions {
    margin-bottom: 10px;
  }

  .users-table {
    margin-top: 10px;
  }
}
</style>
