<template>
  <div class="judge-invite-container">
    <!-- 搜索表单 -->
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="选择赛事">
          <el-select
            v-model="queryParams.competitionId"
            placeholder="请选择赛事"
            clearable
            filterable
            :loading="competitionLoading"
            :disabled="competitionLoading"
            style="width: 250px"
            @change="handleCompetitionChange"
          >
            <template #empty>
              <div style="padding: 20px; text-align: center; color: #909399;">
                <p>暂无赛事数据</p>
                <p style="font-size: 12px; margin-top: 5px;">
                  请先在"赛事管理"中创建赛事
                </p>
              </div>
            </template>
            <el-option
              v-for="item in competitionList"
              :key="item.id"
              :label="item.competitionName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="评委姓名">
          <el-input
            v-model="queryParams.judgeName"
            placeholder="请输入评委姓名"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="评委等级">
          <el-select
            v-model="queryParams.judgeLevel"
            placeholder="请选择等级"
            clearable
            style="width: 130px"
          >
            <el-option label="国家级" value="国家级" />
            <el-option label="一级" value="一级" />
            <el-option label="二级" value="二级" />
            <el-option label="三级" value="三级" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 工具栏 -->
    <el-card shadow="never" class="toolbar-card">
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button
            type="warning"
            :icon="FolderOpened"
            :disabled="competitionLoading || queryParams.competitionId === null || queryParams.competitionId === ''"
            :loading="competitionLoading"
            @click="handleImportFromPool"
          >
            从评委库导入
          </el-button>
          <el-button
            :icon="Download"
            :disabled="competitionLoading || queryParams.competitionId === null || queryParams.competitionId === ''"
            @click="handleExport"
          >
            导出数据
          </el-button>
        </div>
        <div class="toolbar-right">
          <el-tooltip content="刷新" placement="top">
            <el-button circle :icon="Refresh" :disabled="competitionLoading" @click="fetchData" />
          </el-tooltip>
        </div>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never" class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="judgeName" label="评委姓名" />
        <el-table-column prop="judgeLevel" label="评委等级" align="center">
          <template #default="{ row }">
            <el-tag :type="getLevelType(row.judgeLevel)" size="small">
              {{ row.judgeLevel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="inviteCode" label="邀请码" align="center">
          <template #default="{ row }">
            <!-- 已有邀请码：显示邀请码 + 重新生成按钮 -->
            <div v-if="row.inviteCode" style="display: flex; align-items: center; justify-content: center; gap: 8px;">
              <el-tag
                type="warning"
                effect="dark"
                size="default"
                style="font-family: monospace; font-weight: bold; cursor: pointer;"
                @click="copyToClipboard(row.inviteCode, '邀请码')"
                title="点击复制"
              >
                {{ row.inviteCode }}
              </el-tag>
              <el-button
                link
                type="primary"
                size="small"
                @click="handleRegenerateCode(row)"
                title="重新生成邀请码"
              >
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>

            <!-- 未生成邀请码：显示生成按钮 -->
            <el-button
              v-else
              type="primary"
              size="small"
              @click="handleGenerateCode(row)"
            >
              生成邀请码
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="venueName" label="负责场地" align="center">
          <template #default="{ row }">
            <span>{{ row.venueName || "全部场地" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="refereeType" label="裁判类型" align="center">
          <template #default="{ row }">
            <el-tag :type="row.refereeType === 1 ? 'danger' : (row.refereeType === 3 ? 'warning' : 'primary')" size="small">
              {{ row.refereeType === 1 ? '主裁判' : (row.refereeType === 3 ? '总裁' : '裁判员') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="contactPhone" label="联系电话" />
        <el-table-column prop="contactEmail" label="擅长项目" show-overflow-tooltip />
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" :icon="View" @click="handleView(row)">
              查看
            </el-button>
            <el-button link type="danger" :icon="Delete" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchData"
          @current-change="fetchData"
        />
      </div>
    </el-card>

    <!-- 裁判选择对话框 -->
    <el-dialog
      v-model="judgeDialogVisible"
      title="从评委库导入"
      width="900px"
      :close-on-click-modal="false"
    >
      <!-- 场地和项目选择 -->
      <el-form :inline="true" class="venue-project-form" style="margin-bottom: 15px; padding: 15px; background: #f5f7fa; border-radius: 8px;">
        <el-form-item label="分配场地" required>
          <el-select
            v-model="importForm.venueId"
            placeholder="请选择场地"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in venueList"
              :key="item.id"
              :label="item.venueName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

      </el-form>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="judgeQueryParams" class="judge-search-form">
        <el-form-item label="姓名">
          <el-input
            v-model="judgeQueryParams.name"
            placeholder="请输入姓名"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="judgeQueryParams.phone"
            placeholder="请输入手机号"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="裁判类型">
          <el-select
            v-model="judgeQueryParams.refereeType"
            placeholder="请选择"
            clearable
            style="width: 130px"
          >
            <el-option label="主裁判" :value="1" />
            <el-option label="裁判员" :value="2" />
            <el-option label="总裁" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleJudgeSearch">
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="handleJudgeReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 裁判列表 -->
      <el-table
        v-loading="judgeLoading"
        :data="judgeList"
        stripe
        border
        max-height="400"
        @selection-change="handleJudgeSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="{ row }">
            {{ row.gender === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column prop="refereeType" label="裁判类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.refereeType === 1 ? 'danger' : (row.refereeType === 3 ? 'warning' : 'primary')" size="small">
              {{ row.refereeType === 1 ? '主裁判' : (row.refereeType === 3 ? '总裁' : '裁判员') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="等级/职称" width="120" />
        <el-table-column prop="specialty" label="擅长项目" min-width="150" show-overflow-tooltip />
      </el-table>

      <!-- 分页 -->
      <div class="judge-pagination">
        <el-pagination
          v-model:current-page="judgeQueryParams.current"
          v-model:page-size="judgeQueryParams.size"
          :page-sizes="[10, 20, 50]"
          :total="judgeTotal"
          layout="total, sizes, prev, pager, next"
          @size-change="loadJudgeList"
          @current-change="loadJudgeList"
        />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <span style="margin-right: auto; color: #909399;">
            已选择 {{ selectedJudges.length }} 位裁判
          </span>
          <el-button @click="judgeDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :disabled="selectedJudges.length === 0"
            @click="handleConfirmImport"
          >
            确定导入
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Delete,
  Download,
  FolderOpened,
  View,
} from '@element-plus/icons-vue'
import {
  getJudgeInviteList,
  getInviteStatistics,
  exportInvites,
  generateInviteCode,
  batchGenerateInviteCode,
  regenerateInviteCode,
  removeInvite
} from '@/api/martial/judgeInvite'
import { getCompetitionList } from '@/api/martial/competition'
import { getVenuesByCompetition } from '@/api/martial/venue'
import { getProjectsByCompetition } from '@/api/martial/project'
import { getRefereeList } from '@/api/martial/referee'
import dayjs from 'dayjs'

// 数据状态
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const selection = ref([])
const competitionList = ref([])
const competitionLoading = ref(false) // 赛事列表加载状态

// 裁判选择对话框
const judgeDialogVisible = ref(false)

// 场地和项目列表
const venueList = ref([])
const projectList = ref([])

// 导入表单
const importForm = reactive({
  venueId: null,
  projectIds: []
})
const judgeLoading = ref(false)
const judgeList = ref([])
const judgeTotal = ref(0)
const selectedJudges = ref([])
const judgeQueryParams = reactive({
  current: 1,
  size: 10,
  name: '',
  phone: '',
  refereeType: null
})

// 统计数据
const statistics = ref({
  totalInvites: 0,
  pendingCount: 0,
  acceptedCount: 0,
  rejectedCount: 0
})

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 10,
  competitionId: null,
  judgeName: '',
  judgeLevel: '',
  inviteStatus: ''
})

// 加载赛事列表
const loadCompetitionList = async () => {
  competitionLoading.value = true
  try {
    // 查询所有赛事
    const res = await getCompetitionList(1, 1000, {})

    // 根据axios响应拦截器的处理，数据结构为: res.data.data.records
    // res.data = 后端返回的整个JSON对象 { code, success, data, msg }
    // res.data.data = 后端返回的data字段 { records, total, size, current, pages }
    // res.data.data.records = 实际的赛事列表数组
    const records = res.data?.data?.records || []

    competitionList.value = records

    if (competitionList.value.length > 0) {
      // 如果没有选中赛事，自动选择第一个
      if (queryParams.competitionId === null || queryParams.competitionId === '') {
        queryParams.competitionId = competitionList.value[0].id
        handleCompetitionChange(queryParams.competitionId)
      }
    } else {
      ElMessage.warning('暂无可用赛事，请先创建赛事')
    }
  } catch (error) {
    console.error('加载赛事列表失败:', error)
    ElMessage.error(`加载赛事列表失败: ${error.response?.data?.msg || error.message || '请检查网络连接'}`)
  } finally {
    competitionLoading.value = false
  }
}

// 赛事切换
const handleCompetitionChange = (competitionId) => {
  fetchData()
  loadStatistics()
}

// 加载统计数据
const loadStatistics = async () => {
  if (queryParams.competitionId === null || queryParams.competitionId === '') return

  try {
    const res = await getInviteStatistics(queryParams.competitionId)
    if (res.data) {
      statistics.value = res.data
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 获取数据
const fetchData = async () => {
  if (queryParams.competitionId === null || queryParams.competitionId === '') return

  loading.value = true
  try {
    const res = await getJudgeInviteList(
      queryParams.current,
      queryParams.size,
      queryParams
    )
    // 根据axios响应拦截器的处理，数据在 res.data.data 中
    const data = res.data?.data || {}
    tableData.value = data.records || []
    total.value = data.total || 0
  } catch (error) {
    ElMessage.error('加载数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.current = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(queryParams, {
    current: 1,
    size: 10,
    judgeName: '',
    judgeLevel: '',
    inviteStatus: ''
  })
  fetchData()
}

// 从评委库导入
const handleImportFromPool = async () => {
  if (competitionLoading.value) {
    ElMessage.warning('赛事列表加载中，请稍候...')
    return
  }
  if (competitionList.value.length === 0) {
    ElMessage.warning('暂无可用赛事，请先创建赛事')
    return
  }
  if (queryParams.competitionId === null || queryParams.competitionId === '') {
    ElMessage.warning('请先选择赛事')
    return
  }

  // 重置导入表单
  importForm.venueId = null
  importForm.projectIds = []

  // 加载场地和项目列表
  await loadVenueAndProjectList()

  // 打开裁判选择对话框
  judgeDialogVisible.value = true
  selectedJudges.value = []
  loadJudgeList()
}

// 加载场地和项目列表
const loadVenueAndProjectList = async () => {
  try {
    // 并行加载场地和项目
    const [venueRes, projectRes] = await Promise.all([
      getVenuesByCompetition(queryParams.competitionId),
      getProjectsByCompetition(queryParams.competitionId)
    ])

    // 处理场地数据
    const venueData = venueRes.data?.data || venueRes.data || {}
    venueList.value = venueData.records || []

    // 处理项目数据
    const projectData = projectRes.data?.data || projectRes.data || {}
    projectList.value = projectData.records || []

    if (venueList.value.length === 0) {
      ElMessage.warning('该赛事暂无场地，请先添加场地')
    }
    if (projectList.value.length === 0) {
      ElMessage.warning('该赛事暂无项目，请先添加项目')
    }
  } catch (error) {
    console.error('加载场地/项目列表失败:', error)
    ElMessage.error('加载场地/项目列表失败')
  }
}

// 加载裁判列表
const loadJudgeList = async () => {
  judgeLoading.value = true
  try {
    const params = {}
    if (judgeQueryParams.name) {
      params.name = judgeQueryParams.name
    }
    if (judgeQueryParams.phone) {
      params.phone = judgeQueryParams.phone
    }
    if (judgeQueryParams.refereeType !== null && judgeQueryParams.refereeType !== '') {
      params.refereeType = judgeQueryParams.refereeType
    }

    const res = await getRefereeList(
      judgeQueryParams.current,
      judgeQueryParams.size,
      params
    )

    if (res.data && res.data.data && res.data.data.records) {
      judgeList.value = res.data.data.records
      judgeTotal.value = res.data.data.total || 0
    } else if (res.data && res.data.records) {
      judgeList.value = res.data.records
      judgeTotal.value = res.data.total || 0
    }
  } catch (error) {
    console.error('加载裁判列表失败:', error)
    ElMessage.error('加载裁判列表失败')
  } finally {
    judgeLoading.value = false
  }
}

// 裁判搜索
const handleJudgeSearch = () => {
  judgeQueryParams.current = 1
  loadJudgeList()
}

// 裁判搜索重置
const handleJudgeReset = () => {
  judgeQueryParams.name = ''
  judgeQueryParams.phone = ''
  judgeQueryParams.refereeType = null
  judgeQueryParams.current = 1
  loadJudgeList()
}

// 裁判选择改变
const handleJudgeSelectionChange = (val) => {
  selectedJudges.value = val
}

// 确认导入裁判
const handleConfirmImport = async () => {
  if (selectedJudges.value.length === 0) {
    ElMessage.warning('请至少选择一位裁判')
    return
  }

  // 验证场地和项目
  if (!importForm.venueId) {
    ElMessage.warning('请选择分配的场地')
    return
  }


  try {
    await ElMessageBox.confirm(
      `确定为选中的 ${selectedJudges.value.length} 位裁判生成邀请码吗？`,
      '确认导入',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    loading.value = true
    const judgeIds = selectedJudges.value.map(item => item.id)

    const res = await batchGenerateInviteCode({
      competitionId: queryParams.competitionId,
      judgeIds: judgeIds,
      role: 'judge',
      venueId: importForm.venueId,
      // projects不传，裁判默认负责整个场地
      expireDays: 30
    })

    // 根据axios响应拦截器的处理，数据在 res.data.data 中
    const invites = res.data?.data || []

    if (Array.isArray(invites) && invites.length > 0) {
      ElMessage.success(`成功为 ${invites.length} 位裁判生成邀请码`)
      judgeDialogVisible.value = false
      await fetchData()
      await loadStatistics()
    } else if (Array.isArray(invites) && invites.length === 0) {
      ElMessage.warning('所有裁判都已有有效邀请码，无需重复生成')
    } else {
      ElMessage.error(res.data?.msg || '生成邀请码失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('导入裁判失败:', error)
      ElMessage.error(error.response?.data?.msg || error.message || '导入裁判失败')
    }
  } finally {
    loading.value = false
  }
}

// 查看
const handleView = async (row) => {
  try {
    const res = await getJudgeInviteList(1, 1, { id: row.id })
    if (res.data && res.data.records && res.data.records.length > 0) {
      const detail = res.data.records[0]

      // 构建详情信息
      const detailHtml = `
        <div style="text-align: left; padding: 10px;">
          <p><strong>评委姓名：</strong>${detail.judgeName || '-'}</p>
          <p><strong>评委等级：</strong>${detail.judgeLevel || '-'}</p>
          <p><strong>邀请码：</strong><span style="color: #E6A23C; font-weight: bold;">${detail.inviteCode || '-'}</span></p>
          <p><strong>联系电话：</strong>${detail.contactPhone || '-'}</p>
          <p><strong>联系邮箱：</strong>${detail.contactEmail || '-'}</p>
          <p><strong>邀请状态：</strong>${getStatusText(detail.inviteStatus)}</p>
          <p><strong>邀请时间：</strong>${formatDateTime(detail.inviteTime)}</p>
          <p><strong>回复时间：</strong>${detail.replyTime ? formatDateTime(detail.replyTime) : '-'}</p>
          <p><strong>回复备注：</strong>${detail.replyNote || '-'}</p>
          <p><strong>邀请消息：</strong>${detail.inviteMessage || '-'}</p>
          ${detail.cancelReason ? `<p><strong>取消原因：</strong>${detail.cancelReason}</p>` : ''}
        </div>
      `

      ElMessageBox.alert(detailHtml, '邀请详情', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '关闭'
      })
    }
  } catch (error) {
    ElMessage.error('获取详情失败')
  }
}

// ==================== 邀请码生成功能 ====================

/**
 * 生成单个邀请码
 * 注意：此功能仅用于已有邀请记录但未生成邀请码的情况
 * 如果需要为新裁判生成邀请码，请使用"从评委库导入"功能
 */
const handleGenerateCode = async (row) => {
  if (queryParams.competitionId === null || queryParams.competitionId === '') {
    ElMessage.warning('请先选择赛事')
    return
  }

  // 检查是否有judgeId
  if (!row.judgeId) {
    ElMessage.error('数据异常：缺少裁判ID，请使用"从评委库导入"功能')
    return
  }

  try {
    loading.value = true
    const res = await generateInviteCode({
      competitionId: queryParams.competitionId,
      judgeId: row.judgeId,
      role: row.refereeType === 1 ? 'chief_judge' : (row.refereeType === 3 ? 'general_judge' : 'judge'), // 根据评委类型设置角色
      venueId: row.venueId || null,
      projects: row.projects ? JSON.stringify(row.projects) : null,
      expireDays: 30
    })

    if (res.data && res.data.inviteCode) {
      ElMessage.success(`邀请码生成成功：${res.data.inviteCode}`)
      // 自动复制到剪贴板
      copyToClipboard(res.data.inviteCode, '邀请码')
      // 刷新列表
      await fetchData()
      await loadStatistics()
    } else {
      ElMessage.error(res.msg || '生成失败')
    }
  } catch (error) {
    console.error('生成邀请码失败:', error)
    ElMessage.error(error.response?.data?.msg || error.message || '生成邀请码失败')
  } finally {
    loading.value = false
  }
}

/**
 * 重新生成邀请码
 */
const handleRegenerateCode = async (row) => {
  try {
    await ElMessageBox.confirm(
      '重新生成后，旧邀请码将失效。确定继续吗？',
      '重新生成邀请码',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    loading.value = true
    const res = await regenerateInviteCode(row.id)

    if (res.data && res.data.inviteCode) {
      ElMessage.success(`邀请码已重新生成：${res.data.inviteCode}`)
      // 自动复制到剪贴板
      copyToClipboard(res.data.inviteCode, '邀请码')
      // 刷新列表
      await fetchData()
      await loadStatistics()
    } else {
      ElMessage.error(res.msg || '重新生成失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重新生成邀请码失败:', error)
      ElMessage.error(error.response?.data?.msg || error.message || '重新生成邀请码失败')
    }
  } finally {
    loading.value = false
  }
}

/**
 * 删除邀请记录
 */
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除评委"${row.judgeName}"的邀请记录吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    loading.value = true
    await removeInvite(row.id)
    ElMessage.success('删除成功')

    // 刷新列表和统计数据
    await fetchData()
    await loadStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.response?.data?.msg || error.message || '删除失败')
    }
  } finally {
    loading.value = false
  }
}

// 导出
const handleExport = async () => {
  try {
    const res = await exportInvites(queryParams)
    const blob = new Blob([res], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = `评委邀请导出_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`
    link.click()
    window.URL.revokeObjectURL(link.href)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 选择改变
const handleSelectionChange = (val) => {
  selection.value = val
}

// 评委等级类型
const getLevelType = (level) => {
  const typeMap = {
    '国家级': 'danger',
    '一级': 'warning',
    '二级': 'success',
    '三级': 'info'
  }
  return typeMap[level] || ''
}

// 状态类型
const getStatusType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'danger',
    3: 'info'
  }
  return typeMap[status] || ''
}

// 状态文本
const getStatusText = (status) => {
  const textMap = {
    0: '待回复',
    1: '已接受',
    2: '已拒绝',
    3: '已取消'
  }
  return textMap[status] || '未知'
}

// 格式化时间
const formatDateTime = (date) => {
  if (!date) return '-'
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 复制到剪贴板
const copyToClipboard = (text, label) => {
  if (!text) {
    ElMessage.warning(`${label}为空`)
    return
  }

  // 使用现代API复制
  if (navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard.writeText(text).then(() => {
      ElMessage.success(`${label}已复制: ${text}`)
    }).catch(() => {
      fallbackCopyToClipboard(text, label)
    })
  } else {
    fallbackCopyToClipboard(text, label)
  }
}

// 降级复制方法(兼容旧浏览器)
const fallbackCopyToClipboard = (text, label) => {
  const textArea = document.createElement('textarea')
  textArea.value = text
  textArea.style.position = 'fixed'
  textArea.style.top = '-9999px'
  document.body.appendChild(textArea)
  textArea.focus()
  textArea.select()

  try {
    document.execCommand('copy')
    ElMessage.success(`${label}已复制: ${text}`)
  } catch (err) {
    ElMessage.error('复制失败，请手动复制')
  }

  document.body.removeChild(textArea)
}

// 挂载
onMounted(() => {
  loadCompetitionList()
})
</script>

<style scoped lang="scss">
.judge-invite-container {
  padding: 20px;

  .search-card,
  .toolbar-card,
  .table-card {
    margin-bottom: 20px;
  }

  .search-form {
    .el-form-item {
      margin-bottom: 0;
    }
  }

  .stats-row {
    margin-bottom: 20px;

    .stats-card {
      .stats-content {
        display: flex;
        align-items: center;
        padding: 10px 0;

        .stats-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #fff;
          margin-right: 20px;
        }

        .stats-info {
          flex: 1;

          .stats-value {
            font-size: 28px;
            font-weight: bold;
            color: #303133;
            line-height: 1;
            margin-bottom: 8px;
          }

          .stats-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }

  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .toolbar-left {
      display: flex;
      gap: 10px;
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

// 裁判选择对话框样式
.judge-search-form {
  margin-bottom: 15px;

  .el-form-item {
    margin-bottom: 0;
  }
}

.judge-pagination {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
</style>
