<template>
  <div class="contests-page">
    <a-card class="mb-4">
      <template #title>赛事列表</template>
      <template #extra>
        <a-button
          v-permission="'contest:create'"
          type="primary"
          @click="handleAdd"
        >
          <template #icon><PlusOutlined /></template>
          创建比赛
        </a-button>
      </template>
    </a-card>

    <!-- 搜索表单 -->
    <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: 200px"
        />
      </a-form-item>
      <a-form-item 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 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>
        <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="columns"
      :data-source="dataSource"
      :loading="loading"
      :pagination="pagination"
      row-key="id"
      @change="handleTableChange"
    >
      <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 === 'contestType'">
          <a-tag
            :color="record.contestType === 'individual' ? 'blue' : 'green'"
          >
            {{ record.contestType === "individual" ? "个人赛" : "团队赛" }}
          </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 === '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>-</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>-</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>-</span>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <!-- 发布/取消发布 -->
            <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>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 添加评委侧边弹框 -->
    <a-drawer
      v-model:open="judgeDrawerVisible"
      title="添加评委"
      placement="right"
      width="800px"
      :footer-style="{ textAlign: 'right' }"
      @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, onMounted } from "vue"
import { message } from "ant-design-vue"
import {
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
} from "@ant-design/icons-vue"
import { useListRequest } from "@/composables/useListRequest"
import {
  contestsApi,
  type Contest,
  type QueryContestParams,
} 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 {
  loading,
  dataSource,
  pagination,
  searchParams,
  fetchList,
  resetSearch,
  search,
  handleTableChange,
} = useListRequest<Contest, QueryContestParams>({
  requestFn: contestsApi.getList,
  defaultSearchParams: {} as QueryContestParams,
  defaultPageSize: 10,
  errorMessage: "获取赛事列表失败",
})

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

// 表格列定义
const columns = [
  { title: "序号", key: "index", width: 70 },
  {
    title: "赛事名称",
    dataIndex: "contestName",
    key: "contestName",
    width: 200,
  },
  { title: "赛事类型", key: "contestType", width: 100 },
  { title: "赛事状态", key: "contestState", width: 100 },
  { title: "公开范围", key: "publicScope", width: 120 },
  { title: "评委", key: "judges", width: 80 },
  { title: "赛事时间", key: "contestTime", width: 180 },
  { title: "操作", key: "action", width: 260, fixed: "right" as const },
]

// 格式化日期
const formatDate = (dateStr?: string) => {
  if (!dateStr) return "-"
  return dayjs(dateStr).format("YYYY-MM-DD HH:mm")
}

// 获取租户名称
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().indexOf(input.toLowerCase()) >= 0
}

// 获取租户列表
const fetchTenants = async () => {
  try {
    const response = await tenantsApi.getList({ page: 1, pageSize: 100 })
    tenants.value = response.list
    tenantOptions.value = response.list.map((t) => ({
      label: t.name,
      value: t.id,
    }))
  } catch (error) {
    console.error("获取租户列表失败", error)
  }
}

// 搜索
const handleSearch = () => {
  search()
}

// 重置搜索
const handleReset = () => {
  resetSearch()
}

// 新增
const handleAdd = () => {
  router.push(`/${tenantCode}/contests/create`)
}

// 编辑
const handleEdit = (id: number) => {
  if (!id) {
    message.warning("赛事ID不存在")
    return
  }
  const path = `/${tenantCode}/contests/${id}/edit`
  router.push(path).catch((error) => {
    console.error("路由跳转失败:", error)
    message.error("跳转到编辑页面失败，请检查权限或联系管理员")
  })
}

// 添加评委相关
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 {
    const contest = await contestsApi.getDetail(id)
    currentContest.value = contest
    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 {
    // 发布 - 打开选择租户弹框
    // 从后端获取最新数据，确保 contestTenants 正确解析
    try {
      const contest = await contestsApi.getDetail(record.id)
      // 确保 contestTenants 是数字数组，处理 null、undefined 和字符串数组的情况
      if (
        Array.isArray(contest.contestTenants) &&
        contest.contestTenants.length > 0
      ) {
        selectedTenants.value = contest.contestTenants
          .map((id) => Number(id))
          .filter((id) => !isNaN(id))
      } else {
        selectedTenants.value = []
      }
      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()
  } 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()
  } 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()
  } catch (error: any) {
    message.error(error?.response?.data?.message || "删除失败")
  } finally {
    deleteLoading.value = false
  }
}

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

<style scoped lang="scss">
// 主色调
$primary: #1890ff;
$primary-dark: #0958d9;
$gradient-primary: linear-gradient(135deg, $primary 0%, $primary-dark 100%);

.contests-page {
  // 标题卡片样式
  :deep(.ant-card) {
    border: none;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

    .ant-card-head {
      border-bottom: none;
      padding: 16px 24px;

      .ant-card-head-title {
        font-size: 18px;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.85);
      }
    }

    .ant-card-body {
      padding: 0;
    }
  }

  // 渐变主按钮样式
  :deep(.ant-btn-primary) {
    background: $gradient-primary;
    border: none;
    box-shadow: 0 4px 12px rgba($primary, 0.35);
    transition: all 0.3s ease;

    &:hover {
      background: linear-gradient(135deg, $primary-dark 0%, darken($primary-dark, 8%) 100%);
      box-shadow: 0 6px 16px rgba($primary, 0.45);
      transform: translateY(-1px);
    }

    &:active {
      transform: translateY(0);
    }
  }

  // 表格样式
  :deep(.ant-table-wrapper) {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    overflow: hidden;

    .ant-table {
      .ant-table-thead > tr > th {
        background: #fafafa;
        font-weight: 600;
        color: rgba(0, 0, 0, 0.85);
        border-bottom: 1px solid #f0f0f0;
      }

      .ant-table-tbody > tr {
        transition: all 0.2s ease;

        &:hover > td {
          background: rgba($primary, 0.04);
        }

        > td {
          border-bottom: 1px solid #f5f5f5;
        }
      }
    }

    .ant-table-pagination {
      padding: 16px;
      margin: 0;
    }
  }
}

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

.mb-4 {
  margin-bottom: 16px;
}

.mt-2 {
  margin-top: 8px;
}
</style>
