<template>
  <div class="page-wrapper">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <template #header>
        <div class="card-header-title">
          <el-icon><Search /></el-icon>
          <span>搜索条件</span>
        </div>
      </template>
      <el-form :model="query" inline>
        <el-form-item label="用户名">
          <el-input v-model="query.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="query.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="query.status" placeholder="全部" clearable style="width: 120px">
            <el-option label="全部" value="" />
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button-group>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-button-group>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增用户
      </el-button>
    </div>

    <!-- 表格 -->
    <el-card shadow="never">
      <el-table :data="tableData" border stripe v-loading="loading" style="width: 100%">
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="realName" label="真实姓名" width="100" />
        <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column prop="status" label="状态" width="90" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" effect="dark" size="small">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录时间" width="180">
          <template #default="{ row }">
            {{ row.lastLoginTime ? new Date(row.lastLoginTime).toLocaleString('zh-CN') : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" class-name="ops-col">
          <template #default="{ row }">
            <div class="actions">
              <el-button type="primary" size="small" plain @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" size="small" plain @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无用户数据" :image-size="100" />
        </template>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="query.page"
          v-model:page-size="query.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @current-change="fetchData"
          @size-change="fetchData"
        />
      </div>
    </el-card>

  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'

/** 用户类型 */
interface UserItem {
  id?: string
  username: string
  realName: string
  email: string
  phone: string
  post: string
  password?: string
  status: number
  lastLoginTime?: string
}

interface SystemItem {
  id: string
  systemName: string
}

interface RoleItem {
  id: string
  roleName: string
}

// --- 查询 ---
const query = reactive({
  page: 1,
  pageSize: 10,
  username: '',
  email: '',
  status: '' as string | number,
})

const tableData = ref<UserItem[]>([])
const total = ref(0)
const loading = ref(false)

async function fetchData() {
  loading.value = true
  try {
    const params: Record<string, unknown> = {
      page: query.page,
      pageSize: query.pageSize,
    }
    if (query.username) params.username = query.username
    if (query.email) params.email = query.email
    if (query.status !== '') params.status = query.status

    const res = await request.post('/zgapi/v1/admin/user/page', params)
    tableData.value = res.data?.records ?? []
    total.value = res.data?.total ?? 0
  } catch {
    // ignore
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  query.page = 1
  fetchData()
}

function handleReset() {
  query.username = ''
  query.email = ''
  query.status = ''
  query.page = 1
  fetchData()
}

// --- 新增/编辑（路由跳转到独立表单页）---
const router = useRouter()

function handleAdd() {
  router.push('/admin/user/form')
}

function handleEdit(row: UserItem) {
  router.push('/admin/user/form/' + row.id)
}

function handleDelete(row: UserItem) {
  ElMessageBox.confirm(`确认删除用户"${row.username}"吗？`, '删除确认', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(async () => {
    try {
      await request.delete(`/zgapi/v1/admin/user/${row.id}`)
      ElMessage.success('删除成功')
      fetchData()
    } catch {
      // ignore
    }
  }).catch(() => {})
}

// 初始化
fetchData()
</script>

<style scoped>
.page-wrapper {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-card {
  border-radius: var(--radius-lg);
}

.search-card :deep(.el-card__header) {
  padding: 14px 20px;
}

.card-header-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 14px;
  color: var(--text-primary);
}

.toolbar {
  display: flex;
  justify-content: flex-start;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: center;
}

@media (max-width: 768px) {
  .page-wrapper { gap: 10px; }
  .page-toolbar { flex-direction: column; gap: 10px; }
  .page-toolbar .el-select,
  .page-toolbar .el-input { width: 100% !important; }
}
</style>
