<template>
  <div class="users-page">
    <!-- 标题 -->
    <a-card class="title-card">
      <template #title>用户管理</template>
    </a-card>

    <!-- 统计卡片 -->
    <div class="stats-row">
      <div
        v-for="item in statsItems"
        :key="item.type"
        :class="['stat-card', { active: activeType === item.type }]"
        @click="handleStatClick(item.type)"
      >
        <div class="stat-icon" :style="{ background: item.bgColor }">
          <component :is="item.icon" :style="{ color: item.color }" />
        </div>
        <div class="stat-info">
          <span class="stat-count">{{ item.count }}</span>
          <span class="stat-label">{{ item.label }}</span>
        </div>
      </div>
    </div>

    <!-- 筛选栏 -->
    <div class="filter-bar">
      <a-form layout="inline" @finish="handleSearch">
        <a-form-item label="关键词">
          <a-input
            v-model:value="searchParams.keyword"
            placeholder="用户名 / 昵称 / 手机号"
            allow-clear
            style="width: 200px"
            @press-enter="handleSearch"
          />
        </a-form-item>
        <a-form-item v-if="!activeType || activeType === 'org'" label="所属机构">
          <a-select
            v-model:value="searchParams.filterTenantId"
            placeholder="全部机构"
            allow-clear
            show-search
            :filter-option="filterTenantOption"
            style="width: 180px"
            :options="tenantOptions"
          />
        </a-form-item>
        <a-form-item label="用户来源">
          <a-select
            v-model:value="searchParams.userSource"
            placeholder="全部"
            allow-clear
            style="width: 130px"
          >
            <a-select-option value="admin_created">管理创建</a-select-option>
            <a-select-option value="self_registered">自主注册</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-model:value="searchParams.status"
            placeholder="全部"
            allow-clear
            style="width: 100px"
          >
            <a-select-option value="enabled">正常</a-select-option>
            <a-select-option value="disabled">禁用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit">
              <template #icon><SearchOutlined /></template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon><ReloadOutlined /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>

    <!-- 数据表格 -->
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :loading="loading"
      :pagination="pagination"
      row-key="id"
      @change="handleTableChange"
      class="data-table"
    >
      <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 === 'userType'">
          <a-tag :color="getUserTypeTag(record).color">
            {{ getUserTypeTag(record).label }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'tenantName'">
          {{ getUserTypeKey(record) === 'platform' || getUserTypeKey(record) === 'public'
            ? '-'
            : record.tenant?.name || '-' }}
        </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 === 'roles'">
          <a-tag v-for="ur in record.roles" :key="ur.id" class="role-tag">
            {{ ur.role.name }}
          </a-tag>
          <span v-if="!record.roles?.length" class="text-muted">-</span>
        </template>
        <template v-else-if="column.key === 'userSource'">
          <a-tag v-if="record.userSource === 'self_registered'" color="blue">自主注册</a-tag>
          <a-tag v-else>管理创建</a-tag>
        </template>
        <template v-else-if="column.key === 'createTime'">
          {{ formatDate(record.createTime) }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="link" size="small" @click="showDetail(record)">
              查看详情
            </a-button>
            <a-dropdown>
              <a-button type="link" size="small">更多</a-button>
              <template #overlay>
                <a-menu @click="({ key }) => handleAction(key as string, record)">
                  <a-menu-item key="toggleStatus">
                    {{ record.status === 'enabled' ? '禁用' : '启用' }}
                  </a-menu-item>
                  <a-menu-item key="resetPassword">重置密码</a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 详情 Drawer -->
    <a-drawer
      v-model:open="detailVisible"
      title="用户详情"
      :width="560"
      :destroy-on-close="true"
    >
      <template v-if="detailLoading">
        <div class="drawer-loading"><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.email || '-' }}</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="所属机构">{{ detailData.tenant?.name || '-' }}</a-descriptions-item>
          <a-descriptions-item label="用户类型">
            <a-tag :color="getUserTypeTag(detailData).color">{{ getUserTypeTag(detailData).label }}</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="角色">
            <a-tag v-for="ur in detailData.roles" :key="ur.id">{{ ur.role.name }}</a-tag>
            <span v-if="!detailData.roles?.length">-</span>
          </a-descriptions-item>
          <a-descriptions-item label="来源">
            {{ detailData.userSource === 'self_registered' ? '自主注册' : '管理创建' }}
          </a-descriptions-item>
          <a-descriptions-item label="注册时间" :span="2">{{ formatDate(detailData.createTime) }}</a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="detailData.status === 'enabled' ? 'green' : 'red'">
              {{ detailData.status === 'enabled' ? '正常' : '禁用' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item v-if="detailData.organization" label="单位">{{ detailData.organization }}</a-descriptions-item>
        </a-descriptions>

        <!-- 公众用户：子女信息 -->
        <template v-if="getUserTypeKey(detailData) === 'public'">
          <div class="detail-section">
            <h4>子女信息（{{ detailData.children?.length || 0 }}）</h4>
            <a-empty v-if="!detailData.children?.length" description="暂无子女" :image="simpleImage" />
            <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.gender">{{ child.gender === 'male' ? '男' : '女' }}</a-tag>
                  <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="暂无报名" :image="simpleImage" />
            <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="regStateColor(reg.registrationState)" size="small">
                    {{ regStateLabel(reg.registrationState) }}
                  </a-tag>
                  <span v-if="reg.participantType === 'child' && reg.child" class="reg-child">
                    子女：{{ reg.child.name }}
                  </span>
                  <span class="reg-time">{{ formatDate(reg.createTime) }}</span>
                </div>
              </div>
            </div>
          </div>
        </template>

        <!-- 评委：评审活动 -->
        <template v-if="getUserTypeKey(detailData) === 'judge' && detailData.contestJudges?.length">
          <div class="detail-section">
            <h4>评审活动（{{ detailData.contestJudges.length }}）</h4>
            <div class="reg-list">
              <div v-for="cj in detailData.contestJudges" :key="cj.contest.id" class="reg-item">
                <span class="reg-contest">{{ cj.contest.contestName }}</span>
                <div class="reg-meta">
                  <a-tag :color="cj.contest.status === 'ongoing' ? 'green' : 'default'" size="small">
                    {{ cj.contest.status === 'ongoing' ? '进行中' : '已结束' }}
                  </a-tag>
                </div>
              </div>
            </div>
          </div>
        </template>

        <!-- 机构/平台用户：权限概览 -->
        <template v-if="getUserTypeKey(detailData) === 'org' || getUserTypeKey(detailData) === 'platform'">
          <div class="detail-section">
            <h4>权限概览</h4>
            <p v-if="detailData.roles?.length">
              拥有角色：<a-tag v-for="ur in detailData.roles" :key="ur.id">{{ ur.role.name }}</a-tag>
            </p>
            <p v-else class="text-muted">暂无角色</p>
          </div>
        </template>
      </template>
    </a-drawer>

    <!-- 重置密码弹窗 -->
    <a-modal
      v-model:open="passwordModalVisible"
      title="重置密码"
      :confirm-loading="passwordLoading"
      @ok="handlePasswordSubmit"
    >
      <a-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" :label-col="{ span: 6 }">
        <a-form-item label="新密码" name="newPassword">
          <a-input-password v-model:value="passwordForm.newPassword" placeholder="请输入新密码" />
        </a-form-item>
        <a-form-item label="确认密码" name="confirmPassword">
          <a-input-password v-model:value="passwordForm.confirmPassword" placeholder="请再次输入" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, h } from 'vue'
import { message, Modal, Empty } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import {
  SearchOutlined,
  ReloadOutlined,
  TeamOutlined,
  CrownOutlined,
  BankOutlined,
  AuditOutlined,
  UserOutlined,
} from '@ant-design/icons-vue'
import {
  usersApi,
  type User,
  type UserQueryParams,
  type UserStats,
} from '@/api/users'
import { tenantsApi, type Tenant } from '@/api/tenants'
import dayjs from 'dayjs'

const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE

// ========== 统计 ==========
const stats = ref<UserStats>({ total: 0, platform: 0, org: 0, judge: 0, public: 0 })
const activeType = ref<string>('')

const statsItems = computed(() => [
  { type: '', label: '全部', count: stats.value.total, icon: TeamOutlined, color: '#6366f1', bgColor: 'rgba(99,102,241,0.1)' },
  { type: 'platform', label: '平台', count: stats.value.platform, icon: CrownOutlined, color: '#3b82f6', bgColor: 'rgba(59,130,246,0.1)' },
  { type: 'org', label: '机构', count: stats.value.org, icon: BankOutlined, color: '#10b981', bgColor: 'rgba(16,185,129,0.1)' },
  { type: 'judge', label: '评委', count: stats.value.judge, icon: AuditOutlined, color: '#f59e0b', bgColor: 'rgba(245,158,11,0.1)' },
  { type: 'public', label: '公众', count: stats.value.public, icon: UserOutlined, color: '#8b5cf6', bgColor: 'rgba(139,92,246,0.1)' },
])

const fetchStats = async () => {
  try {
    stats.value = await usersApi.getStats()
  } catch {
    // 静默失败
  }
}

const handleStatClick = (type: string) => {
  activeType.value = type
  searchParams.userType = type || undefined
  if (type && type !== 'org') {
    searchParams.filterTenantId = undefined
  }
  handleSearch()
}

// ========== 筛选 & 列表 ==========
const loading = ref(false)
const dataSource = ref<User[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (t: number) => `共 ${t} 条`,
})
const searchParams = reactive<UserQueryParams>({
  keyword: undefined,
  userType: undefined,
  filterTenantId: undefined,
  userSource: undefined,
  status: undefined,
})

