<template>
  <div class="contests-page">
    <a-card class="title-card">
      <template #title>活动列表</template>
      <template #extra>
        <a-button
          v-if="!isSuperAdmin"
          v-permission="'contest:create'"
          type="primary"
          @click="handleAdd"
        >
          <template #icon><PlusOutlined /></template>
          创建活动
        </a-button>
      </template>
    </a-card>

    <!-- 超管统计卡片 -->
    <div v-if="isSuperAdmin" class="stats-row">
      <div
        v-for="item in statsItems"
        :key="item.stage"
        :class="['stat-card', { active: activeStage === item.stage }]"
        @click="handleStatClick(item.stage)"
      >
        <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>

    <!-- 搜索表单 -->
    <a-form
      :model="searchParams"
      layout="inline"
      class="search-form"
      @finish="handleSearch"
    >
      <a-form-item label="活动名称">
        <a-input
          v-model:value="searchParams.contestName"
          placeholder="请输入活动名称"
          allow-clear
          style="width: 180px"
        />
      </a-form-item>
      <a-form-item v-if="!isSuperAdmin" label="活动状态">
        <a-select
          v-model:value="searchParams.contestState"
          placeholder="请选择状态"
          allow-clear
          style="width: 120px"
        >
          <a-select-option value="published">已发布</a-select-option>
          <a-select-option value="unpublished">未发布</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item v-if="isSuperAdmin" label="活动阶段">
        <a-select
          v-model:value="searchParams.stage"
          placeholder="全部阶段"
          allow-clear
          style="width: 120px"
        >
          <a-select-option value="unpublished">未发布</a-select-option>
          <a-select-option value="registering">报名中</a-select-option>
          <a-select-option value="submitting">征稿中</a-select-option>
          <a-select-option value="reviewing">评审中</a-select-option>
          <a-select-option value="finished">已结束</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="活动类型">
        <a-select
          v-model:value="searchParams.contestType"
          placeholder="请选择类型"
          allow-clear
          style="width: 120px"
        >
          <a-select-option value="individual">个人参与</a-select-option>
          <a-select-option value="team">团队参与</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="可见范围">
        <a-select
          v-model:value="searchParams.visibility"
          placeholder="全部"
          allow-clear
          style="width: 120px"
        >
          <a-select-option value="public">公开</a-select-option>
          <a-select-option value="targeted">定向推送</a-select-option>
          <a-select-option value="designated">指定机构</a-select-option>
          <a-select-option value="internal">仅内部</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item v-if="isSuperAdmin" label="主办机构">
        <a-select
          v-model:value="searchParams.creatorTenantId"
          placeholder="全部机构"
          allow-clear
          show-search
          :filter-option="filterTenantOption"
          style="width: 160px"
          :options="tenantOptions"
        />
      </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="currentColumns"
      :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 === 'organizer'">
          <span v-if="isSuperAdmin && record.creatorTenant">
            {{ record.creatorTenant.name }}
          </span>
          <span v-else-if="record.organizers">
            {{ typeof record.organizers === 'string' ? record.organizers : (Array.isArray(record.organizers) ? record.organizers[0] : '-') }}
          </span>
          <span v-else class="text-muted">-</span>
        </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 === 'stage'">
          <a-tag :color="stageTagMap[record.stage]?.color || 'default'">
            {{ stageTagMap[record.stage]?.label || '已发布' }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'contestState'">
          <a-tag :color="record.contestState === 'published' ? 'success' : 'default'">
            {{ record.contestState === "published" ? "已发布" : "未发布" }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'visibility'">
          <a-tag v-if="record.visibility === 'public'" color="green">公开</a-tag>
          <a-tag v-else-if="record.visibility === 'targeted'" color="orange">
            <a-tooltip>
              <template #title>
                <div v-if="record.targetCities?.length">城市：{{ record.targetCities.join('、') }}</div>
                <div v-if="record.ageMin || record.ageMax">年龄：{{ record.ageMin || 0 }}-{{ record.ageMax || '不限' }}岁</div>
                <div v-if="!record.targetCities?.length && !record.ageMin && !record.ageMax">无附加条件</div>
              </template>
              定向推送
            </a-tooltip>
          </a-tag>
          <a-tag v-else-if="record.visibility === 'internal'" color="default">仅内部</a-tag>
          <a-tag v-else color="blue">指定机构</a-tag>
        </template>
        <template v-else-if="column.key === 'publicScope'">
          <template v-if="record.contestTenants && record.contestTenants.length > 0">
            <a-tooltip>
              <template #title>
                <div v-for="tenantId in record.contestTenants" :key="tenantId">
                  {{ getTenantName(tenantId) }}
                </div>
              </template>
              <a-tag>{{ record.contestTenants.length }}个机构</a-tag>
            </a-tooltip>
          </template>
          <span v-else class="text-muted">-</span>
        </template>
        <template v-else-if="column.key === 'regCount'">
          <a-button
            v-if="isSuperAdmin && record._count?.registrations > 0"
            type="link"
            size="small"
            class="count-link"
            @click="goToRegistrations(record.id)"
          >
            {{ record._count.registrations }}
          </a-button>
          <span v-else-if="record._count?.registrations > 0">{{ record._count.registrations }}</span>
          <span v-else class="text-muted">0</span>
        </template>
        <template v-else-if="column.key === 'workCount'">
          <a-button
            v-if="isSuperAdmin && record._count?.works > 0"
            type="link"
            size="small"
            class="count-link"
            @click="goToWorks(record.id)"
          >
            {{ record._count.works }}
          </a-button>
          <span v-else-if="record._count?.works > 0">{{ record._count.works }}</span>
          <span v-else class="text-muted">0</span>
        </template>
        <template v-else-if="column.key === 'reviewProgress'">
          <span v-if="record.totalWorksCount > 0">
            <span :class="{ 'text-success': record.reviewedCount === record.totalWorksCount }">
              {{ record.reviewedCount }}
            </span>
            <span class="text-muted">/{{ record.totalWorksCount }}</span>
          </span>
          <span v-else class="text-muted">-</span>
        </template>
        <template v-else-if="column.key === 'judges'">
          <a-tag v-if="record._count?.judges > 0" color="blue">
            {{ record._count.judges }}人
          </a-tag>
          <span v-else class="text-muted">-</span>
        </template>
        <template v-else-if="column.key === 'contestTime'">
          <div v-if="record.startTime || record.endTime">
            <div>{{ formatDate(record.startTime) }}</div>
            <div>至 {{ formatDate(record.endTime) }}</div>
          </div>
          <span v-else class="text-muted">-</span>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <template v-if="!isSuperAdmin">
              <a-button v-permission="'contest:publish'" type="link" size="small" @click="handlePublishClick(record)">
                {{ record.contestState === "published" ? "取消发布" : "发布" }}
              </a-button>
              <a-button v-permission="'contest:update'" type="link" size="small" @click="handleAddJudge(record.id)">
                添加评委
              </a-button>
              <a-button v-permission="'contest:update'" type="link" size="small" @click.stop="handleEdit(record.id)">
                编辑
              </a-button>
              <a-button v-permission="'contest:delete'" type="link" danger size="small" @click="handleDeleteClick(record)">
                删除
              </a-button>
            </template>
            <a-button
              v-if="isSuperAdmin"
              type="link"
              size="small"
              @click="router.push(`/${tenantCode}/contests/${record.id}/overview`)"
            >
              查看详情
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 添加评委侧边弹框 -->
    <a-drawer
      v-model:open="judgeDrawerVisible"
      title="添加评委"
      placement="right"
      width="800px"
      @close="handleJudgeDrawerClose"
    >
      <AddJudgeDrawer
        v-if="currentContestId && currentContest"
        :contest-id="currentContestId"
        :contest="currentContest"
        @success="handleJudgeAddSuccess"
      />
    </a-drawer>

    <!-- 发布弹框 -->
    <a-modal
      v-model:open="publishModalVisible"
      title="发布活动"
      :confirm-loading="publishLoading"
      @ok="handlePublishConfirm"
    >
      <a-form layout="vertical">
        <a-form-item label="选择公开范围（可见机构）" required>
          <a-select
            v-model:value="selectedTenants"
            mode="multiple"
            placeholder="请选择公开范围"
            style="width: 100%"
            :options="tenantOptions"
            :filter-option="filterTenantOption"
            show-search
          />
        </a-form-item>
      </a-form>
      <a-alert type="warning" message="发布后，只有选中的机构可以看到此活动" show-icon class="mt-2" />
    </a-modal>

    <!-- 取消发布确认弹框 -->
    <a-modal
      v-model:open="unpublishModalVisible"
      title="取消发布"
      :confirm-loading="publishLoading"
      @ok="handleUnpublishConfirm"
    >
      <p>确定要取消发布活动「{{ currentPublishContest?.contestName }}」吗？</p>
      <a-alert type="warning" message="取消发布后，所有机构将无法看到此活动" show-icon />
    </a-modal>

    <!-- 删除确认弹框 -->
    <a-modal
      v-model:open="deleteModalVisible"
      title="删除活动"
      :confirm-loading="deleteLoading"
      @ok="handleDeleteConfirm"
    >
      <p>确定要删除活动「{{ currentDeleteContest?.contestName }}」吗？</p>
      <a-alert type="error" message="删除后数据将无法恢复，请谨慎操作！" show-icon />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { useRouter, useRoute } from "vue-router"
import { ref, computed, reactive, onMounted } from "vue"
import { message } from "ant-design-vue"
import { useAuthStore } from "@/stores/auth"
import {
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
  AppstoreOutlined,
  FormOutlined,
  EditOutlined,
  EyeOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
} from "@ant-design/icons-vue"
import {
  contestsApi,
  type Contest,
  type QueryContestParams,
  type ContestStats,
} from "@/api/contests"
import { tenantsApi, type Tenant } from "@/api/tenants"
import AddJudgeDrawer from "./components/AddJudgeDrawer.vue"
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 stats = ref<ContestStats>({ total: 0, unpublished: 0, registering: 0, submitting: 0, reviewing: 0, finished: 0 })
const activeStage = ref<string>('')

const statsItems = computed(() => [
  { stage: '', label: '全部', count: stats.value.total, icon: AppstoreOutlined, color: '#6366f1', bgColor: 'rgba(99,102,241,0.1)' },
  { stage: 'registering', label: '报名中', count: stats.value.registering, icon: FormOutlined, color: '#3b82f6', bgColor: 'rgba(59,130,246,0.1)' },
  { stage: 'submitting', label: '征稿中', count: stats.value.submitting, icon: EditOutlined, color: '#10b981', bgColor: 'rgba(16,185,129,0.1)' },
  { stage: 'reviewing', label: '评审中', count: stats.value.reviewing, icon: EyeOutlined, color: '#f59e0b', bgColor: 'rgba(245,158,11,0.1)' },
  { stage: 'finished', label: '已结束', count: stats.value.finished, icon: CheckCircleOutlined, color: '#6b7280', bgColor: 'rgba(107,114,128,0.1)' },
  { stage: 'unpublished', label: '未发布', count: stats.value.unpublished, icon: CloseCircleOutlined, color: '#9ca3af', bgColor: 'rgba(156,163,175,0.1)' },
])

const fetchStats = async () => {
  try {
    stats.value = await contestsApi.getStats()
  } catch { /* 静默 */ }
}

const handleStatClick = (stage: string) => {
  activeStage.value = stage
  searchParams.stage = stage || undefined
  handleSearch()
}

// ========== 列表 ==========
const loading = ref(false)
const dataSource = ref<Contest[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (t: number) => `共 ${t} 条`,
})

const searchParams = reactive<QueryContestParams>({})

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

const handleSearch = () => {
  pagination.current = 1
  fetchList()
}

const handleReset = () => {
  Object.keys(searchParams).forEach((key) => {
    ;(searchParams as any)[key] = undefined
  })
  activeStage.value = ''
  pagination.current = 1
  fetchList()
}

const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchList()
}

