<template>
  <section class="space-y-6">
    <header class="flex flex-wrap items-center justify-between gap-4">
      <div>
        <h1 class="mos-title text-2xl font-semibold">{{ activity?.name || '活动详情' }}</h1>
        <p class="mos-muted mt-2 text-sm">{{ activity?.description }}</p>
      </div>
      <div class="flex items-center gap-2">
        <span class="mos-pill">{{ statusLabel }}</span>
        <button
          v-if="hasPermission('activity.index.pause.ALL') || hasPermission('activity.index.resume.ALL')"
          class="mos-btn mos-btn-secondary"
          @click="toggleStatus"
        >
          {{ toggleLabel }}
        </button>
        <button
          v-if="hasPermission('activity.index.end.ALL')"
          class="mos-btn mos-btn-accent"
          @click="endActivity"
        >
          下线
        </button>
        <button
          v-if="activity?.status === 'ENDED' && hasPermission('activity.index.update.ALL')"
          class="mos-btn mos-btn-secondary"
          @click="handleArchive"
        >
          归档
        </button>
        <button
          v-if="activity?.status === 'DRAFT' && hasPermission('activity.index.delete.ALL')"
          class="mos-btn !border-red-500 !text-red-500 hover:!bg-red-50"
          @click="handleDelete"
        >
          删除
        </button>
      </div>
    </header>

    <div class="grid gap-4 md:grid-cols-4">
      <div class="mos-card p-4" v-for="metric in metricsCards" :key="metric.label">
        <div class="text-xs font-semibold text-mosquito-ink/70">{{ metric.label }}</div>
        <div class="mos-kpi mt-3 text-xl font-semibold">{{ metric.value }}</div>
        <div class="mos-muted mt-1 text-xs">{{ metric.hint }}</div>
      </div>
    </div>

    <div class="grid gap-6 lg:grid-cols-3">
      <div class="mos-card lg:col-span-2 p-5 space-y-4">
        <div class="text-sm font-semibold text-mosquito-ink">活动配置</div>
        <div class="grid gap-4 md:grid-cols-2 text-sm">
          <div>
            <div class="text-xs text-mosquito-ink/70">目标人群</div>
            <div class="font-semibold">{{ activityConfig.audience }}</div>
          </div>
          <div>
            <div class="text-xs text-mosquito-ink/70">转化条件</div>
            <div class="font-semibold">{{ activityConfig.conversion }}</div>
          </div>
          <div>
            <div class="text-xs text-mosquito-ink/70">奖励规则</div>
            <div class="font-semibold">{{ activityConfig.reward }}</div>
          </div>
          <div>
            <div class="text-xs text-mosquito-ink/70">预算/限额</div>
            <div class="font-semibold">{{ activityConfig.budget }}</div>
          </div>
        </div>
        <RouterLink to="/activity/config" class="text-sm font-semibold text-mosquito-accent">
          进入配置向导
        </RouterLink>
      </div>

      <div class="mos-card p-5 space-y-4">
        <div class="flex items-center justify-between">
          <div class="text-sm font-semibold text-mosquito-ink">导出</div>
          <select class="mos-input !py-1 !px-2 !text-xs" v-model="exportType">
            <option value="summary">活动摘要</option>
            <option value="conversions">转化明细</option>
            <option value="rewards">奖励明细</option>
          </select>
        </div>
        <ExportFieldPanel
          :title="exportTitle"
          :fields="currentFields"
          :selected="currentSelected"
          @update:selected="setCurrentSelected"
          @export="exportData"
        />
      </div>
    </div>

    <div class="mos-card p-5 space-y-4">
      <div class="text-sm font-semibold text-mosquito-ink">排行榜预览</div>
      <MosquitoLeaderboard v-if="activity" :activity-id="activity.id" :top-n="5" />
    </div>

    <!-- 裂变关系图 -->
    <div class="mos-card p-5 space-y-4">
      <div class="flex items-center justify-between">
        <div class="text-sm font-semibold text-mosquito-ink">裂变关系图</div>
        <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="loadGraph" :disabled="graphLoading">
          {{ graphLoading ? '加载中...' : '刷新关系图' }}
        </button>
      </div>
      <div v-if="graphError" class="text-red-500 text-sm">{{ graphError }}</div>
      <div v-else-if="!graphData || graphData.nodes?.length === 0" class="text-mosquito-ink/50 text-sm text-center py-8">
        暂无关系图数据
      </div>
      <div v-else class="graph-container overflow-auto" style="max-height: 400px;">
        <div class="flex flex-wrap gap-2 mb-4">
          <span class="text-xs">节点: {{ graphData.nodes?.length || 0 }}</span>
          <span class="text-xs">关系: {{ graphData.edges?.length || 0 }}</span>
        </div>
        <!-- 简化关系图展示：节点列表 + 连接关系 -->
        <div class="grid gap-2 md:grid-cols-2 lg:grid-cols-3">
          <div v-for="node in (graphData.nodes || []).slice(0, 20)" :key="node.id"
               class="border rounded p-2 text-xs hover:bg-mosquito-bg/50 cursor-pointer"
               @click="showNodeDetail(node)">
            <div class="font-semibold truncate">{{ node.label || node.id }}</div>
            <div class="text-mosquito-ink/70">
              直接邀请: {{ node.directInvites || 0 }} | 间接邀请: {{ node.indirectInvites || 0 }}
            </div>
          </div>
        </div>
        <div v-if="(graphData.nodes?.length || 0) > 20" class="text-center text-xs text-mosquito-ink/50 mt-2">
          ... 还有 {{ (graphData.nodes?.length || 0) - 20 }} 个节点
        </div>
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter, RouterLink } from 'vue-router'
import MosquitoLeaderboard from '../../../components/MosquitoLeaderboard.vue'
import { useActivityStore } from '../stores/activities'
import { useAuditStore } from '../stores/audit'
import { activityService } from '../services/activity'
import type { ActivityItem } from '../stores/activities'
import { downloadCsv } from '../utils/export'
import ExportFieldPanel, { type ExportField } from '../components/ExportFieldPanel.vue'
import { useExportFields } from '../composables/useExportFields'
import { useDataService } from '../services'
import { usePermission } from '../composables/usePermission'
import type { Permission } from '../auth/roles'