const fetchList = async () => {
  loading.value = true
  try {
    const res = await usersApi.getList({
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchParams,
    })
    dataSource.value = res.list
    pagination.total = res.total
  } catch {
    message.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

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

const handleReset = () => {
  searchParams.keyword = undefined
  searchParams.userType = undefined
  searchParams.filterTenantId = undefined
  searchParams.userSource = undefined
  searchParams.status = undefined
  activeType.value = ''
  pagination.current = 1
  fetchList()
}

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

// ========== 租户下拉 ==========
const tenantOptions = ref<{ label: string; value: number }[]>([])

const fetchTenants = async () => {
  try {
    const res = await tenantsApi.getList({ page: 1, pageSize: 100 })
    tenantOptions.value = res.list
      .filter((t: Tenant) => !t.isSuper && t.code !== 'public' && t.code !== 'judge')
      .map((t: Tenant) => ({ label: t.name, value: t.id }))
  } catch {
    // 静默失败
  }
}

const filterTenantOption = (input: string, option: any) => {
  return option.label?.toLowerCase().includes(input.toLowerCase())
}

// ========== 表格列 ==========
const columns = [
  { title: '用户信息', key: 'userInfo', width: 220 },
  { title: '用户类型', key: 'userType', width: 90 },
  { title: '所属机构', key: 'tenantName', width: 140 },
  { title: '手机号', key: 'phone', width: 130 },
  { title: '城市', key: 'city', width: 100 },
  { title: '角色', key: 'roles', width: 120 },
  { title: '来源', key: 'userSource', width: 90 },
  { title: '注册时间', key: 'createTime', width: 160 },
  { title: '操作', key: 'action', width: 140, fixed: 'right' as const },
]

// ========== 用户类型推导 ==========
function getUserTypeKey(user: User): string {
  if (!user.tenant) return 'org'
  if (user.tenant.isSuper === 1) return 'platform'
  if (user.tenant.code === 'public') return 'public'
  if (user.tenant.code === 'judge') return 'judge'
  return 'org'
}

function getUserTypeTag(user: User) {
  const map: Record<string, { label: string; color: string }> = {
    platform: { label: '平台', color: 'blue' },
    org: { label: '机构', color: 'green' },
    judge: { label: '评委', color: 'orange' },
    public: { label: '公众', color: 'purple' },
  }
  return map[getUserTypeKey(user)] || { label: '未知', color: 'default' }
}

// ========== 详情 Drawer ==========
const detailVisible = ref(false)
const detailLoading = ref(false)
const detailData = ref<User | null>(null)

const showDetail = async (record: User) => {
  detailVisible.value = true
  detailLoading.value = true
  try {
    detailData.value = await usersApi.getDetail(record.id)
  } catch {
    message.error('获取用户详情失败')
  } finally {
    detailLoading.value = false
  }
}

// ========== 操作 ==========
const handleAction = (key: string, record: User) => {
  if (key === 'toggleStatus') {
    const newStatus = record.status === 'enabled' ? 'disabled' : 'enabled'
    const action = newStatus === 'disabled' ? '禁用' : '启用'
    Modal.confirm({
      title: `确认${action}`,
      content: `确定要${action}用户「${record.nickname}」吗？`,
      okText: '确定',
      okType: newStatus === 'disabled' ? 'danger' : 'primary',
      cancelText: '取消',
      onOk: async () => {
        try {
          await usersApi.updateStatus(record.id, newStatus)
          message.success(`${action}成功`)
          fetchList()
          fetchStats()
        } catch (err: any) {
          message.error(err?.response?.data?.message || `${action}失败`)
        }
      },
    })
  } else if (key === 'resetPassword') {
    currentPasswordUserId.value = record.id
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''
    passwordModalVisible.value = true
  }
}

// ========== 重置密码 ==========
const passwordModalVisible = ref(false)
const passwordLoading = ref(false)
const passwordFormRef = ref<FormInstance>()
const currentPasswordUserId = ref<number | null>(null)
const passwordForm = reactive({ newPassword: '', confirmPassword: '' })

const passwordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码不少于6位', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请再次输入', trigger: 'blur' },
    {
      validator: (_: any, value: string) =>
        value === passwordForm.newPassword
          ? Promise.resolve()
          : Promise.reject('两次密码不一致'),
      trigger: 'blur',
    },
  ],
}

