<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { isAdmin as getIsAdmin } from '../utils/auth'

const users = ref([])
const showDialog = ref(false)
const editingUser = ref(null)
const isAdmin = getIsAdmin()

const userForm = reactive({
  username: '',
  role: 'user',
  is_active: true,
  password: '',
  confirm_password: ''
})

const ensureAdmin = () => {
  if (isAdmin) return true
  ElMessage.warning('普通用户仅支持查看与分析，不能修改账号信息')
  return false
}

const formatTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

const resetForm = () => {
  Object.assign(userForm, {
    username: '',
    role: 'user',
    is_active: true,
    password: '',
    confirm_password: ''
  })
  editingUser.value = null
}

const loadUsers = async () => {
  const response = await fetch('/api/users')
  const data = await response.json()
  if (data.status === 'success') {
    users.value = data.data || []
  } else {
    ElMessage.error(data.message || '用户列表加载失败')
  }
}

const openCreateDialog = () => {
  if (!ensureAdmin()) return
  resetForm()
  showDialog.value = true
}

const editUser = (row) => {
  if (!ensureAdmin()) return
  editingUser.value = row
  Object.assign(userForm, {
    username: row.username,
    role: row.role || 'user',
    is_active: row.is_active,
    password: '',
    confirm_password: ''
  })
  showDialog.value = true
}

const saveUser = async () => {
  if (!ensureAdmin()) return
  if (!userForm.username) {
    ElMessage.warning('请输入用户名')
    return
  }
  if (!editingUser.value && !userForm.password) {
    ElMessage.warning('请设置初始密码')
    return
  }
  if (userForm.password && userForm.password !== userForm.confirm_password) {
    ElMessage.warning('两次输入的密码不一致')
    return
  }

  const payload = {
    username: userForm.username,
    real_name: userForm.username,
    role: userForm.role,
    is_active: userForm.is_active,
    ...(userForm.password ? { password: userForm.password } : {})
  }

  const url = editingUser.value ? `/api/users/${editingUser.value.id}` : '/api/users'
  const method = editingUser.value ? 'PUT' : 'POST'
  const response = await fetch(url, {
    method,
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload)
  })
  const data = await response.json()

  if (data.status === 'success') {
    ElMessage.success(editingUser.value ? '用户已更新' : '用户已创建')
    showDialog.value = false
    resetForm()
    loadUsers()
  } else {
    ElMessage.error(data.message || '保存失败')
  }
}

const deleteUser = async (row) => {
  if (!ensureAdmin()) return
  try {
    await ElMessageBox.confirm(`确定删除用户“${row.username}”吗？`, '提示', { type: 'warning' })
    const response = await fetch(`/api/users/${row.id}`, { method: 'DELETE' })
    const data = await response.json()
    if (data.status === 'success') {
      ElMessage.success('用户已删除')
      loadUsers()
    } else {
      ElMessage.error(data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

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

<template>
  <div class="user-management">
    <div class="toolbar">
      <el-button type="primary" :disabled="!isAdmin" @click="openCreateDialog">
        <el-icon><Plus /></el-icon>
        新增用户
      </el-button>
    </div>

    <el-table :data="users" stripe>
      <el-table-column prop="username" label="账号" min-width="120" show-overflow-tooltip />
      <el-table-column prop="role" label="角色" width="100">
        <template #default="{ row }">
          <el-tag :type="row.role === 'admin' ? 'danger' : 'success'" size="small">
            {{ row.role === 'admin' ? '管理员' : '普通用户' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="is_active" label="状态" width="86">
        <template #default="{ row }">
          <el-tag :type="row.is_active ? 'success' : 'info'" size="small">
            {{ row.is_active ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="150">
        <template #default="{ row }">
          {{ formatTime(row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column prop="last_login" label="最后登录" width="150">
        <template #default="{ row }">
          {{ row.last_login ? formatTime(row.last_login) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="124">
        <template #default="{ row }">
          <el-button type="primary" text size="small" :disabled="!isAdmin" @click="editUser(row)">编辑</el-button>
          <el-button v-if="row.id !== 1" type="danger" text size="small" :disabled="!isAdmin" @click="deleteUser(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="showDialog" :title="editingUser ? '编辑用户' : '新增用户'" width="520px">
      <el-form :model="userForm" label-width="80px">
        <el-form-item label="账号">
          <el-input v-model="userForm.username" :disabled="!!editingUser" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="userForm.role" style="width: 100%;">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="userForm.is_active" />
        </el-form-item>
        <el-form-item :label="editingUser ? '新密码' : '密码'">
          <el-input v-model="userForm.password" type="password" show-password placeholder="留空表示不修改密码" />
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="userForm.confirm_password" type="password" show-password placeholder="再次输入密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" :disabled="!isAdmin" @click="saveUser">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user-management .toolbar {
  margin-bottom: 16px;
}
</style>