const route = useRoute()
const router = useRouter()
const store = useActivityStore()
const auditStore = useAuditStore()
const service = useDataService()
const activity = ref<any>(null)
const stats = ref<any>(null)
const { hasPermission } = usePermission()

// 裂变关系图相关
const graphData = ref<any>(null)
const graphLoading = ref(false)
const graphError = ref<string | null>(null)

const loadGraph = async () => {
  if (!activity.value) return
  graphLoading.value = true
  graphError.value = null
  try {
    graphData.value = await activityService.getActivityGraph(activity.value.id)
  } catch (e: any) {
    graphError.value = e.message || '加载关系图失败'
    console.error('加载关系图失败:', e)
  } finally {
    graphLoading.value = false
  }
}

const showNodeDetail = (node: any) => {
  alert(`用户: ${node.label || node.id}\n直接邀请: ${node.directInvites || 0}人\n间接邀请: ${node.indirectInvites || 0}人`)
}

// 解析活动配置
const activityConfig = computed(() => {
  if (!activity.value) return { audience: '-', conversion: '-', reward: '-', budget: '-' }
  try {
    const targetUsers = activity.value.targetUsersConfig ? JSON.parse(activity.value.targetUsersConfig) : {}
    const pageContent = activity.value.pageContentConfig ? JSON.parse(activity.value.pageContentConfig) : {}
    const rewardTiers = activity.value.rewardTiersConfig ? JSON.parse(activity.value.rewardTiersConfig) : {}
    return {
      audience: targetUsers.description || targetUsers.targetType || '全量用户',
      conversion: pageContent.conversionGoal || pageContent.condition || '完成邀请',
      reward: rewardTiers.tiers?.map((t: any) => `${t.level}级:${t.reward}`).join(', ') || '按阶梯奖励',
      budget: activity.value.budget || activity.value.maxBudget || '-'
    }
  } catch (e) {
    return { audience: '-', conversion: '-', reward: '-', budget: '-' }
  }
})

