<template>
  <div class="public-users-page">
    <a-card>
      <template #title>公众用户</template>
      <template #extra>
        <span class="total-hint">共 {{ total }} 位注册用户</span>
      </template>

      <!-- 搜索 -->
      <a-form layout="inline" class="search-form">
        <a-form-item label="关键词">
          <a-input
            v-model:value="keyword"
            placeholder="用户名/昵称/手机号/城市"
            allow-clear
            @press-enter="handleSearch"
            style="width: 240px"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">搜索</a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <!-- 表格 -->
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'userInfo'">
            <div class="user-cell">
              <a-avatar :size="36" :src="record.avatar" class="user-avatar">
                {{ record.nickname?.charAt(0) }}
              </a-avatar>
              <div class="user-detail">
                <span class="user-nickname">{{ record.nickname }}</span>
                <span class="user-username">@{{ record.username }}</span>
              </div>
            </div>
          </template>
          <template v-else-if="column.key === 'phone'">
            {{ record.phone || '-' }}
          </template>
          <template v-else-if="column.key === 'city'">
            {{ record.city || '-' }}
          </template>
          <template v-else-if="column.key === 'children'">
            <a-tag v-if="record.childrenCount > 0" color="green">
              {{ record.childrenCount }} 个子女
            </a-tag>
            <span v-else class="text-muted">无</span>
          </template>
          <template v-else-if="column.key === 'registrations'">
            <a-tag v-if="record.registrationCount > 0" color="purple">
              {{ record.registrationCount }} 次报名
            </a-tag>
            <span v-else class="text-muted">无</span>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="record.status === 'enabled' ? 'green' : 'red'">
              {{ record.status === 'enabled' ? '正常' : '禁用' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'createTime'">
            {{ formatDate(record.createTime) }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-button type="link" size="small" @click="showDetail(record.id)">
              查看详情
            </a-button>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 详情抽屉 -->
    <a-drawer
      v-model:open="detailVisible"
      title="用户详情"
      :width="520"
    >
      <template v-if="detailLoading">
        <div style="text-align: center; padding: 40px"><a-spin /></div>
      </template>
      <template v-else-if="detailData">
        <!-- 基本信息 -->
        <a-descriptions title="基本信息" :column="2" bordered size="small">
          <a-descriptions-item label="昵称">{{ detailData.nickname }}</a-descriptions-item>
          <a-descriptions-item label="用户名">{{ detailData.username }}</a-descriptions-item>
          <a-descriptions-item label="手机号">{{ detailData.phone || '-' }}</a-descriptions-item>
          <a-descriptions-item label="城市">{{ detailData.city || '-' }}</a-descriptions-item>
          <a-descriptions-item label="性别">{{ genderLabel(detailData.gender) }}</a-descriptions-item>
          <a-descriptions-item label="注册时间">{{ formatDate(detailData.createTime) }}</a-descriptions-item>
        </a-descriptions>

        <!-- 子女信息 -->
        <div class="detail-section">
          <h4>子女信息（{{ detailData.children?.length || 0 }}）</h4>
          <a-empty v-if="!detailData.children?.length" description="暂无子女" />
          <div v-else class="children-list">
            <div v-for="child in detailData.children" :key="child.id" class="child-item">
              <span class="child-name">{{ child.name }}</span>
              <a-space>
                <a-tag v-if="child.grade">{{ child.grade }}</a-tag>
                <a-tag v-if="child.city">{{ child.city }}</a-tag>
                <a-tag v-if="child.schoolName" color="blue">{{ child.schoolName }}</a-tag>
              </a-space>
            </div>
          </div>
        </div>

        <!-- 报名记录 -->
        <div class="detail-section">
          <h4>报名记录（近20条）</h4>
          <a-empty v-if="!detailData.contestRegistrations?.length" description="暂无报名" />
          <div v-else class="reg-list">
            <div v-for="reg in detailData.contestRegistrations" :key="reg.id" class="reg-item">
              <span class="reg-contest">{{ reg.contest?.contestName }}</span>
              <div class="reg-meta">
                <a-tag :color="stateColor(reg.registrationState)" size="small">
                  {{ stateLabel(reg.registrationState) }}
                </a-tag>
                <span v-if="reg.participantType === 'child'" class="reg-child">
                  子女：{{ reg.child?.name }}
                </span>
                <span class="reg-time">{{ formatDate(reg.registrationTime) }}</span>
              </div>
            </div>
          </div>
        </div>
      </template>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import axios from 'axios'
import { getToken } from '@/utils/auth'
import dayjs from 'dayjs'

const dataSource = ref<any[]>([])
const loading = ref(false)
const total = ref(0)
const keyword = ref('')
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (t: number) => `共 ${t} 条`,
})

const detailVisible = ref(false)
const detailLoading = ref(false)
const detailData = ref<any>(null)

const columns = [
  { title: '用户信息', key: 'userInfo', width: 220 },
  { title: '手机号', key: 'phone', width: 130 },
  { title: '城市', key: 'city', width: 100 },
  { title: '子女', key: 'children', width: 100 },
  { title: '报名', key: 'registrations', width: 100 },
  { title: '状态', key: 'status', width: 80 },
  { title: '注册时间', key: 'createTime', width: 160 },
  { title: '操作', key: 'action', width: 100, fixed: 'right' as const },
]

const formatDate = (d: string) => d ? dayjs(d).format('YYYY-MM-DD HH:mm') : '-'
const genderLabel = (g: string) => g === 'male' ? '男' : g === 'female' ? '女' : '-'
const stateLabel = (s: string) => ({ pending: '待审核', passed: '已通过', rejected: '已拒绝', withdrawn: '已撤回' }[s] || s)
const stateColor = (s: string) => ({ pending: 'orange', passed: 'green', rejected: 'red', withdrawn: 'default' }[s] || 'default')

const api = axios.create({ baseURL: '/api' })
api.interceptors.request.use((config) => {
  const token = getToken()
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config
})

const fetchData = async () => {
  loading.value = true
  try {
    const res = await api.get('/public/users', {
      params: {
        page: pagination.current,
        pageSize: pagination.pageSize,
        keyword: keyword.value || undefined,
      },
    })
    const data = res.data?.data || res.data
    dataSource.value = data.list
    total.value = data.total
    pagination.total = data.total
  } catch {
    message.error('获取公众用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

const handleReset = () => {
  keyword.value = ''
  pagination.current = 1
  fetchData()
}

const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchData()
}

const showDetail = async (userId: number) => {
  detailVisible.value = true
  detailLoading.value = true
  try {
    const res = await api.get(`/public/users/${userId}`)
    detailData.value = res.data?.data || res.data
  } catch {
    message.error('获取用户详情失败')
  } finally {
    detailLoading.value = false
  }
}

onMounted(fetchData)
</script>

<style scoped lang="scss">
$primary: #6366f1;

.search-form {
  margin-bottom: 16px;
}

.total-hint {
  font-size: 13px;
  color: #9ca3af;
}

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

  .user-avatar {
    background: linear-gradient(135deg, $primary, #ec4899);
    font-weight: 700;
    flex-shrink: 0;
  }

  .user-detail {
    display: flex;
    flex-direction: column;
    min-width: 0;

    .user-nickname {
      font-weight: 600;
      color: #1e1b4b;
      font-size: 13px;
    }

    .user-username {
      font-size: 11px;
      color: #9ca3af;
    }
  }
}

.text-muted {
  color: #d1d5db;
  font-size: 12px;
}

// 详情抽屉
.detail-section {
  margin-top: 24px;

  h4 {
    font-size: 14px;
    font-weight: 600;
    color: #1e1b4b;
    margin: 0 0 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #f0ecf9;
  }
}

.children-list {
  .child-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 12px;
    background: #faf9fe;
    border-radius: 8px;
    margin-bottom: 8px;

    .child-name {
      font-weight: 600;
      color: #1e1b4b;
    }
  }
}

.reg-list {
  .reg-item {
    padding: 10px 12px;
    background: #faf9fe;
    border-radius: 8px;
    margin-bottom: 8px;

    .reg-contest {
      font-weight: 600;
      color: #1e1b4b;
      font-size: 13px;
      display: block;
      margin-bottom: 4px;
    }

    .reg-meta {
      display: flex;
      align-items: center;
      gap: 8px;

      .reg-child {
        font-size: 12px;
        color: #6b7280;
      }

      .reg-time {
        font-size: 11px;
        color: #9ca3af;
        margin-left: auto;
      }
    }
  }
}
</style>
