<template>
  <div class="space-y-6">
    <!-- 主卡片 -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
      <div class="border-b border-gray-200 pb-4 mb-6">
        <div class="flex items-center justify-between">
          <h2 class="text-xl font-semibold text-gray-800 flex items-center gap-2">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
            </svg>
            用户列表
          </h2>
        </div>
      </div>

      <!-- 数据统计 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        <div class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg p-4 border border-blue-200">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-blue-600 mb-1">总用户数</p>
              <p class="text-2xl font-bold text-blue-700">{{ userList.length }}</p>
            </div>
            <div class="p-3 bg-blue-200 rounded-lg">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
              </svg>
            </div>
          </div>
        </div>
        <div class="bg-gradient-to-br from-green-50 to-green-100 rounded-lg p-4 border border-green-200">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-green-600 mb-1">已实名认证</p>
              <p class="text-2xl font-bold text-green-700">{{ authenticatedCount }}</p>
            </div>
            <div class="p-3 bg-green-200 rounded-lg">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
              </svg>
            </div>
          </div>
        </div>
        <div class="bg-gradient-to-br from-yellow-50 to-yellow-100 rounded-lg p-4 border border-yellow-200">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-yellow-600 mb-1">未完成认证</p>
              <p class="text-2xl font-bold text-yellow-700">{{ unauthenticatedCount }}</p>
            </div>
            <div class="p-3 bg-yellow-200 rounded-lg">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-yellow-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
              </svg>
            </div>
          </div>
        </div>
        <div class="bg-gradient-to-br from-purple-50 to-purple-100 rounded-lg p-4 border border-purple-200">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-purple-600 mb-1">启用状态</p>
              <p class="text-2xl font-bold text-purple-700">{{ activeCount }}</p>
            </div>
            <div class="p-3 bg-purple-200 rounded-lg">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-purple-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
              </svg>
            </div>
          </div>
        </div>
      </div>

      <!-- 用户列表表格 -->
      <el-table
        :data="userList"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column prop="id" label="用户ID" width="80" />
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column prop="jobNumber" label="工号" width="130" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column label="认证状态" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.userStatus === 2" type="success">已完成认证</el-tag>
            <el-tag v-else-if="row.userStatus === 1" type="warning">未完成认证</el-tag>
            <el-tag v-else-if="row.userStatus === 0" type="info">未找到账号</el-tag>
            <el-tag v-else type="info">未认证</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="令牌状态" width="120">
          <template #default="{ row }">
            <el-tag v-if="isTokenValid(row)" type="success">有效</el-tag>
            <el-tag v-else-if="row.userToken" type="danger">已过期</el-tag>
            <el-tag v-else type="info">无令牌</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="令牌过期时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.userTokenExpiresAt) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button v-if="row.jobNumber === jobNumber" size="small" type="primary" @click="handleGotoProfile">去认证</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="用户详情"
      width="700px"
    >
      <el-descriptions :column="1" border v-if="currentUser">
        <el-descriptions-item label="用户ID">
          {{ currentUser.id }}
        </el-descriptions-item>
        <el-descriptions-item label="手机号">
          {{ currentUser.phone }}
        </el-descriptions-item>
        <el-descriptions-item label="工号">
          {{ currentUser.jobNumber || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="姓名">
          {{ currentUser.name || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="认证状态">
          <el-tag v-if="currentUser.userStatus === 2" type="success">已完成认证</el-tag>
          <el-tag v-else-if="currentUser.userStatus === 1" type="warning">未完成认证</el-tag>
          <el-tag v-else-if="currentUser.userStatus === 0" type="info">未找到账号</el-tag>
          <el-tag v-else type="info">未认证</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="实名认证令牌">
          <el-text v-if="currentUser.userToken">{{ currentUser.userToken }}</el-text>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="令牌过期时间">
          {{ formatDateTime(currentUser.userTokenExpiresAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="令牌状态">
          <el-tag v-if="isTokenValid(currentUser)" type="success">有效</el-tag>
          <el-tag v-else-if="currentUser.userToken" type="danger">已过期</el-tag>
          <el-tag v-else type="info">无令牌</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentUser.status === 1 ? 'success' : 'danger'">
            {{ currentUser.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDateTime(currentUser.createTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ formatDateTime(currentUser.updateTime) }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
defineOptions({
  name: 'User'
})

import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Lock } from '@element-plus/icons-vue'
import {
  listUsers,
  deleteUser,
  getUserAuthUrl
} from '@/api/user'
import router from '@/router'

// 数据
const loading = ref(false)
const userList = ref([])

// 用户信息
const jobNumber = ref('')
const userInfo = ref(null)

// 加载用户信息
const loadUserInfo = () => {
  const storedUserInfo = localStorage.getItem('userInfo')
  if (storedUserInfo) {
    userInfo.value = JSON.parse(storedUserInfo)
    jobNumber.value = userInfo.value.jobNumber || '未知'
  }
}

// 对话框
const detailDialogVisible = ref(false)

const handleGotoProfile = () => {
  router.push({ path: '/profile' })
}

// 计算属性
const authenticatedCount = computed(() => {
  return userList.value.filter(item => item.userStatus === 2).length
})

const unauthenticatedCount = computed(() => {
  return userList.value.filter(item => !item.userStatus || item.userStatus !== 2).length
})

const activeCount = computed(() => {
  return userList.value.filter(item => item.status === 1).length
})

// 方法
const loadUserList = async () => {
  loading.value = true
  try {
    const res = await listUsers()
    userList.value = res.data || []
  } catch (error) {
    console.error('加载用户列表失败：', error)
  } finally {
    loading.value = false
  }
}

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

const isTokenValid = (user) => {
  if (!user || !user.userToken || !user.userTokenExpiresAt) {
    return false
  }
  if (user.userStatus !== 2) {
    return false
  }
  const now = new Date()
  const expiresAt = new Date(user.userTokenExpiresAt)
  return expiresAt > now
}

// 生命周期
onMounted(() => {
  loadUserList()
  loadUserInfo()
})
</script>

<style scoped>
/* 使用Tailwind CSS类替代自定义样式 */
</style>
