<template>
  <div class="user-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="openDialog()">新增用户</el-button>
        </div>
      </template>

      <el-table :data="list" v-loading="loading" stripe>
        <el-table-column label="ID" width="200">
          <template #default="{ row }">{{ row.id || row._id }}</template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column label="角色" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.role_id === 9527" type="danger" size="small">超级管理员</el-tag>
            <el-tag v-else-if="row.role === 'admin'" type="warning" size="small">管理员</el-tag>
            <el-tag v-else type="info" size="small">普通用户</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="is_beta" label="Beta" width="80">
          <template #default="{ row }">
            <el-tag v-if="row.is_beta" type="success" size="small">是</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="llm" label="LLM" width="80" />
        <el-table-column prop="last_login" label="最后登录" width="120" />
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="openDialog(row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        @current-change="fetchList"
        @size-change="fetchList"
        style="margin-top: 16px"
      />
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="editId ? '编辑用户' : '新增用户'" width="500px" @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" :disabled="!!editId" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码" prop="password" :rules="editId ? [] : [{ required: true, message: '请输入密码' }]">
          <el-input v-model="form.password" type="password" :placeholder="editId ? '不修改请留空' : '请输入密码'" show-password />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择">
            <el-option label="用户" value="user" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色ID" prop="role_id">
          <el-select v-model="form.role_id" placeholder="请选择">
            <el-option label="普通用户" :value="1" />
            <el-option label="超级管理员" :value="9527" />
          </el-select>
        </el-form-item>
        <el-form-item label="Beta用户" prop="is_beta">
          <el-switch v-model="form.is_beta" />
        </el-form-item>
        <el-form-item label="LLM" prop="llm">
          <el-input v-model="form.llm" placeholder="如 m1, qwen" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUsers, createUser, updateUser, deleteUser } from '../../api/admin'

const list = ref([])
const loading = ref(false)
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)

const fetchList = async () => {
  loading.value = true
  try {
    const res = await getUsers({ page: page.value, page_size: pageSize.value })
    list.value = res.list || []
    total.value = res.total || 0
  } catch (e) {
    ElMessage.error(e.message)
  } finally {
    loading.value = false
  }
}

const dialogVisible = ref(false)
const editId = ref('')
const submitting = ref(false)
const formRef = ref(null)
const form = reactive({
  username: '',
  email: '',
  password: '',
  role: 'user',
  role_id: 1,
  is_beta: false,
  llm: ''
})

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }]
}

const openDialog = (row) => {
  editId.value = row ? (row.id || row._id) : ''
  if (row) {
    form.username = row.username
    form.email = row.email
    form.role = row.role || 'user'
    form.role_id = row.role_id ?? 1
    form.is_beta = row.is_beta || false
    form.llm = row.llm || ''
    form.password = ''
  } else {
    resetForm()
  }
  dialogVisible.value = true
}

const resetForm = () => {
  form.username = ''
  form.email = ''
  form.password = ''
  form.role = 'user'
  form.role_id = 1
  form.is_beta = false
  form.llm = ''
  formRef.value?.resetFields()
}

const submitForm = async () => {
  await formRef.value?.validate()
  submitting.value = true
  try {
    if (editId.value) {
      const data = { username: form.username, email: form.email, role: form.role, role_id: form.role_id, is_beta: form.is_beta, llm: form.llm || undefined }
      if (form.password) data.password = form.password
      await updateUser(editId.value, data)
      ElMessage.success('更新成功')
    } else {
      await createUser({
        username: form.username,
        email: form.email,
        password: form.password,
        role: form.role,
        role_id: form.role_id,
        is_beta: form.is_beta,
        llm: form.llm || undefined
      })
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    fetchList()
  } catch (e) {
    ElMessage.error(e.message)
  } finally {
    submitting.value = false
  }
}

const handleDelete = async (row) => {
  await ElMessageBox.confirm(`确定删除用户 ${row.username}？`, '提示', {
    type: 'warning'
  })
  try {
    await deleteUser(row.id || row._id)
    ElMessage.success('删除成功')
    fetchList()
  } catch (e) {
    ElMessage.error(e.message)
  }
}

onMounted(fetchList)
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