const handlePasswordSubmit = async () => {
  try {
    await passwordFormRef.value?.validate()
    passwordLoading.value = true
    await usersApi.update(currentPasswordUserId.value!, { password: passwordForm.newPassword })
    message.success('密码重置成功')
    passwordModalVisible.value = false
  } catch (err: any) {
    if (!err?.errorFields) {
      message.error(err?.response?.data?.message || '重置失败')
    }
  } finally {
    passwordLoading.value = false
  }
}

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

// ========== 初始化 ==========
onMounted(() => {
  fetchStats()
  fetchList()
  fetchTenants()
})
</script>

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

.users-page {
  .title-card {
    margin-bottom: 16px;
    border: none;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);

    :deep(.ant-card-head) {
      border-bottom: none;
      .ant-card-head-title {
        font-size: 18px;
        font-weight: 600;
      }
    }
    :deep(.ant-card-body) {
      padding: 0;
    }
  }
}

// 统计卡片
.stats-row {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.stat-card {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.2s ease;

  &:hover {
    box-shadow: 0 4px 16px rgba($primary, 0.12);
  }

  &.active {
    border-color: $primary;
    background: rgba($primary, 0.02);
  }

  .stat-icon {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    flex-shrink: 0;
  }

  .stat-info {
    display: flex;
    flex-direction: column;

    .stat-count {
      font-size: 20px;
      font-weight: 700;
      color: #1e1b4b;
      line-height: 1.2;
    }

    .stat-label {
      font-size: 12px;
      color: #9ca3af;
    }
  }
}

// 筛选栏
.filter-bar {
  padding: 20px 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  margin-bottom: 16px;
}

// 表格
.data-table {
  :deep(.ant-table-wrapper) {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
    overflow: hidden;

    .ant-table-thead > tr > th {
      background: #fafafa;
      font-weight: 600;
    }

    .ant-table-tbody > tr:hover > td {
      background: rgba($primary, 0.03);
    }

    .ant-table-pagination {
      padding: 16px;
      margin: 0;
    }
  }
}

// 用户信息列
.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;
    }
  }
}

.role-tag {
  margin-bottom: 2px;
}

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

// Drawer 详情
.drawer-loading {
  text-align: center;
  padding: 60px;
}

.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>
