<template>
  <section class="space-y-6">

    <div v-if="!hasAuth" class="mos-card border-dashed p-4 text-sm text-mosquito-ink/70">
      <div class="flex items-start gap-3">
        <div class="flex h-10 w-10 items-center justify-center rounded-2xl bg-mosquito-accent/10 text-mosquito-accent">!</div>
        <div>
          <div class="font-semibold text-mosquito-ink">未配置鉴权信息</div>
          <div class="mos-muted mt-1 text-xs">请设置 API Key 与用户令牌后查看活动列表。</div>
        </div>
      </div>
    </div>

    <div v-if="loadError" class="mos-card border-dashed p-4 text-sm text-rose-600">
      {{ loadError }}
    </div>

    <ListSection :page="page + 1" :total-pages="totalPages" @prev="prevPage" @next="nextPage">
      <template #title>活动运营看板</template>
      <template #subtitle>查看活动列表并管理分享推广设置。</template>
      <template #filters>
        <input class="mos-input !py-1 !px-2 !text-xs w-48" v-model="query" placeholder="搜索活动名称" />
        <select class="mos-input !py-1 !px-2 !text-xs" v-model="statusFilter">
          <option value="">全部状态</option>
          <!-- 值为英文状态码，显示为中文 -->
          <option value="RUNNING">进行中</option>
          <option value="WAITING_PUBLISH">待发布</option>
          <option value="ENDED">已结束</option>
          <option value="PAUSED">已暂停</option>
          <option value="DRAFT">草稿</option>
        </select>
        <input class="mos-input !py-1 !px-2 !text-xs" type="date" v-model="startDate" />
        <input class="mos-input !py-1 !px-2 !text-xs" type="date" v-model="endDate" />
      </template>
      <template #actions>
        <PermissionButton permission="activity.index.create.ALL" :hide-when-no-permission="true">
          <RouterLink to="/activity/new" class="rounded-xl bg-mosquito-accent px-3 py-2 text-sm font-semibold text-white shadow-soft">
            新建活动
          </RouterLink>
        </PermissionButton>
      </template>
      <template #default>
        <!-- 批量操作工具栏 -->
        <div v-if="pagedActivities.length" class="mb-3 flex items-center justify-between rounded-lg bg-mosquito-bg/50 px-3 py-2">
          <div class="flex items-center gap-2">
            <label class="flex cursor-pointer items-center gap-1 text-xs">
              <input type="checkbox" v-model="selectAll" @change="toggleSelectAll" class="h-3.5 w-3.5" />
              <span class="text-mosquito-ink/70">全选</span>
            </label>
            <span class="text-xs text-mosquito-ink/50">|</span>
            <span class="text-xs text-mosquito-ink/70">已选 {{ selectedIds.length }} 项</span>
          </div>
          <div v-if="selectedIds.length > 0" class="flex gap-2">
            <PermissionButton permission="activity.index.publish.ALL" variant="secondary" @click="handleBatchPublish" :disabled="batchLoading">
              <span class="rounded px-2 py-1 text-xs font-semibold text-mosquito-brand hover:bg-mosquito-accent/10">批量发布</span>
            </PermissionButton>
            <PermissionButton permission="activity.index.pause.ALL" variant="secondary" @click="handleBatchPause" :disabled="batchLoading">
              <span class="rounded px-2 py-1 text-xs font-semibold text-amber-600 hover:bg-amber-50">批量暂停</span>
            </PermissionButton>
            <PermissionButton permission="activity.index.end.ALL" variant="secondary" @click="handleBatchEnd" :disabled="batchLoading">
              <span class="rounded px-2 py-1 text-xs font-semibold text-blue-600 hover:bg-blue-50">批量结束</span>
            </PermissionButton>
          </div>
        </div>
        <div v-if="pagedActivities.length" class="space-y-3">
          <div
            v-for="item in pagedActivities"
            :key="item.id"
            class="flex items-center justify-between rounded-xl border border-mosquito-line px-4 py-3 transition hover:bg-mosquito-bg/60"
          >
            <div class="flex items-center gap-3">
              <input type="checkbox" :value="item.id" v-model="selectedIds" class="h-4 w-4" @click.stop />
              <RouterLink :to="`/activity/${item.id}`" class="flex-1">
                <div class="text-sm font-semibold text-mosquito-ink">{{ item.name }}</div>
                <div class="mos-muted text-xs">{{ item.period }}</div>
              </RouterLink>
            </div>
            <div class="flex items-center gap-4 text-xs text-mosquito-ink/70">
              <span>{{ item.participants }} 人参与</span>
              <span class="rounded-full bg-mosquito-accent/10 px-2 py-1 text-[10px] font-semibold text-mosquito-brand">{{ item.status }}</span>
              <div class="flex items-center gap-1" @click.stop>
                <PermissionButton
                  v-if="getAvailableActions(item).some(a => a.key === 'publish')"
                  permission="activity.index.publish.ALL"
                  :disabled="isOperating(item.id)"
                  variant="primary"
                  @click="handlePublish(item.id)"
                >发布</PermissionButton>
                <PermissionButton
                  v-if="getAvailableActions(item).some(a => a.key === 'pause')"
                  permission="activity.index.pause.ALL"
                  :disabled="isOperating(item.id)"
                  variant="secondary"
                  @click="handlePause(item.id)"
                >暂停</PermissionButton>
                <PermissionButton
                  v-if="getAvailableActions(item).some(a => a.key === 'resume')"
                  permission="activity.index.resume.ALL"
                  :disabled="isOperating(item.id)"
                  variant="secondary"
                  @click="handleResume(item.id)"
                >恢复</PermissionButton>
                <PermissionButton
                  v-if="getAvailableActions(item).some(a => a.key === 'end')"
                  permission="activity.index.end.ALL"
                  :disabled="isOperating(item.id)"
                  variant="secondary"
                  @click="handleEnd(item.id)"
                >结束</PermissionButton>
                <PermissionButton
                  v-if="getAvailableActions(item).some(a => a.key === 'delete')"
                  permission="activity.index.delete.ALL"
                  :disabled="isOperating(item.id)"
                  variant="danger"
                  @click="handleDelete(item.id)"
                >删除</PermissionButton>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template #empty>
        <div v-if="!pagedActivities.length" class="mt-6 rounded-xl border border-dashed border-mosquito-line p-6 text-sm text-mosquito-ink/70">
          <div class="flex items-start gap-3">
            <div class="flex h-10 w-10 items-center justify-center rounded-2xl bg-mosquito-accent/10 text-mosquito-accent">+</div>
            <div>
              <div class="font-semibold text-mosquito-ink">暂无活动数据</div>
              <div class="mos-muted mt-1 text-xs">点击“新建活动”开始配置分享任务。</div>
            </div>
          </div>
        </div>
      </template>
    </ListSection>

    <div class="mos-card p-5">
      <div class="flex items-center justify-between">
        <div>
          <div class="text-xs font-semibold text-mosquito-ink/70">排行榜预览</div>
          <div class="mos-muted mt-1 text-xs">数据来自 /api/v1/activities/{id}/leaderboard</div>
        </div>
        <span class="mos-pill">示例</span>
      </div>

      <div v-if="hasAuth && activitiesWithMeta.length" class="mt-4">
        <MosquitoLeaderboard
          :activity-id="activeActivityId"
          :top-n="3"
          :current-user-id="currentUserId"
        />
      </div>

      <div v-else-if="hasAuth" class="mt-6 rounded-xl border border-dashed border-mosquito-line p-6 text-sm text-mosquito-ink/70">
        <div class="flex items-start gap-3">
          <div class="flex h-10 w-10 items-center justify-center rounded-2xl bg-mosquito-accent/10 text-mosquito-accent">!</div>
          <div>
            <div class="font-semibold text-mosquito-ink">暂无活动榜单</div>
            <div class="mos-muted mt-1 text-xs">请先创建活动后再查看排行。</div>
          </div>
        </div>
      </div>

      <div v-else class="mt-6 rounded-xl border border-dashed border-mosquito-line p-6 text-sm text-mosquito-ink/70">
        <div class="flex items-start gap-3">
          <div class="flex h-10 w-10 items-center justify-center rounded-2xl bg-mosquito-accent/10 text-mosquito-accent">!</div>
          <div>
            <div class="font-semibold text-mosquito-ink">配置鉴权后可查看榜单</div>
            <div class="mos-muted mt-1 text-xs">请设置 API Key 与用户令牌。</div>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useRoute, RouterLink } from 'vue-router'
