<template>
  <div class="registrations-container">
    <el-page-header @back="$router.back()">
      <template #content>
        <h2 class="page-title">报名管理 - {{ activityName }}</h2>
      </template>
    </el-page-header>
    
    <!-- 统计信息 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="stat-item">
            <span class="stat-label">报名总数</span>
            <span class="stat-value">{{ stats.totalCount }}</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="stat-item">
            <span class="stat-label">已签到</span>
            <span class="stat-value text-success">{{ stats.checkedInCount }}</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="stat-item">
            <span class="stat-label">未签到</span>
            <span class="stat-value text-warning">{{ stats.notCheckedInCount }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 搜索栏 -->
    <el-card shadow="never" class="toolbar-card">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-space wrap>
            <el-select v-model="filters.checkInStatus" placeholder="签到状态" clearable style="width: 120px" @change="loadRegistrationList">
              <el-option label="全部" :value="undefined" />
              <el-option label="已报名" :value="1" />
              <el-option label="已取消" :value="2" />
              <el-option label="已签到" :value="3" />
            </el-select>
            
            <el-select v-model="filters.paymentStatus" placeholder="支付状态" clearable style="width: 120px" @change="loadRegistrationList">
              <el-option label="全部" :value="undefined" />
              <el-option label="未支付" :value="0" />
              <el-option label="已支付" :value="1" />
            </el-select>
            
            <el-input
              v-model="filters.keyword"
              placeholder="搜索用户名或手机号"
              clearable
              style="width: 200px"
              @clear="loadRegistrationList"
              @keyup.enter="loadRegistrationList"
            >
              <template #append>
                <el-button icon="Search" @click="loadRegistrationList" />
              </template>
            </el-input>
            
            <el-button type="success" icon="Download" @click="handleExport">
              导出数据
            </el-button>
          </el-space>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 报名列表 -->
    <el-card shadow="never" class="table-card">
      <template #header>
        <span>报名列表</span>
      </template>
      
      <el-table
        v-loading="loading"
        :data="registrationList"
        stripe
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" />
        
        <el-table-column prop="userId" label="用户ID" width="80" />
        
        <el-table-column prop="userName" label="用户名" width="120" />
        
        <el-table-column prop="userPhone" label="手机号" width="130" />
        
        <el-table-column prop="userGender" label="性别" width="60">
          <template #default="{ row }">
            {{ row.userGender === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="registrationTime" label="报名时间" width="180" />
        
        <el-table-column prop="paymentStatus" label="支付状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.paymentStatus === 1 ? 'success' : 'warning'" size="small">
              {{ row.paymentStatus === 1 ? '已支付' : '未支付' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="签到状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getCheckInStatusType(row.status)" size="small">
              {{ getCheckInStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status !== 3"
              type="primary"
              size="small"
              link
              @click="handleCheckIn(row)"
            >
              签到
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadRegistrationList"
          @current-change="loadRegistrationList"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { API_BASE_URL, API_ENDPOINTS } from '@/config/api'

const route = useRoute()
const activityId = ref(parseInt(route.params.id))
const activityName = ref('')
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const registrationList = ref([])

const filters = reactive({
  checkInStatus: undefined,
  paymentStatus: undefined,
  keyword: ''
})

const stats = reactive({
  totalCount: 0,
  checkedInCount: 0,
  notCheckedInCount: 0
})

// 加载统计数据
const loadStats = async () => {
  try {
    const response = await request.get(API_ENDPOINTS.ACTIVITY_REGISTRATION_STATS, {
      params: {
        activityId: activityId.value
      }
    })
    
    if (response.code === 200) {
      stats.totalCount = response.data.totalCount || 0
      stats.checkedInCount = response.data.checkedInCount || 0
      stats.notCheckedInCount = response.data.notCheckedInCount || 0
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 加载报名列表
const loadRegistrationList = async () => {
  loading.value = true
  try {
    const response = await request.get(API_ENDPOINTS.ACTIVITY_REGISTRATIONS, {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        activityId: activityId.value,
        checkInStatus: filters.checkInStatus,
        paymentStatus: filters.paymentStatus,
        keyword: filters.keyword || undefined
      }
    })
    
    if (response.code === 200) {
      registrationList.value = response.data.list || []
      total.value = response.data.total || 0
      activityName.value = response.data.activityName || ''
      
      // 加载统计数据
      await loadStats()
    }
  } catch (error) {
    console.error('加载报名列表失败:', error)
    ElMessage.error('加载报名列表失败')
  } finally {
    loading.value = false
  }
}

// 获取签到状态文本
const getCheckInStatusText = (status) => {
  const texts = { 1: '已报名', 2: '已取消', 3: '已签到' }
  return texts[status] || '未知'
}

// 获取签到状态类型
const getCheckInStatusType = (status) => {
  const types = { 1: 'info', 2: 'danger', 3: 'success' }
  return types[status] || ''
}

// 签到
const handleCheckIn = async (row) => {
  try {
    const response = await request.post(`/api/admin/activity/check-in`, {
      activityId: activityId.value,
      userId: row.userId
    })
    
    if (response.code === 200) {
      ElMessage.success('签到成功')
      // 重新加载列表和统计数据
      await loadRegistrationList()
      await loadStats()
    }
  } catch (error) {
    console.error('签到失败:', error)
  }
}

// 取消报名
const handleCancelRegistration = async (row) => {
  try {
    await ElMessageBox.confirm('确定要取消此用户的报名吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await request.delete(`/api/admin/activity/cancel-registration`, {
      params: {
        activityId: activityId.value,
        userId: row.userId
      }
    })
    
    if (response.code === 200) {
      ElMessage.success('取消报名成功')
      // 重新加载列表和统计数据
      await loadRegistrationList()
      await loadStats()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消报名失败:', error)
    }
  }
}

// 导出数据
const handleExport = async () => {
  try {
    loading.value = true
    const params = {
      activityId: activityId.value,
      checkInStatus: filters.checkInStatus,
      paymentStatus: filters.paymentStatus,
      keyword: filters.keyword || undefined
    }
    
    // 使用axios下载文件
    const blob = await request.get(API_ENDPOINTS.ACTIVITY_REGISTRATION_EXPORT, {
      params: params,
      responseType: 'blob'
    })
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `活动报名列表_${new Date().getTime()}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    // 如果是blob响应但包含错误信息，尝试解析
    if (error.response && error.response.data instanceof Blob) {
      const text = await error.response.data.text()
      try {
        const errorData = JSON.parse(text)
        ElMessage.error('导出失败: ' + (errorData.msg || '未知错误'))
      } catch {
        ElMessage.error('导出失败')
      }
    } else {
      ElMessage.error('导出失败: ' + (error.message || '未知错误'))
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadRegistrationList()
})
</script>

<style scoped>
.registrations-container {
  padding: 0;
}

.page-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.stats-row {
  margin: 20px 0;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.text-success {
  color: #67c23a;
}

.text-warning {
  color: #e6a23c;
}

.toolbar-card {
  margin-top: 20px;
}

.table-card {
  margin-top: 20px;
}

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

