<template>
  <div class="results-page">
    <!-- ========== 超管端 ========== -->
    <template v-if="isSuperAdmin">
      <a-card class="title-card">
        <template #title>成果发布</template>
      </a-card>

      <!-- 统计卡片 -->
      <div class="stats-row">
        <div
          v-for="item in statsItems"
          :key="item.key"
          :class="['stat-card', { active: activeFilter === item.key }]"
          @click="handleStatClick(item.key)"
        >
          <div class="stat-icon" :style="{ background: item.bgColor }">
            <component :is="item.icon" :style="{ color: item.color }" />
          </div>
          <div class="stat-info">
            <span class="stat-count">{{ item.count }}</span>
            <span class="stat-label">{{ item.label }}</span>
          </div>
        </div>
      </div>

      <!-- 筛选栏 -->
      <div class="filter-bar">
        <a-form layout="inline" @finish="handleSuperSearch">
          <a-form-item label="活动名称">
            <a-input
              v-model:value="superSearch.contestName"
              placeholder="请输入活动名称"
              allow-clear
              style="width: 180px"
            />
          </a-form-item>
          <a-form-item label="发布状态">
            <a-select
              v-model:value="superSearch.resultState"
              placeholder="全部"
              allow-clear
              style="width: 110px"
            >
              <a-select-option value="published">已发布</a-select-option>
              <a-select-option value="unpublished">未发布</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="主办机构">
            <a-select
              v-model:value="superSearch.creatorTenantId"
              placeholder="全部机构"
              allow-clear
              show-search
              :filter-option="filterTenantOption"
              style="width: 160px"
              :options="tenantOptions"
            />
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" html-type="submit">
                <template #icon><SearchOutlined /></template>
                搜索
              </a-button>
              <a-button @click="handleSuperReset">
                <template #icon><ReloadOutlined /></template>
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>

      <!-- 表格 -->
      <a-table
        :columns="superColumns"
        :data-source="superDataSource"
        :loading="superLoading"
        :pagination="superPagination"
        row-key="id"
        @change="handleSuperTableChange"
        class="data-table"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'index'">
            {{ (superPagination.current - 1) * superPagination.pageSize + index + 1 }}
          </template>
          <template v-else-if="column.key === 'contestName'">
            <a-button
              type="link"
              size="small"
              class="contest-link"
              @click="router.push(`/${tenantCode}/contests/${record.id}/overview`)"
            >
              {{ record.contestName }}
            </a-button>
          </template>
          <template v-else-if="column.key === 'organizer'">
            {{ record.creatorTenant?.name || record.organizers || '-' }}
          </template>
          <template v-else-if="column.key === 'contestType'">
            <a-tag :color="record.contestType === 'individual' ? 'blue' : 'green'">
              {{ record.contestType === 'individual' ? '个人参与' : '团队参与' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'regCount'">
            {{ record._count?.registrations || 0 }}
          </template>
          <template v-else-if="column.key === 'workCount'">
            {{ record._count?.works || 0 }}
          </template>
          <template v-else-if="column.key === 'resultState'">
            <a-tag v-if="record.resultState === 'published'" color="green">已发布</a-tag>
            <a-tag v-else>未发布</a-tag>
          </template>
          <template v-else-if="column.key === 'resultPublishTime'">
            {{ record.resultState === 'published' ? formatDate(record.resultPublishTime) : '-' }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-button type="link" size="small" @click="handleSuperViewDetail(record)">
              查看详情
            </a-button>
          </template>
        </template>
      </a-table>
    </template>

    <!-- ========== 机构端：保持不变 ========== -->
    <template v-else>
      <a-card class="title-card">
        <template #title>成果发布</template>
      </a-card>

      <a-tabs v-model:activeKey="activeTab" class="org-tabs" @change="handleTabChange">
        <a-tab-pane key="individual" tab="个人参与" />
        <a-tab-pane key="team" tab="团队参与" />
      </a-tabs>

      <a-form :model="searchParams" layout="inline" class="filter-bar" @finish="handleSearch">
        <a-form-item label="活动名称">
          <a-input v-model:value="searchParams.contestName" placeholder="请输入活动名称" allow-clear style="width: 200px" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">
            <template #icon><SearchOutlined /></template>
            搜索
          </a-button>
          <a-button style="margin-left: 8px" @click="handleReset">
            <template #icon><ReloadOutlined /></template>
            重置
          </a-button>
        </a-form-item>
      </a-form>

      <a-table
        :columns="orgColumns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
        class="data-table"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'index'">
            {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
          </template>
          <template v-else-if="column.key === 'organizers'">
            {{ record.organizers || '-' }}
          </template>
          <template v-else-if="column.key === 'registrationCount'">
            {{ record._count?.registrations || 0 }}
          </template>
          <template v-else-if="column.key === 'worksCount'">
            {{ record._count?.works || 0 }}
          </template>
          <template v-else-if="column.key === 'resultState'">
            <a-tag v-if="record.resultState === 'published'" color="green">已发布</a-tag>
            <a-tag v-else color="default">未发布</a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-button type="link" size="small" @click="handleViewDetail(record)">详情</a-button>
          </template>
        </template>
      </a-table>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue"
import { useRouter, useRoute } from "vue-router"
import { message } from "ant-design-vue"
import { useAuthStore } from "@/stores/auth"
import {
  SearchOutlined,
  ReloadOutlined,
  TrophyOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
} from "@ant-design/icons-vue"
import {
  contestsApi,
  type Contest,
  type QueryContestParams,
} from "@/api/contests"
import { tenantsApi, type Tenant } from "@/api/tenants"
import dayjs from "dayjs"

const router = useRouter()
const route = useRoute()
const tenantCode = route.params.tenantCode as string
const authStore = useAuthStore()
const isSuperAdmin = computed(() => authStore.hasAnyRole(['super_admin']))

const formatDate = (d?: string) => d ? dayjs(d).format("YYYY-MM-DD HH:mm") : "-"

// =============================================
// 超管端逻辑
// =============================================
const activeFilter = ref<string>('')
const superLoading = ref(false)
const superDataSource = ref<Contest[]>([])
const superAllData = ref<Contest[]>([]) // 用于前端统计
const superPagination = reactive({
  current: 1, pageSize: 10, total: 0,
  showSizeChanger: true,
  showTotal: (t: number) => `共 ${t} 条`,
})
const superSearch = reactive({
  contestName: undefined as string | undefined,
  resultState: undefined as string | undefined,
  creatorTenantId: undefined as number | undefined,
})

// 统计（基于当前列表数据前端计算）
const publishedCount = ref(0)
const unpublishedCount = ref(0)

const statsItems = computed(() => [
  { key: '', label: '全部', count: publishedCount.value + unpublishedCount.value, icon: TrophyOutlined, color: '#6366f1', bgColor: 'rgba(99,102,241,0.1)' },
  { key: 'published', label: '已发布', count: publishedCount.value, icon: CheckCircleOutlined, color: '#10b981', bgColor: 'rgba(16,185,129,0.1)' },
  { key: 'unpublished', label: '未发布', count: unpublishedCount.value, icon: CloseCircleOutlined, color: '#9ca3af', bgColor: 'rgba(156,163,175,0.1)' },
])

// 租户下拉
const tenantOptions = ref<{ label: string; value: number }[]>([])
const fetchTenants = async () => {
  try {
    const res = await tenantsApi.getList({ page: 1, pageSize: 100 })
    const systemCodes = ['super', 'public', 'judge', 'teacher', 'student', 'school']
    tenantOptions.value = res.list
      .filter((t: Tenant) => !t.isSuper && !systemCodes.includes(t.code))
      .map((t: Tenant) => ({ label: t.name, value: t.id }))
  } catch { /* 静默 */ }
}
const filterTenantOption = (input: string, option: any) => option.label?.toLowerCase().includes(input.toLowerCase())

const fetchSuperStats = async () => {
  // 获取所有活动统计发布状态
  try {
    const res = await contestsApi.getList({ page: 1, pageSize: 100, contestState: 'published' })
    publishedCount.value = res.list.filter((c) => c.resultState === 'published').length
    unpublishedCount.value = res.list.filter((c) => c.resultState !== 'published').length
  } catch { /* 静默 */ }
}

const fetchSuperList = async () => {
  superLoading.value = true
  try {
    const params: QueryContestParams = {
      page: superPagination.current,
      pageSize: superPagination.pageSize,
      contestName: superSearch.contestName,
      contestState: 'published', // 成果发布只看已发布的活动
      creatorTenantId: superSearch.creatorTenantId,
    }
    const res = await contestsApi.getList(params)

    // 前端过滤发布状态
    let list = res.list
    if (superSearch.resultState) {
      list = list.filter((c) =>
        superSearch.resultState === 'published'
          ? c.resultState === 'published'
          : c.resultState !== 'published'
      )
    }

    superDataSource.value = list
    superPagination.total = superSearch.resultState ? list.length : res.total
  } catch {
    message.error('获取成果列表失败')
  } finally {
    superLoading.value = false
  }
}

const handleStatClick = (key: string) => {
  activeFilter.value = key
  superSearch.resultState = key || undefined
  superPagination.current = 1
  fetchSuperList()
}

const handleSuperSearch = () => {
  superPagination.current = 1
  fetchSuperList()
}

const handleSuperReset = () => {
  superSearch.contestName = undefined
  superSearch.resultState = undefined
  superSearch.creatorTenantId = undefined
  activeFilter.value = ''
  superPagination.current = 1
  fetchSuperList()
  fetchSuperStats()
}

const handleSuperTableChange = (pag: any) => {
  superPagination.current = pag.current
  superPagination.pageSize = pag.pageSize
  fetchSuperList()
}

const handleSuperViewDetail = (record: Contest) => {
  router.push(`/${tenantCode}/contests/results/${record.id}`)
}

const superColumns = [
  { title: '序号', key: 'index', width: 60 },
  { title: '活动名称', key: 'contestName', width: 200 },
  { title: '主办机构', key: 'organizer', width: 120 },
  { title: '活动类型', key: 'contestType', width: 90 },
  { title: '报名', key: 'regCount', width: 70 },
  { title: '作品', key: 'workCount', width: 70 },
  { title: '发布状态', key: 'resultState', width: 90 },
  { title: '发布时间', key: 'resultPublishTime', width: 150 },
  { title: '操作', key: 'action', width: 100, fixed: 'right' as const },
]

// =============================================
// 机构端逻辑（保持不变）
// =============================================
const activeTab = ref<'individual' | 'team'>('individual')
const loading = ref(false)
const dataSource = ref<Contest[]>([])
const pagination = reactive({ current: 1, pageSize: 10, total: 0 })
const searchParams = reactive<QueryContestParams>({ contestName: '' })

const orgColumns = [
  { title: '序号', key: 'index', width: 70 },
  { title: '活动名称', key: 'contestName', dataIndex: 'contestName', width: 250 },
  { title: '主办机构', key: 'organizers', width: 140 },
  { title: '报名人数', key: 'registrationCount', width: 100 },
  { title: '提交作品数', key: 'worksCount', width: 100 },
  { title: '发布状态', key: 'resultState', width: 100 },
  { title: '操作', key: 'action', width: 100, fixed: 'right' as const },
]

const fetchList = async () => {
  loading.value = true
  try {
    const res = await contestsApi.getList({
      ...searchParams,
      contestType: activeTab.value,
      page: pagination.current,
      pageSize: pagination.pageSize,
    })
    dataSource.value = res.list
    pagination.total = res.total
  } catch { message.error('获取列表失败') }
  finally { loading.value = false }
}

const handleTabChange = () => { pagination.current = 1; fetchList() }
const handleSearch = () => { pagination.current = 1; fetchList() }
const handleReset = () => { searchParams.contestName = ''; pagination.current = 1; fetchList() }
const handleTableChange = (pag: any) => { pagination.current = pag.current; pagination.pageSize = pag.pageSize; fetchList() }
const handleViewDetail = (record: Contest) => { router.push(`/${tenantCode}/contests/results/${record.id}`) }

// =============================================
// 初始化
// =============================================
onMounted(() => {
  if (isSuperAdmin.value) {
    fetchTenants()
    fetchSuperStats()
    fetchSuperList()
  } else {
    fetchList()
  }
})
</script>

<style scoped lang="scss">
$primary: #6366f1;

.title-card {
  margin-bottom: 16px;
  border: none;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  :deep(.ant-card-head) { border-bottom: none; .ant-card-head-title { font-size: 18px; font-weight: 600; } }
  :deep(.ant-card-body) { padding: 0; }
}

.stats-row { display: flex; gap: 12px; margin-bottom: 16px; }

.stat-card {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 14px 16px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.2s;
  &:hover { box-shadow: 0 4px 16px rgba($primary, 0.12); }
  &.active { border-color: $primary; background: rgba($primary, 0.02); }
  .stat-icon { width: 36px; height: 36px; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 16px; flex-shrink: 0; }
  .stat-info { display: flex; flex-direction: column; .stat-count { font-size: 18px; font-weight: 700; color: #1e1b4b; line-height: 1.2; } .stat-label { font-size: 12px; color: #9ca3af; } }
}

.filter-bar {
  padding: 20px 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  margin-bottom: 16px;
}

.data-table {
  :deep(.ant-table-wrapper) {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
    overflow: hidden;
    .ant-table-thead > tr > th { background: #fafafa; font-weight: 600; }
    .ant-table-tbody > tr:hover > td { background: rgba($primary, 0.03); }
    .ant-table-pagination { padding: 16px; margin: 0; }
  }
}

.contest-link { padding: 0; text-align: left; }
.text-muted { color: #d1d5db; }

.org-tabs {
  background: #fff;
  padding: 0 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  margin-bottom: 16px;
}
</style>
