<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminApi } from '@/api/admin'
import type { AdminUser } from '@/types'
import { UserStatus, AdminRole } from '@/types'

const router = useRouter()

const loading = ref(false)
const users = ref<AdminUser[]>([])
const total = ref(0)
const query = reactive({
  page: 1,
  pageSize: 20,
  search: '',
  status: undefined as UserStatus | undefined
})

onMounted(() => {
  fetchUsers()
})

async function fetchUsers() {
  loading.value = true
  try {
    const response = await adminApi.getUsers(query)
    if (response.success && response.data) {
      users.value = response.data.items
      total.value = response.data.total
    }
  } finally {
    loading.value = false
  }
}

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

function handlePageChange(page: number) {
  query.page = page
  fetchUsers()
}

function handleViewDetail(user: AdminUser) {
  router.push(`/users/${user.id}`)
}

function handleViewBookmarks(user: AdminUser) {
  router.push(`/users/${user.id}/bookmarks`)
}

async function handleToggleStatus(user: AdminUser) {
  const disabled = user.status === UserStatus.Normal
  const action = disabled ? '禁用' : '启用'

  try {
    await ElMessageBox.confirm(
      `确定要${action}用户 "${user.userName}" 吗？`,
      `${action}确认`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    const response = await adminApi.setUserStatus(user.id, disabled)
    if (response.success) {
      ElMessage.success(`${action}成功`)
      fetchUsers()
    }
  } catch {
    // 取消
  }
}

function formatDate(dateStr?: string) {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

function getRoleText(role: AdminRole) {
  const map = {
    [AdminRole.User]: '普通用户',
    [AdminRole.Admin]: '管理员',
    [AdminRole.SuperAdmin]: '超级管理员'
  }
  return map[role] || '未知'
}

function getRoleType(role: AdminRole) {
  const map = {
    [AdminRole.User]: 'info',
    [AdminRole.Admin]: 'warning',
    [AdminRole.SuperAdmin]: 'danger'
  }
  return map[role] || 'info'
}
</script>

<template>
  <div class="user-list">
    <div class="page-header">
      <h2>用户管理</h2>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="query.search"
        placeholder="搜索用户邮箱或用户名"
        clearable
        style="width: 300px"
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-select
        v-model="query.status"
        placeholder="用户状态"
        clearable
        style="width: 150px"
        @change="handleSearch"
      >
        <el-option label="正常" :value="UserStatus.Normal" />
        <el-option label="禁用" :value="UserStatus.Disabled" />
      </el-select>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
    </div>

    <!-- 用户列表 -->
    <el-table :data="users" v-loading="loading" class="user-table">
      <el-table-column label="用户" min-width="200">
        <template #default="{ row }">
          <div class="user-cell">
            <el-avatar :size="40" :src="row.avatar">
              {{ row.userName?.[0] || 'U' }}
            </el-avatar>
            <div class="user-info">
              <div class="user-name">{{ row.userName }}</div>
              <div class="user-email">{{ row.email }}</div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="角色" width="120">
        <template #default="{ row }">
          <el-tag :type="getRoleType(row.role)" size="small">
            {{ getRoleText(row.role) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === UserStatus.Normal ? 'success' : 'danger'" size="small">
            {{ row.status === UserStatus.Normal ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="设备数" width="80" align="center">
        <template #default="{ row }">
          {{ row.deviceCount }}
        </template>
      </el-table-column>

      <el-table-column label="书签数" width="80" align="center">
        <template #default="{ row }">
          {{ row.bookmarkCount }}
        </template>
      </el-table-column>

      <el-table-column label="注册时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>

      <el-table-column label="最后登录" width="180">
        <template #default="{ row }">
          {{ formatDate(row.lastLoginAt) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="220" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleViewDetail(row)">
            详情
          </el-button>
          <el-button size="small" @click="handleViewBookmarks(row)">
            书签
          </el-button>
          <el-button
            size="small"
            :type="row.status === UserStatus.Normal ? 'danger' : 'success'"
            @click="handleToggleStatus(row)"
          >
            {{ row.status === UserStatus.Normal ? '禁用' : '启用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="query.page"
        :page-size="query.pageSize"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.user-list {
  .page-header {
    margin-bottom: 20px;

    h2 {
      font-size: 20px;
      font-weight: 600;
      color: #333;
    }
  }

  .search-bar {
    display: flex;
    gap: 12px;
    margin-bottom: 20px;
    background: #fff;
    padding: 16px;
    border-radius: 8px;
  }

  .user-table {
    background: #fff;
    border-radius: 8px;
  }

  .user-cell {
    display: flex;
    align-items: center;
    gap: 12px;

    .user-info {
      .user-name {
        font-weight: 500;
        color: #333;
      }

      .user-email {
        font-size: 12px;
        color: #999;
      }
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

