<template>
  <div>
    <div class="page-header">
      <h1>账号管理</h1>
      <p>管理系统用户账号，分配角色权限</p>
    </div>

    <div class="content-card">
      <div class="card-title">
        <span>用户列表</span>
        <el-button type="primary" @click="showDialog()">+ 新增用户</el-button>
      </div>
      <el-table :data="users" stripe v-loading="loading">
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="realname" label="姓名" width="120" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="roleType(row.role)" effect="dark" round>{{ roleLabel(row.role) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" effect="dark" round>
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" min-width="200">
          <template #default="{ row }">
            <el-button size="small" @click="showDialog(row)">编辑</el-button>
            <el-button size="small" :type="row.status === 1 ? 'warning' : 'success'"
              @click="toggleStatus(row)">{{ row.status === 1 ? '禁用' : '启用' }}</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- Dialog -->
    <el-dialog v-model="dialogVisible" :title="editingId ? '编辑用户' : '新增用户'" width="460px" destroy-on-close>
      <el-form :model="form" :rules="computedRules" ref="formRef" label-width="80px">
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="选择角色" style="width: 100%" @change="handleRoleChange">
            <el-option label="管理员" value="admin" />
            <el-option label="销售" value="sales" />
            <el-option label="研发" value="rd" />
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="realname">
          <el-input v-model="form.realname" placeholder="真实姓名" />
        </el-form-item>
        <template v-if="form.role !== 'sales'">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" :disabled="!!editingId" placeholder="登录用户名" />
          </el-form-item>
          <el-form-item label="密码" :prop="editingId ? '' : 'password'">
            <el-input v-model="form.password" type="password" show-password
              :placeholder="editingId ? '留空则不修改' : '请输入密码'" />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminApi } from '../../api'

const users = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const saving = ref(false)
const editingId = ref(null)
const formRef = ref(null)

const form = reactive({ username: '', password: '', realname: '', role: '' })
const computedRules = computed(() => {
  return {
    username: form.role === 'sales' ? [] : [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: form.role === 'sales' ? [] : [{ required: true, message: '请输入密码', trigger: 'blur' }],
    realname: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    role: [{ required: true, message: '请选择角色', trigger: 'change' }]
  }
})

function handleRoleChange() {
  if (formRef.value) formRef.value.clearValidate(['username', 'password'])
}

const roleLabel = (r) => ({ admin: '管理员', sales: '销售', rd: '研发' }[r] || r)
const roleType = (r) => ({ admin: 'danger', sales: 'warning', rd: '' }[r] || 'info')

async function loadUsers() {
  loading.value = true
  try {
    const res = await adminApi.getUsers()
    users.value = res.data
  } finally { loading.value = false }
}

function showDialog(row) {
  editingId.value = row?.id || null
  form.username = row?.username || ''
  form.password = ''
  form.realname = row?.realname || ''
  form.role = row?.role || ''
  dialogVisible.value = true
}

async function handleSave() {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return
  saving.value = true
  try {
    if (editingId.value) {
      const updateData = { realname: form.realname, role: form.role }
      if (form.password) updateData.password = form.password
      await adminApi.updateUser(editingId.value, updateData)
      ElMessage.success('更新成功')
    } else {
      await adminApi.createUser(form)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    loadUsers()
  } finally { saving.value = false }
}

async function toggleStatus(row) {
  await adminApi.updateUser(row.id, { status: row.status === 1 ? 0 : 1 })
  ElMessage.success('状态已更新')
  loadUsers()
}

async function handleDelete(row) {
  await ElMessageBox.confirm(`确定删除用户 "${row.realname}" 吗？`, '确认删除', { type: 'warning' })
  await adminApi.deleteUser(row.id)
  ElMessage.success('删除成功')
  loadUsers()
}

onMounted(loadUsers)
</script>