import MosquitoLeaderboard from '../../../components/MosquitoLeaderboard.vue'
import { getUserIdFromToken, parseUserId } from '../../../shared/auth'
import { useDataService } from '../services'
import activityService from '../services/activity'
import { useAuthStore } from '../stores/auth'
import ListSection from '../components/ListSection.vue'
import PermissionButton from '../components/PermissionButton.vue'

type ActivitySummary = {
  id: number
  name: string
  startTime?: string
  endTime?: string
  status?: string
  participants?: number
  period?: string
}

const activityId = 1
const service = useDataService()
const route = useRoute()
const auth = useAuthStore()
const userToken = import.meta.env.VITE_MOSQUITO_USER_TOKEN
// 基于认证状态计算权限（真实鉴权）
const hasAuth = computed(() => auth.isAuthenticated)
const routeUserId = computed(() => parseUserId(route.query.userId ?? route.params.userId))
const currentUserId = computed(() => getUserIdFromToken(userToken) ?? routeUserId.value ?? undefined)
const activities = ref<ActivitySummary[]>([])
const loadError = ref('')
const activeActivityId = computed(() => activities.value[0]?.id ?? activityId)
const query = ref('')
const statusFilter = ref('')
const startDate = ref('')
const endDate = ref('')
const page = ref(0)
const pageSize = 6

