<template>
  <div class="activity-list-container">
    <h2 class="page-title">活动管理</h2>
    
    <!-- 操作栏 -->
    <el-card shadow="never" class="toolbar-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-space>
            <el-button type="primary" icon="Plus" @click="$router.push('/activity/create')">
              新增活动
            </el-button>
            <el-button icon="Refresh" @click="loadActivityList">刷新</el-button>
          </el-space>
        </el-col>
        <el-col :span="16">
          <el-space style="justify-content: flex-end; width: 100%;">
            <el-select v-model="filters.type" placeholder="活动类型" clearable style="width: 120px" @change="loadActivityList">
              <el-option label="全部" :value="undefined" />
              <el-option label="线上" :value="1" />
              <el-option label="线下" :value="2" />
            </el-select>
            
            <el-select v-model="filters.status" placeholder="活动状态" clearable style="width: 120px" @change="loadActivityList">
              <el-option label="全部" :value="undefined" />
              <el-option label="未开始" :value="1" />
              <el-option label="进行中" :value="2" />
              <el-option label="已结束" :value="3" />
            </el-select>
            
            <el-input
              v-model="filters.keyword"
              placeholder="搜索活动名称"
              clearable
              style="width: 200px"
              @clear="loadActivityList"
              @keyup.enter="loadActivityList"
            >
              <template #append>
                <el-button icon="Search" @click="loadActivityList" />
              </template>
            </el-input>
          </el-space>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 活动列表 -->
    <el-card shadow="never" class="table-card">
      <el-table
        v-loading="loading"
        :data="activityList"
        stripe
        style="width: 100%"
      >
        <template #empty>
          <div class="custom-empty-state">
            <el-icon class="empty-icon"><Calendar /></el-icon>
            <div class="empty-text">暂无活动数据</div>
            <div class="empty-hint">点击"新增活动"按钮开始创建</div>
          </div>
        </template>
        <el-table-column type="index" label="序号" width="60" />
        
        <el-table-column prop="coverImage" label="封面" width="120">
          <template #default="{ row }">
            <el-image
              :src="getCoverImage(row)"
              fit="cover"
              class="cover-image"
              :preview-src-list="getCoverPreviewList(row)"
              preview-teleported
              hide-on-click-modal
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        
        <el-table-column prop="name" label="活动名称" min-width="150">
          <template #default="{ row }">
            <span class="data-highlight text-ellipsis-line" :title="row.name">
              {{ row.name }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column prop="type" label="类型" width="90" align="center">
          <template #default="{ row }">
            <el-tag :type="row.type === 1 ? 'success' : 'primary'" size="small" effect="light">
              {{ row.type === 1 ? '线上' : '线下' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="category" label="类别" width="100" />
        
        <el-table-column prop="location" label="地点" min-width="120">
          <template #default="{ row }">
            <span class="data-description text-ellipsis-line" :title="row.location">
              {{ row.location || '-' }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column label="报名人数" width="120" align="center">
          <template #default="{ row }">
            <span :class="row.actualParticipants >= row.maxParticipants ? 'amount-text negative' : 'number-emphasis'">
              {{ row.actualParticipants || 0 }}
            </span>
            <span class="data-meta"> / {{ row.maxParticipants }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="price" label="费用" width="100" align="right">
          <template #default="{ row }">
            <span v-if="row.price > 0" class="amount-text">¥{{ row.price }}</span>
            <el-tag v-else class="status-success" size="small" effect="light">免费</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag 
              :type="row.status === 1 ? 'info' : row.status === 2 ? 'success' : 'danger'"
              size="small"
              effect="light"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="isHot" label="热门" width="80" align="center">
          <template #default="{ row }">
            <el-switch
              :model-value="Boolean(row.isHot)"
              active-color="var(--danger-color)"
              inactive-color="var(--border-dark)"
              @change="(val) => handleHotChange(row, val)"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="startTime" label="开始时间" width="180">
          <template #default="{ row }">
            <span v-if="row.startTime">{{ formatDateTime(row.startTime) }}</span>
            <span v-else class="data-meta">-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="endTime" label="结束时间" width="180">
          <template #default="{ row }">
            <span v-if="row.endTime">{{ formatDateTime(row.endTime) }}</span>
            <span v-else class="data-meta">-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="registrationEndTime" label="报名截止时间" width="180">
          <template #default="{ row }">
            <span v-if="row.registrationEndTime">{{ formatDateTime(row.registrationEndTime) }}</span>
            <span v-else class="data-meta">-</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              link
              icon="View"
              @click="handleViewRegistrations(row)"
            >
              报名
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              icon="Edit"
              @click="$router.push(`/activity/edit/${row.id}`)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              icon="Delete"
              @click="handleDelete(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="loadActivityList"
          @current-change="loadActivityList"
        />
      </div>
    </el-card>
  </div>
</template>

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

const router = useRouter()
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const activityList = ref([])

const filters = reactive({
  type: null,
  status: null,
  keyword: ''
})

// 规范化图片地址，兼容相对路径和缺少协议的情况
const resolveImageUrl = (url) => {
  if (!url || typeof url !== 'string') return ''
  const normalized = url.trim()
  if (/^https?:\/\//i.test(normalized)) return normalized
  if (normalized.startsWith('//')) return `${window.location.protocol}${normalized}`
  const base = API_BASE_URL || window.location.origin
  if (normalized.startsWith('/')) return `${base}${normalized}`
  return `${base}/${normalized}`
}

// 获取封面图，兼容不同字段命名
const getCoverImage = (row) => {
  const url = row?.coverImage || row?.cover_image || row?.cover || ''
  return resolveImageUrl(url)
}

const getCoverPreviewList = (row) => {
  const url = getCoverImage(row)
  return url ? [url] : []
}

// 加载活动列表
const loadActivityList = async () => {
  loading.value = true
  try {
    const response = await request.get(API_ENDPOINTS.ACTIVITY_LIST, {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        type: filters.type,
        status: filters.status,
        keyword: filters.keyword
      }
    })
    
    if (response.code === 200) {
      const list = response.data.list || response.data || []
      // 字段兼容与转换：确保 isHot 为布尔，并兼容不同时间字段命名
      activityList.value = list.map(item => ({
        ...item,
        isHot:
          item.isHot === true ||
          item.isHot === 1 ||
          item.isHot === '1' ||
          item.is_hot === true ||
          item.is_hot === 1,
        // 兼容下划线命名与不同字段名
        startTime: item.startTime || item.start_time || item.start_at || '',
        endTime: item.endTime || item.end_time || item.end_at || '',
        registrationEndTime:
          item.registrationEndTime ||
          item.registration_end_time ||
          item.signup_end_time ||
          '',
        // 兼容报名人数字段
        actualParticipants: item.actualParticipants ?? item.actual_participants ?? 0,
        maxParticipants: item.maxParticipants ?? item.max_participants
      }))
      total.value = response.data.total || activityList.value.length
    }
  } catch (error) {
    console.error('加载活动列表失败:', error)
    ElMessage.error('加载活动列表失败')
  } finally {
    loading.value = false
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = { 1: '未开始', 2: '进行中', 3: '已结束' }
  return texts[status] || '未知'
}

// 获取状态颜色
const getStatusType = (status) => {
  const types = { 1: 'info', 2: 'success', 3: '' }
  return types[status] || ''
}

// 查看报名情况
const handleViewRegistrations = (row) => {
  router.push(`/activity/registrations/${row.id}`)
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  // 如果是字符串，兼容 '2025-01-01T12:00:00' 或 '2025-01-01 12:00:00'
  if (typeof dateTime === 'string') {
    const normalized = dateTime.replace('T', ' ')
    return normalized.substring(0, 19)
  }
  // 如果是时间戳（秒或毫秒），转换为日期字符串
  if (typeof dateTime === 'number') {
    const ts = dateTime > 1e12 ? dateTime : dateTime * 1000
    const d = new Date(ts)
    const pad = (n) => (n < 10 ? `0${n}` : n)
    const Y = d.getFullYear()
    const M = pad(d.getMonth() + 1)
    const D = pad(d.getDate())
    const h = pad(d.getHours())
    const m = pad(d.getMinutes())
    const s = pad(d.getSeconds())
    return `${Y}-${M}-${D} ${h}:${m}:${s}`
  }
  // 其它类型（如 Date 对象）直接格式化
  if (dateTime instanceof Date) {
    const d = dateTime
    const pad = (n) => (n < 10 ? `0${n}` : n)
    const Y = d.getFullYear()
    const M = pad(d.getMonth() + 1)
    const D = pad(d.getDate())
    const h = pad(d.getHours())
    const m = pad(d.getMinutes())
    const s = pad(d.getSeconds())
    return `${Y}-${M}-${D} ${h}:${m}:${s}`
  }
  return String(dateTime)
}

// 切换热门状态
const handleHotChange = async (row, newValue) => {
  const oldValue = row.isHot
  // 立即更新UI
  row.isHot = newValue
  
  try {
    const response = await request.put(`${API_ENDPOINTS.ACTIVITY_UPDATE}/${row.id}`, {
      isHot: newValue
    })
    
    if (response.code === 200) {
      ElMessage.success('状态更新成功')
      // 重新加载列表以确保数据同步
      loadActivityList()
    } else {
      // 恢复原值
      row.isHot = oldValue
      ElMessage.error(response.message || '状态更新失败')
    }
  } catch (error) {
    console.error('状态更新失败:', error)
    // 恢复原值
    row.isHot = oldValue
    ElMessage.error('状态更新失败，请重试')
  }
}

// 删除活动
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个活动吗？删除后将无法恢复！', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await request.delete(`${API_ENDPOINTS.ACTIVITY_DELETE}/${row.id}`)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadActivityList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

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

<style scoped>
.activity-list-container {
  padding: 20px;
}

.page-title {
  margin: 0 0 20px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

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

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

/* 活动封面图片 */
.cover-image {
  width: 90px;
  height: 60px;
  border-radius: var(--radius-base);
  cursor: pointer;
  border: 2px solid var(--border-color);
  transition: all var(--transition-base);
  box-shadow: var(--shadow-sm);
}

.cover-image:hover {
  border-color: var(--primary-color);
  transform: scale(1.05);
  box-shadow: var(--shadow-md);
}

.image-slot {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 90px;
  height: 60px;
  background-color: var(--bg-tertiary);
  color: var(--text-tertiary);
  font-size: 20px;
  border-radius: var(--radius-base);
  border: 1px solid var(--border-color);
}
</style>

