<template>
  <div>
    <div style="display:flex;justify-content:space-between;margin-bottom:16px">
      <h2>用户管理</h2>
      <el-button type="primary" @click="openDialog()">新增管理员</el-button>
    </div>
    <el-table :data="users" v-loading="loading" border>
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column label="角色">
        <template #default="{ row }">
          <el-tag :type="row.role==='superadmin'?'danger':row.role==='admin'?'warning':'info'">
            {{ { superadmin:'超管', admin:'公司管理员', seeker:'求职者' }[row.role] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="所属公司">
        <template #default="{ row }">{{ row.organization ? orgs.find(o=>o.id===row.organization)?.name : '-' }}</template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="{ row }"><el-tag :type="row.is_active?'success':'danger'">{{ row.is_active?'正常':'停用' }}</el-tag></template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }"><el-button size="small" @click="openDialog(row)">编辑</el-button></template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 16px; text-align: right;">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="handlePageChange"
        layout="total, prev, pager, next, jumper"
      />
    </div>

    <el-dialog v-model="dialogVisible" :title="editing ? '编辑用户' : '新增管理员'" width="480px">
      <el-form :model="form" label-width="90px">
        <el-form-item label="用户名"><el-input v-model="form.username" /></el-form-item>
        <el-form-item label="邮箱"><el-input v-model="form.email" /></el-form-item>
        <el-form-item label="手机号"><el-input v-model="form.phone" /></el-form-item>
        <el-form-item label="角色">
          <el-select v-model="form.role">
            <el-option value="admin" label="公司管理员" />
            <el-option value="superadmin" label="超级管理员" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属公司" v-if="form.role==='admin'">
          <el-select v-model="form.organization" clearable>
            <el-option v-for="o in orgs" :key="o.id" :value="o.id" :label="o.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="密码" v-if="!editing"><el-input v-model="form.password" type="password" /></el-form-item>
        <el-form-item label="状态"><el-switch v-model="form.is_active" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="save" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { manageOrganizations } from '@/api/organizations'
import client from '@/api/client'
import { ElMessage } from 'element-plus'

const users = ref([])
const orgs = ref([])
const dialogVisible = ref(false)
const editing = ref(null)
const saving = ref(false)
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const form = reactive({ username: '', email: '', phone: '', role: 'admin', organization: null, password: '', is_active: true })

const fetchUsers = async (page = 1) => {
  loading.value = true
  try {
    const { data } = await client.get('/auth/users/', { params: { page } })
    users.value = data.results
    total.value = data.count
    currentPage.value = page
  } catch (error) {
    ElMessage.error('加载用户列表失败，请重试')
  } finally {
    loading.value = false
  }
}
const fetchOrgs = async () => { const { data } = await manageOrganizations(); orgs.value = data.results }

function handlePageChange(newPage) {
  fetchUsers(newPage)
}

function openDialog(user = null) {
  editing.value = user
  if (user) Object.assign(form, user)
  else Object.assign(form, { username: '', email: '', phone: '', role: 'admin', organization: null, password: '', is_active: true })
  dialogVisible.value = true
}

async function save() {
  saving.value = true
  try {
    if (editing.value) await client.patch(`/auth/users/${editing.value.id}/`, form)
    else await client.post('/auth/users/', form)
    ElMessage.success('保存成功')
    dialogVisible.value = false
    fetchUsers(1)
  } catch { ElMessage.error('保存失败') } finally { saving.value = false }
}
onMounted(() => { fetchUsers(); fetchOrgs() })
</script>