// ========== 租户 ==========
const tenants = ref<Tenant[]>([])
const tenantOptions = ref<{ label: string; value: number }[]>([])

const fetchTenants = async () => {
  try {
    const response = await tenantsApi.getList({ page: 1, pageSize: 100 })
    tenants.value = response.list
    // 主办机构筛选：排除所有系统租户，只保留真正的机构（如广东省图）
    const systemCodes = ['super', 'public', 'judge', 'teacher', 'student', 'school']
    tenantOptions.value = response.list
      .filter((t) => !t.isSuper && !systemCodes.includes(t.code))
      .map((t) => ({ label: t.name, value: t.id }))
  } catch { /* 静默 */ }
}

const getTenantName = (tenantId: number) => {
  const tenant = tenants.value.find((t) => t.id === tenantId)
  return tenant?.name || `机构${tenantId}`
}

const filterTenantOption = (input: string, option: any) => {
  return option.label?.toLowerCase().includes(input.toLowerCase())
}

// ========== 表格列定义 ==========
const superColumns = [
  { title: "序号", key: "index", width: 60 },
  { title: "活动名称", dataIndex: "contestName", key: "contestName", width: 200 },
  { title: "主办机构", key: "organizer", width: 120 },
  { title: "活动类型", key: "contestType", width: 90 },
  { title: "活动阶段", key: "stage", width: 100 },
  { title: "可见范围", key: "visibility", width: 90 },
  { title: "报名", key: "regCount", width: 70 },
  { title: "作品", key: "workCount", width: 70 },
  { title: "评审", key: "reviewProgress", width: 80 },
  { title: "活动时间", key: "contestTime", width: 160 },
  { title: "操作", key: "action", width: 100, fixed: "right" as const },
]