const loadActivity = async () => {
  const id = Number(route.params.id)
  activity.value = await activityService.getActivityById(id)
  // 获取活动统计数据
  try {
    stats.value = await activityService.getActivityStats(id)
  } catch (e) {
    console.warn('获取统计数据失败:', e)
    stats.value = { pv: 0, uv: 0, participants: 0, shares: 0, newUsers: 0, kFactor: 0, cac: 0 }
  }
  // 加载裂变关系图
  loadGraph()
}

const statusLabel = computed(() => {
  if (!activity.value) return '未知'
  const map: Record<string, string> = {
    DRAFT: '草稿',
    PENDING: '待审批',
    IN_APPROVAL: '审批中',
    APPROVED: '已审批',
    REJECTED: '已拒绝',
    WAITING_PUBLISH: '待发布',
    RUNNING: '进行中',
    PAUSED: '已暂停',
    ENDED: '已结束',
    ARCHIVED: '已归档',
    DELETED: '已删除'
  }
  return map[activity.value.status] ?? '未知'
})

const toggleLabel = computed(() => {
  if (!activity.value) return '切换状态'
  return activity.value.status === 'RUNNING' ? '暂停' : '上线'
})

const toggleStatus = async () => {
  if (!activity.value) return
  const next = activity.value.status === 'RUNNING' ? 'PAUSED' : 'RUNNING'
  try {
    if (next === 'PAUSED') {
      await activityService.pauseActivity(activity.value.id)
    } else {
      await activityService.resumeActivity(activity.value.id)
    }
    // 重新获取活动详情以确保状态同步
    const updated = await activityService.getActivityById(activity.value.id)
    if (updated) {
      activity.value = updated
    }
    auditStore.addLog(next === 'RUNNING' ? '上线活动' : '暂停活动', activity.value?.name ?? '活动')
  } catch (error) {
    console.error('切换状态失败:', error)
  }
}

// 删除活动
const handleDelete = async () => {
  if (!activity.value) return
  if (!confirm('确定要删除这个活动吗？只有草稿状态的活动才能删除。')) return
  try {
    await activityService.deleteActivity(activity.value.id)
    alert('活动删除成功')
    router.push('/activities')
    auditStore.addLog('删除活动', activity.value?.name ?? '活动')
  } catch (error) {
    console.error('删除活动失败:', error)
    alert(error instanceof Error ? error.message : '删除活动失败')
  }
}

// 归档活动
const handleArchive = async () => {
  if (!activity.value) return
  if (!confirm('确定要归档这个活动吗？归档后活动将不再显示在列表中。')) return
  try {
    await activityService.archiveActivity(activity.value.id)
    // 重新获取活动详情以确保状态同步
    const updated = await activityService.getActivityById(activity.value.id)
    if (updated) {
      activity.value = updated
    }
    alert('活动归档成功')
    auditStore.addLog('归档活动', activity.value?.name ?? '活动')
  } catch (error) {
    console.error('归档活动失败:', error)
    alert(error instanceof Error ? error.message : '归档活动失败')
  }
}

const endActivity = async () => {
  if (!activity.value) return
  try {
    await activityService.endActivity(activity.value.id)
    // 重新获取活动详情以确保状态同步
    const updated = await activityService.getActivityById(activity.value.id)
    if (updated) {
      activity.value = updated
    }
    auditStore.addLog('下线活动', activity.value?.name ?? '活动')
  } catch (error) {
    console.error('结束活动失败:', error)
  }
}

const metricsCards = computed(() => {
  if (!stats.value) return []
  return [
    { label: '访问(PV)', value: stats.value.pv || 0, hint: '页面访问次数' },
    { label: '独立访客(UV)', value: stats.value.uv || 0, hint: '独立访客数' },
    { label: '分享', value: stats.value.shares || 0, hint: '累计分享次数' },
    { label: '转化(新用户)', value: stats.value.newUsers || 0, hint: '累计新用户数(新注册/转化)' }
  ]
})

type ExportType = 'summary' | 'conversions' | 'rewards'