// 批量选择相关
const selectedIds = ref<number[]>([])
const selectAll = ref(false)
const batchLoading = ref(false)

// 分页方法
const prevPage = () => {
  if (page.value > 0) {
    page.value--
  }
}

const nextPage = () => {
  if (page.value < totalPages.value - 1) {
    page.value++
  }
}

// 全选/取消全选
const toggleSelectAll = () => {
  if (selectAll.value) {
    selectedIds.value = pagedActivities.value.map((item: any) => item.id)
  } else {
    selectedIds.value = []
  }
}

// 批量发布
const handleBatchPublish = async () => {
  if (selectedIds.value.length === 0) return
  if (!confirm(`确定发布选中的 ${selectedIds.value.length} 个活动吗？`)) return
  batchLoading.value = true
  try {
    const result = await activityService.batchPublish(selectedIds.value)
    showMessage(`批量发布成功: ${result.successCount || selectedIds.value.length} 个`)
    selectedIds.value = []
    selectAll.value = false
    await loadActivities()
  } catch (e: any) {
    showMessage(e.message || '批量发布失败', true)
  } finally {
    batchLoading.value = false
  }
}

// 批量暂停
const handleBatchPause = async () => {
  if (selectedIds.value.length === 0) return
  if (!confirm(`确定暂停选中的 ${selectedIds.value.length} 个活动吗？`)) return
  batchLoading.value = true
  try {
    const result = await activityService.batchPause(selectedIds.value)
    showMessage(`批量暂停成功: ${result.successCount || selectedIds.value.length} 个`)
    selectedIds.value = []
    selectAll.value = false
    await loadActivities()
  } catch (e: any) {
    showMessage(e.message || '批量暂停失败', true)
  } finally {
    batchLoading.value = false
  }
}

// 批量结束
const handleBatchEnd = async () => {
  if (selectedIds.value.length === 0) return
  if (!confirm(`确定结束选中的 ${selectedIds.value.length} 个活动吗？`)) return
  batchLoading.value = true
  try {
    const result = await activityService.batchEnd(selectedIds.value)
    showMessage(`批量结束成功: ${result.successCount || selectedIds.value.length} 个`)
    selectedIds.value = []
    selectAll.value = false
    await loadActivities()
  } catch (e: any) {
    showMessage(e.message || '批量结束失败', true)
  } finally {
    batchLoading.value = false
  }
}

// 监听分页变化，重新加载数据
watch(page, () => {
  loadActivities()
})

const formatPeriod = (activity: ActivitySummary) => {
  if (!activity.startTime || !activity.endTime) {
    return '活动时间待配置'
  }
  const start = new Date(activity.startTime)
  const end = new Date(activity.endTime)
  if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) {
    return '活动时间待配置'
  }
  return `${start.toLocaleDateString('zh-CN')} - ${end.toLocaleDateString('zh-CN')}`
}