const orgColumns = [
  { title: "序号", key: "index", width: 70 },
  { title: "活动名称", dataIndex: "contestName", key: "contestName", width: 200 },
  { title: "主办方", key: "organizer", width: 140 },
  { title: "活动类型", key: "contestType", width: 100 },
  { title: "活动状态", key: "contestState", width: 100 },
  { title: "可见范围", key: "visibility", width: 100 },
  { title: "公开机构", key: "publicScope", width: 120 },
  { title: "报名", key: "regCount", width: 70 },
  { title: "作品", key: "workCount", width: 70 },
  { title: "评委", key: "judges", width: 70 },
  { title: "活动时间", key: "contestTime", width: 180 },
  { title: "操作", key: "action", width: 260, fixed: "right" as const },
]

const currentColumns = computed(() => isSuperAdmin.value ? superColumns : orgColumns)

// ========== 阶段标签 ==========
const stageTagMap: Record<string, { label: string; color: string }> = {
  unpublished: { label: '未发布', color: 'default' },
  published: { label: '已发布', color: 'blue' },
  registering: { label: '报名中', color: 'processing' },
  submitting: { label: '征稿中', color: 'success' },
  reviewing: { label: '评审中', color: 'warning' },
  finished: { label: '已结束', color: 'default' },
}

