<template>
  <div class="users-page">
    <div class="table-card">
      <el-table :data="paginatedUsers">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="row.role === 'admin' ? 'danger' : row.role === 'supplier' ? 'warning' : 'info'">
              {{ row.role === 'admin' ? '管理员' : row.role === 'supplier' ? '供应商' : '用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="purchase_credits" label="积分" width="100" />
        <el-table-column prop="is_active" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'" size="small">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="注册时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="openEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)" :disabled="row.role === 'admin'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrap">
        <el-pagination
          v-model:current-page="page"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <el-dialog v-model="editVisible" title="编辑用户" width="480px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="editForm.role">
            <el-option label="用户" value="user" />
            <el-option label="供应商" value="supplier" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="editForm.is_active" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEdit" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

const users = ref<any[]>([])
const page = ref(1)
const pageSize = 20
const total = computed(() => users.value.length)
const paginatedUsers = computed(() => {
  const start = (page.value - 1) * pageSize
  return users.value.slice(start, start + pageSize)
})

const editVisible = ref(false)
const editForm = ref<any>({})
const saving = ref(false)

function handlePageChange() {
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

async function fetchUsers() {
  try {
    const res: any = await adminApi.getUsers()
    users.value = res.data || []
  } catch {
    ElMessage.error('获取用户列表失败')
  }
}

onMounted(fetchUsers)

function formatDate(date: string) {
  if (!date) return '-'
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

function openEdit(row: any) {
  editForm.value = { ...row }
  editVisible.value = true
}

async function handleEdit() {
  saving.value = true
  try {
    await adminApi.updateUser(editForm.value.id, {
      username: editForm.value.username,
      email: editForm.value.email,
      role: editForm.value.role,
      is_active: editForm.value.is_active,
    })
    ElMessage.success('更新成功')
    editVisible.value = false
    fetchUsers()
  } catch {
    ElMessage.error('更新失败')
  } finally {
    saving.value = false
  }
}

async function handleDelete(row: any) {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', { type: 'warning' })
    await adminApi.deleteUser(row.id)
    ElMessage.success('删除成功')
    fetchUsers()
  } catch {}
}
</script>

<style scoped lang="scss">
.users-page { padding: 0; }
.table-card { background: #2d2d44; border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 12px; padding: 20px; }

.pagination-wrap {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.pagination-wrap :deep(.el-pagination) {
  --el-pagination-bg-color: rgba(255, 255, 255, 0.06);
  --el-pagination-text-color: rgba(255, 255, 255, 0.6);
  --el-pagination-button-disabled-bg-color: rgba(255, 255, 255, 0.04);
  --el-pagination-button-bg-color: rgba(255, 255, 255, 0.06);
  --el-pagination-hover-color: #4e6ef2;
}

.pagination-wrap :deep(.el-pagination .el-pager li) {
  background: rgba(255, 255, 255, 0.06);
  color: rgba(255, 255, 255, 0.6);
  border-radius: 6px;
  margin: 0 4px;
}

.pagination-wrap :deep(.el-pagination .el-pager li:hover),
.pagination-wrap :deep(.el-pagination .el-pager li.is-active) {
  background: #4e6ef2;
  color: #fff;
}

.pagination-wrap :deep(.el-pagination .btn-prev),
.pagination-wrap :deep(.el-pagination .btn-next) {
  background: rgba(255, 255, 255, 0.06);
  color: rgba(255, 255, 255, 0.6);
  border-radius: 6px;
}

.pagination-wrap :deep(.el-pagination .btn-prev:hover),
.pagination-wrap :deep(.el-pagination .btn-next:hover) {
  background: rgba(78, 110, 242, 0.2);
  color: #4e6ef2;
}

.pagination-wrap :deep(.el-pagination__total) {
  color: rgba(255, 255, 255, 0.5);
}
</style>