const exportType = ref<ExportType>('summary')
const summaryFields: ExportField[] = [
  { key: 'name', label: '活动名称', required: true },
  { key: 'status', label: '状态' },
  { key: 'startTime', label: '开始时间' },
  { key: 'endTime', label: '结束时间' },
  { key: 'visits', label: '访问' },
  { key: 'shares', label: '分享' },
  { key: 'conversions', label: '转化' },
  { key: 'budgetUsed', label: '预算消耗' }
]
const conversionFields: ExportField[] = [
  { key: 'user', label: '用户', required: true },
  { key: 'channel', label: '来源' },
  { key: 'convertedAt', label: '转化时间' },
  { key: 'reward', label: '奖励' }
]
const rewardFields: ExportField[] = [
  { key: 'user', label: '用户', required: true },
  { key: 'points', label: '积分' },
  { key: 'status', label: '状态' },
  { key: 'issuedAt', label: '发放时间' }
]

const exportFieldsMap: Record<ExportType, ExportField[]> = {
  summary: summaryFields,
  conversions: conversionFields,
  rewards: rewardFields
}

const exportStates = {
  summary: useExportFields(summaryFields, summaryFields.map((field) => field.key)),
  conversions: useExportFields(conversionFields, conversionFields.map((field) => field.key)),
  rewards: useExportFields(rewardFields, rewardFields.map((field) => field.key))
}

const exportTitle = computed(() => {
  if (exportType.value === 'summary') return '导出活动摘要字段'
  if (exportType.value === 'conversions') return '导出转化明细字段'
  return '导出奖励明细字段'
})

const currentFields = computed(() => exportFieldsMap[exportType.value])
const currentSelected = computed(() => exportStates[exportType.value].selected.value)

const setCurrentSelected = (next: string[]) => {
  exportStates[exportType.value].setSelected(next)
}

const exportData = async () => {
  const fields = currentFields.value
  const selectedKeys = currentSelected.value
  const filename = `${activity.value?.name ?? 'activity'}-${exportType.value}.csv`

  if (exportType.value === 'summary') {
    const values: Record<string, string> = {
      name: activity.value?.name ?? '',
      status: statusLabel.value,
      startTime: activity.value?.startTime ?? '',
      endTime: activity.value?.endTime ?? '',
      visits: String(stats.value?.pv ?? 0),
      shares: String(stats.value?.shares ?? 0),
      conversions: String(stats.value?.newUsers ?? 0),
      budgetUsed: '0'
    }
    const rows = fields
      .filter((field) => selectedKeys.includes(field.key))
      .map((field) => [field.label, values[field.key] ?? ''])
    downloadCsv(filename, ['字段', '值'], rows)
    auditStore.addLog('导出活动摘要', activity.value?.name ?? '')
    return
  }

  // 导出转化明细或奖励明细 - 使用真实API数据
  try {
    let exportData: { headers: string[]; rows: string[][] } | null = null

    if (exportType.value === 'conversions') {
      // 调用真实API获取参与者数据
      const activityId = Number(route.params.id)
      exportData = await service.exportActivityParticipants(activityId)
    } else if (exportType.value === 'rewards') {
      // 调用真实API获取奖励数据
      const activityId = Number(route.params.id)
      exportData = await service.exportActivityRewards(activityId)
    }

    if (exportData && exportData.rows.length > 0) {
      // 过滤选中的字段
      const fieldMap = new Map(fields.map(f => [f.key, f.label]))
      const filteredHeaders = exportData.headers.filter((_, i) => {
        const key = Object.keys(exportData!.rows[0] || {})[i]
        return selectedKeys.includes(key)
      })
      const filteredRows = exportData.rows.map(row =>
        exportData!.headers.map((h, i) => row[i])
      ).map(row =>
        row.filter((_, i) => selectedKeys.includes(Object.keys(exportData!.rows[0] || {})[i]))
      )

      downloadCsv(filename, filteredHeaders, filteredRows)
      auditStore.addLog(
        exportType.value === 'conversions' ? '导出转化明细' : '导出奖励明细',
        activity.value?.name ?? ''
      )
    } else {
      alert('暂无数据可导出')
    }
  } catch (error) {
    console.error('导出失败:', error)
    alert('导出失败: ' + (error as Error).message)
  }
}

onMounted(loadActivity)
</script>