const resolveStatus = (activity: ActivitySummary) => {
  // 优先使用后端返回的状态，不再使用时间推导
  if (activity.status) {
    return mapBackendStatusToChinese(activity.status)
  }
  // 兜底：如果后端没有返回状态，才使用时间推导（兼容旧数据）
  if (!activity.startTime || !activity.endTime) {
    return '待配置'
  }
  const now = Date.now()
  const start = new Date(activity.startTime).getTime()
  const end = new Date(activity.endTime).getTime()
  if (Number.isNaN(start) || Number.isNaN(end)) {
    return '待配置'
  }
  if (now < start) {
    return '未开始'
  }
  if (now > end) {
    return '已结束'
  }
  return '进行中'
}

// 后端状态到中文的映射
const mapBackendStatusToChinese = (backendStatus: string): string => {
  const statusMap: Record<string, string> = {
    'DRAFT': '草稿',
    'PENDING': '待审批',
    'IN_APPROVAL': '审批中',
    'APPROVED': '已审批',
    'REJECTED': '已拒绝',
    'WAITING_PUBLISH': '待发布',
    'RUNNING': '进行中',
    'PAUSED': '已暂停',
    'ENDED': '已结束',
    'ARCHIVED': '已归档',
    'DELETED': '已删除'
  }
  return statusMap[backendStatus] || backendStatus
}

// 获取原始后端状态（用于按钮逻辑）
const getBackendStatus = (activity: ActivitySummary): string => {
  return activity.status || ''
}

const activitiesWithMeta = computed(() =>
  activities.value.map((item) => ({
    id: item.id,
    name: item.name ?? `活动 #${item.id}`,
    period: formatPeriod(item),
    participants: 0,
    status: resolveStatus(item),
    startTime: item.startTime ?? '',
    endTime: item.endTime ?? ''
  }))
)

const filteredActivities = computed(() => {
  return activitiesWithMeta.value.filter((item) => {
    const matchesQuery = item.name.includes(query.value.trim())
    const matchesStatus = statusFilter.value ? item.status === statusFilter.value : true
    const startOk = startDate.value ? new Date(item.startTime).getTime() >= new Date(startDate.value).getTime() : true
    const endOk = endDate.value ? new Date(item.endTime).getTime() <= new Date(endDate.value).getTime() : true
    return matchesQuery && matchesStatus && startOk && endOk
  })
})

// 活动列表（使用过滤后的数据 + 后端分页）
const pagedActivities = computed(() => {
  // 后端已返回分页数据，直接使用
  const data = activities.value
  // 前端再做一次筛选确保一致性（搜索/状态/日期）
  return data.filter((item: any) => {
    const matchesQuery = (item.name ?? `活动 #${item.id}`).includes(query.value.trim())
    // 统一使用后端状态码进行筛选，支持中英文状态值
    const matchesStatus = statusFilter.value
      ? item.status === statusFilter.value || item.status === mapChineseStatusToBackend(statusFilter.value)
      : true
    const startOk = startDate.value ? new Date(item.startTime).getTime() >= new Date(startDate.value).getTime() : true
    const endOk = endDate.value ? new Date(item.endTime).getTime() <= new Date(endDate.value).getTime() : true
    return matchesQuery && matchesStatus && startOk && endOk
  })
})

// 中文状态到后端状态的映射（用于筛选）
const mapChineseStatusToBackend = (chineseStatus: string): string => {
  const reverseStatusMap: Record<string, string> = {
    '草稿': 'DRAFT',
    '待审批': 'PENDING',
    '审批中': 'IN_APPROVAL',
    '已审批': 'APPROVED',
    '已拒绝': 'REJECTED',
    '待发布': 'WAITING_PUBLISH',
    '进行中': 'RUNNING',
    '已暂停': 'PAUSED',
    '已结束': 'ENDED',
    '已归档': 'ARCHIVED',
    '已删除': 'DELETED',
    '待配置': 'DRAFT'
  }
  return reverseStatusMap[chineseStatus] || chineseStatus
}

// 监听筛选条件变化，重置页码并重新加载数据
watch([query, statusFilter, startDate, endDate], (newVals, oldVals) => {
  // 如果当前页不是第一页，先回到第一页（这会自动触发loadActivities）
  if (page.value !== 0) {
    page.value = 0
  } else {
    // 如果已经在第一页，直接重新加载
    loadActivities()
  }
})

// 总记录数（来自后端分页）
const total = ref(0)
const totalPages = computed(() => Math.ceil(total.value / pageSize))