// ========== 超管跳转 ==========
const goToRegistrations = (contestId: number) => {
  router.push(`/${tenantCode}/contests/registrations?contestId=${contestId}`)
}
const goToWorks = (contestId: number) => {
  router.push(`/${tenantCode}/contests/works/${contestId}/list`)
}

// ========== 工具函数 ==========
const formatDate = (dateStr?: string) => {
  if (!dateStr) return "-"
  return dayjs(dateStr).format("YYYY-MM-DD HH:mm")
}

// ========== 机构端操作（超管不可见）==========
const handleAdd = () => {
  router.push(`/${tenantCode}/contests/create`)
}

const handleEdit = (id: number) => {
  if (!id) { message.warning("活动ID不存在"); return }
  router.push(`/${tenantCode}/contests/${id}/edit`)
}

// 添加评委
const judgeDrawerVisible = ref(false)
const currentContestId = ref<number | null>(null)
const currentContest = ref<Contest | null>(null)

const handleAddJudge = async (id: number) => {
  currentContestId.value = id
  try {
    currentContest.value = await contestsApi.getDetail(id)
    judgeDrawerVisible.value = true
  } catch (error: any) {
    message.error(error?.response?.data?.message || "获取活动信息失败")
  }
}

const handleJudgeDrawerClose = () => {
  judgeDrawerVisible.value = false
  currentContestId.value = null
  currentContest.value = null
}

