<template>
  <div class="user-edit">
    <h1>编辑用户</h1>
    <form @submit.prevent="submitForm">
      <div class="form-group">
        <label for="username">用户名</label>
        <input type="text" id="username" v-model="userForm.username" required>
      </div>
      <div class="form-group">
        <label for="password">密码（不修改请留空）</label>
        <input type="password" id="password" v-model="userForm.password">
      </div>
      <div class="form-group">
        <label for="nickname">昵称</label>
        <input type="text" id="nickname" v-model="userForm.nickname" required>
      </div>
      <div class="form-group">
        <label for="email">邮箱</label>
        <input type="email" id="email" v-model="userForm.email">
      </div>
      <div class="form-group">
        <label for="phone">电话</label>
        <input type="text" id="phone" v-model="userForm.phone">
      </div>
      <div class="form-group">
        <label for="status">状态</label>
        <select id="status" v-model="userForm.status">
          <option value="1">启用</option>
          <option value="0">禁用</option>
        </select>
      </div>
      <div class="form-actions">
        <button type="submit">保存</button>
        <button type="button" @click="router.back()">取消</button>
      </div>
    </form>
  </div>
</template>

<script setup>
import { reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getUserById, updateUser } from '../api/userApi'

const router = useRouter()
const route = useRoute()
const userForm = reactive({
  id: null,
  username: '',
  password: '',
  nickname: '',
  email: '',
  phone: '',
  status: 1
})

const loadUser = async () => {
  const id = route.params.id
  try {
    const response = await getUserById(id)
    const user = response.data
    Object.assign(userForm, user)
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

const submitForm = async () => {
  try {
    // 如果密码为空，不更新密码
    const updateData = { ...userForm }
    if (!updateData.password) {
      delete updateData.password
    }
    await updateUser(updateData)
    router.push('/users')
  } catch (error) {
    console.error('更新用户失败:', error)
  }
}

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

<style scoped>
.user-edit {
  padding: 2rem;
  max-width: 600px;
  margin: 0 auto;
}

.form-group {
  margin-bottom: 1rem;
  text-align: left;
}

label {
  display: block;
  margin-bottom: 0.5rem;
}

input, select {
  width: 100%;
  padding: 0.5rem;
  box-sizing: border-box;
}

.form-actions {
  margin-top: 2rem;
  display: flex;
  gap: 1rem;
  justify-content: center;
}
</style>