const loadActivities = async () => {
  loadError.value = ''
  try {
    // 使用后端分页API（带筛选参数）
    const result = await service.getActivities({
      page: page.value,
      size: pageSize,
      status: statusFilter.value || undefined,
      keyword: query.value || undefined,
      startDate: startDate.value || undefined,
      endDate: endDate.value || undefined
    })

    // 处理分页响应
    const pageResult = result as { items?: any[]; total?: number }
    if (pageResult && typeof pageResult === 'object' && 'items' in pageResult && Array.isArray(pageResult.items)) {
      // 分页对象格式
      activities.value = pageResult.items
      total.value = typeof pageResult.total === 'number' ? pageResult.total : pageResult.items.length
    } else if (Array.isArray(result)) {
      // 数组格式（演示模式兼容）
      activities.value = result
      total.value = result.length
    } else {
      activities.value = []
      total.value = 0
    }
  } catch (error) {
    loadError.value = '活动列表加载失败。'
  }
}

// 活动操作函数
const operationLoading = ref<Record<number, string>>({})

const showMessage = (message: string, isError = false) => {
  // 使用简单的alert或console展示消息
  if (isError) {
    console.error(message)
    alert('错误: ' + message)
  } else {
    console.log(message)
    alert(message)
  }
}

const handlePublish = async (id: number) => {
  operationLoading.value[id] = 'publishing'
  try {
    await activityService.publishActivity(id)
    showMessage('发布成功')
    await loadActivities()
  } catch (e: any) {
    showMessage(e.message || '发布失败', true)
  } finally {
    delete operationLoading.value[id]
  }
}

const handlePause = async (id: number) => {
  operationLoading.value[id] = 'pausing'
  try {
    await activityService.pauseActivity(id)
    showMessage('暂停成功')
    await loadActivities()
  } catch (e: any) {
    showMessage(e.message || '暂停失败', true)
  } finally {
    delete operationLoading.value[id]
  }
}

const handleResume = async (id: number) => {
  operationLoading.value[id] = 'resuming'
  try {
    await activityService.resumeActivity(id)
    showMessage('恢复成功')
    await loadActivities()
  } catch (e: any) {
    showMessage(e.message || '恢复失败', true)
  } finally {
    delete operationLoading.value[id]
  }
}

const handleEnd = async (id: number) => {
  operationLoading.value[id] = 'ending'
  try {
    await activityService.endActivity(id)
    showMessage('结束成功')
    await loadActivities()
  } catch (e: any) {
    showMessage(e.message || '结束失败', true)
  } finally {
    delete operationLoading.value[id]
  }
}

const handleDelete = async (id: number) => {
  if (!confirm('确定要删除该活动吗？此操作不可恢复。')) {
    return
  }
  operationLoading.value[id] = 'deleting'
  try {
    await activityService.deleteActivity(id)
    showMessage('删除成功')
    await loadActivities()
  } catch (e: any) {
    showMessage(e.message || '删除失败', true)
  } finally {
    delete operationLoading.value[id]
  }
}

// 根据后端状态判断操作按钮显示（严格遵守状态机规则）
const getAvailableActions = (item: ActivitySummary) => {
  // 使用原始后端状态，不再使用前端推导的中文状态
  const backendStatus = getBackendStatus(item)
  const actions: { key: string; label: string; type: string; show: boolean }[] = [
    // 发布按钮：DRAFT, REJECTED, WAITING_PUBLISH 可以发布
    { key: 'publish', label: '发布', type: 'primary', show: ['DRAFT', 'REJECTED', 'WAITING_PUBLISH'].includes(backendStatus) },
    // 暂停按钮：RUNNING 状态可以暂停
    { key: 'pause', label: '暂停', type: 'warning', show: backendStatus === 'RUNNING' },
    // 恢复按钮：PAUSED 状态可以恢复
    { key: 'resume', label: '恢复', type: 'success', show: backendStatus === 'PAUSED' },
    // 结束按钮：RUNNING 或 PAUSED 可以结束
    { key: 'end', label: '结束', type: 'info', show: ['RUNNING', 'PAUSED'].includes(backendStatus) },
    // 删除按钮：仅 DRAFT 状态可以删除
    { key: 'delete', label: '删除', type: 'danger', show: backendStatus === 'DRAFT' }
  ]
  return actions.filter(a => a.show)
}

const isOperating = (id: number) => !!operationLoading.value[id]

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