<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="6">
          <el-button type="primary" icon="Plus" @click="$router.push('/activity/create')">
            新增活动
          </el-button>
          <el-button icon="Refresh" @click="loadActivityList">刷新</el-button>
        </el-col>
        <el-col :span="18">
          <el-space wrap>
            <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="row.coverImage"
              fit="cover"
              class="cover-image"
              :preview-src-list="[row.coverImage]"
            />
          </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 
              :class="{
                'status-pending': row.status === 1,
                'status-processing': row.status === 2,
                'status-disabled': row.status === 3
              }"
              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
              v-model="row.isHot"
              active-color="var(--danger-color)"
              inactive-color="var(--border-dark)"
              @change="handleHotChange(row)"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="startTime" label="开始时间" width="180" />
        
        <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 } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { 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 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) {
      activityList.value = response.data.list || response.data || []
      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 handleHotChange = async (row) => {
  try {
    const response = await request.put(`${API_ENDPOINTS.ACTIVITY_UPDATE}/${row.id}`, {
      isHot: row.isHot
    })
    
    if (response.code === 200) {
      ElMessage.success('状态更新成功')
    } else {
      row.isHot = !row.isHot
    }
  } catch (error) {
    console.error('状态更新失败:', error)
    row.isHot = !row.isHot
  }
}

// 删除活动
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>
@import '@/assets/list-common.css';

.activity-list-container {
  padding: 0;
}

/* 活动封面图片 */
.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);
}
</style>