const handleJudgeAddSuccess = () => {
  message.success("添加评委成功")
  fetchList()
  handleJudgeDrawerClose()
}

// 发布
const publishModalVisible = ref(false)
const unpublishModalVisible = ref(false)
const publishLoading = ref(false)
const currentPublishContest = ref<Contest | null>(null)
const selectedTenants = ref<number[]>([])

const handlePublishClick = async (record: Contest) => {
  currentPublishContest.value = record
  if (record.contestState === "published") {
    unpublishModalVisible.value = true
  } else {
    try {
      const contest = await contestsApi.getDetail(record.id)
      selectedTenants.value = Array.isArray(contest.contestTenants)
        ? contest.contestTenants.map((id) => Number(id)).filter((id) => !isNaN(id))
        : []
      publishModalVisible.value = true
    } catch (error: any) {
      message.error(error?.response?.data?.message || "获取活动信息失败")
    }
  }
}

const handlePublishConfirm = async () => {
  if (selectedTenants.value.length === 0) { message.warning("请至少选择一个公开范围"); return }
  publishLoading.value = true
  try {
    await contestsApi.update(currentPublishContest.value!.id, { contestTenants: selectedTenants.value })
    await contestsApi.publish(currentPublishContest.value!.id, "published")
    message.success("发布成功")
    publishModalVisible.value = false
    fetchList()
    if (isSuperAdmin.value) fetchStats()
  } catch (error: any) {
    message.error(error?.response?.data?.message || "发布失败")
  } finally { publishLoading.value = false }
}

const handleUnpublishConfirm = async () => {
  publishLoading.value = true
  try {
    await contestsApi.publish(currentPublishContest.value!.id, "unpublished")
    message.success("取消发布成功")
    unpublishModalVisible.value = false
    fetchList()
    if (isSuperAdmin.value) fetchStats()
  } catch (error: any) {
    message.error(error?.response?.data?.message || "取消发布失败")
  } finally { publishLoading.value = false }
}

// 删除
const deleteModalVisible = ref(false)
const deleteLoading = ref(false)
const currentDeleteContest = ref<Contest | null>(null)

const handleDeleteClick = (record: Contest) => {
  currentDeleteContest.value = record
  deleteModalVisible.value = true
}

const handleDeleteConfirm = async () => {
  deleteLoading.value = true
  try {
    await contestsApi.delete(currentDeleteContest.value!.id)
    message.success("删除成功")
    deleteModalVisible.value = false
    fetchList()
    if (isSuperAdmin.value) fetchStats()
  } catch (error: any) {
    message.error(error?.response?.data?.message || "删除失败")
  } finally { deleteLoading.value = false }
}

onMounted(() => {
  fetchList()
  fetchTenants()
  if (isSuperAdmin.value) fetchStats()
})
</script>

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

.contests-page {
  .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; }
  }

  :deep(.ant-btn-primary) {
    background: linear-gradient(135deg, $primary 0%, darken($primary, 10%) 100%);
    border: none;
    box-shadow: 0 4px 12px rgba($primary, 0.35);
    &:hover {
      box-shadow: 0 6px 16px rgba($primary, 0.45);
      transform: translateY(-1px);
    }
  }
}

// 统计卡片
.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 ease;

  &: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; }
  }
}

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

// 表格
.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; }
  }
}

.count-link { padding: 0; font-weight: 600; }
.text-muted { color: #d1d5db; }
.text-success { color: #10b981; font-weight: 600; }
.mt-2 { margin-top: 8px; }
</style>
