<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="赛事ID" prop="name">
              <el-input v-model="queryParams.id" placeholder="请输入赛事ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="赛事名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入赛事名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable v-model="queryParams.startTimeOne" type="date" value-format="YYYY-MM-DD" placeholder="请选择比赛开始时间" />
            </el-form-item>
            <el-form-item label="赛事标识" prop="tournamentType">
              <el-select v-model="queryParams.tournamentType" placeholder="请选择" clearable style="width: 150px">
                <el-option label="普通赛" :value="0" />
                <el-option label="晋级赛" :value="1" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['physical:tournaments:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['physical:tournaments:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['physical:tournaments:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['physical:tournaments:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="tournamentsList">
        <el-table-column label="比赛ID" align="center" prop="id" width="70" />
        <el-table-column label="比赛名" align="center" prop="name" />
        <el-table-column label="比赛Logo" align="center" width="90">
          <template #default="scope">
            <el-image
              v-if="scope.row.competitionIcon"
              :src="scope.row.competitionIcon"
              style="width: 40px; height: 40px; border-radius: 4px; cursor: zoom-in"
              :preview-src-list="[scope.row.competitionIcon]"
              :preview-teleported="true"
              fit="cover"
            />
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column label="比赛背景" align="center" width="90">
          <template #default="scope">
            <el-image
              v-if="scope.row.competitionBg"
              :src="scope.row.competitionBg"
              style="width: 40px; height: 40px; border-radius: 4px; cursor: zoom-in"
              :preview-src-list="[scope.row.competitionBg]"
              :preview-teleported="true"
              fit="cover"
            />
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column label="报名时间" align="center" prop="signTime" width="150" sortable="custom"> </el-table-column>
        <el-table-column label="开赛时间" align="center" prop="startTime" width="150" sortable="custom"> </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" width="150"> </el-table-column>
        <el-table-column label="报名人数" align="center" prop="signNum" width="80"> </el-table-column>
        <el-table-column label="总手数" align="center" prop="totalSignup" width="70"> </el-table-column>
        <el-table-column label="报名要求" align="center">
          <template #default="scope">
            <div v-if="scope.row.itemsConditionList && scope.row.itemsConditionList.length > 0">
              <!-- 显示第一个报名条件 -->
              <div>{{ scope.row.itemsConditionList[0].itemsName }} x {{ scope.row.itemsConditionList[0].quantity }}</div>

              <!-- 如果有更多报名条件，用 tooltip 显示 -->
              <el-tooltip
                v-if="scope.row.itemsConditionList.length > 1"
                :content="getConditionTooltipContent(scope.row.itemsConditionList)"
                placement="top"
              >
                <span class="more-conditions">更多</span>
              </el-tooltip>
            </div>
            <span v-else>—</span>
          </template>
        </el-table-column>
        <el-table-column label="开始级别" align="center" prop="startBlindLevel" />
        <el-table-column label="截止级别" align="center" prop="lateRegistrationLevel" />
        <el-table-column label="盲注表" align="center" prop="blindStructuresName" />
        <el-table-column label="奖励" align="center">
          <template #default="scope">
            <div v-if="scope.row.itemsPrizeList && scope.row.itemsPrizeList.length > 0">
              <!-- 显示第一名奖励 -->
              <div>
                第{{ scope.row.itemsPrizeList[0].ranking }}名：{{ scope.row.itemsPrizeList[0].quantity }} {{ scope.row.itemsPrizeList[0].itemsName }}
              </div>

              <!-- 如果有更多奖励，用 tooltip 显示 -->
              <el-tooltip v-if="scope.row.itemsPrizeList.length > 1" :content="getRewardTooltipContent(scope.row.itemsPrizeList)" placement="top">
                <span class="more-rewards">更多</span>
              </el-tooltip>
            </div>
            <span v-else>—</span>
          </template>
        </el-table-column>
        <el-table-column label="最小参赛人数" align="center" prop="minPlayers" />
        <el-table-column label="赛事标识" align="center" prop="tournamentType">
          <template #default="scope">
            <span :style="{ color: scope.row.tournamentType === 1 ? 'red' : 'inherit' }">
              {{ scope.row.tournamentType === 0 ? '普通赛' : '晋级赛' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <span
              :style="{
                color: scope.row.isDelete ? 'red' : ''
              }"
            >
              {{ scope.row.isDelete ? '已删除' : scope.row.statusText || '' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-dropdown trigger="click" placement="bottom">
              <span style="color: #303133; cursor: pointer; font-size: 14px; font-weight: 500">
                操作 <span style="font-size: 14px; margin-left: 2px">▼</span>
              </span>
              <template #dropdown>
                <el-dropdown-menu style="min-width: 100px; padding: 4px 0">
                  <el-dropdown-item @click="handleUpdate(scope.row)" v-hasPermi="['physical:tournaments:edit']">修改</el-dropdown-item>
                  <el-dropdown-item
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['physical:tournaments:remove']"
                    :disabled="!(scope.row.status === -1 || scope.row.status === 0)"
                  >
                    删除
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleCopy(scope.row)" v-hasPermi="['business:tournaments:query']">复制</el-dropdown-item>
                  <el-dropdown-item @click="handleToggleShow(scope.row)" v-hasPermi="['physical:tournaments:edit']">
                    {{ scope.row.isShow === 1 ? '隐藏' : '展示' }}
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleQueryItem(scope.row)">查询线下报名记录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改线下赛事对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body @close="cancel">
      <el-form ref="tournamentsFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="赛事名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入赛事名称" />
        </el-form-item>
        <el-form-item label="所属联赛" prop="leagueTournamentId">
          <el-select v-model="form.leagueTournamentId" placeholder="请选择联赛" style="width: 100%">
            <el-option v-for="item in leagueTournamentOptions" :key="item.id" :label="item.title" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属赛区" prop="leagueTournamentRegionId">
          <el-select v-model="form.leagueTournamentRegionId" placeholder="请选择赛区" style="width: 100%" @change="handleCompetitionZoneChange">
            <el-option v-for="item in competitionZoneOptions" :key="item.id" :label="item.zoneName" :value="item.id" />
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="所属赛区" prop="leagueTournamentRegion">
          <el-input v-model="form.leagueTournamentRegion" placeholder="请输入赛区" />
        </el-form-item>-->
        <el-form-item label="比赛项目" prop="gameVariant">
          <el-select aria-required="true" v-model="form.gameVariant" placeholder="请选择" :disabled="dialog.mode === 'view'">
            <el-option v-for="dict in game_variant_type" :key="dict.value" :label="dict.label" :value="dict.value"> </el-option>
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="赛事位置" prop="competitionLocation">
          <el-input v-model="form.competitionLocation" placeholder="请输入赛事位置" />
        </el-form-item>-->
        <!-- 比赛图标 -->
        <el-form-item label="比赛图标" prop="competitionIcon">
          <div class="icon-select-container">
            <el-button type="primary" @click="openIconSelectDialog('icon')" :disabled="dialog.mode === 'view'">点击选择图标</el-button>
            <div v-if="form.competitionIcon" class="preview-area" @click="handlePreviewIconClick">
              <img
                :src="form.competitionIcon"
                alt="预览图"
                style="max-width: 100px; max-height: 100px; margin-top: 10px; cursor: pointer; border-radius: 4px"
              />
            </div>
            <div v-else style="margin-top: 10px; color: #999">未选择图标</div>
          </div>
        </el-form-item>
        <!-- 比赛背景 -->
        <el-form-item label="比赛背景" prop="competitionBg">
          <div class="icon-select-container">
            <el-button type="primary" @click="openIconSelectDialog('background')" :disabled="dialog.mode === 'view'">点击选择背景</el-button>
            <div v-if="form.competitionBg" class="preview-area" @click="handlePreviewBgClick">
              <img
                :src="form.competitionBg"
                alt="预览图"
                style="max-width: 100px; max-height: 100px; margin-top: 10px; cursor: pointer; border-radius: 4px"
              />
            </div>
            <div v-else style="margin-top: 10px; color: #999">未选择背景</div>
          </div>
        </el-form-item>
        <el-form-item label="报名时间" prop="startTime">
          <el-date-picker clearable v-model="form.signTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择比赛开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="开赛时间" prop="startTime">
          <el-date-picker clearable v-model="form.startTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择比赛开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="比赛类型" prop="gameType">
          <el-select aria-required="true" v-model="form.gameType" placeholder="请选择">
            <el-option v-for="dict in physical_tournaments_type" :key="dict.value" :label="dict.label" :value="dict.value"> </el-option>
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="报名时长" prop="signTime">
          <el-select v-model="form.signTime" placeholder="请选择" :disabled="dialog.mode === 'view'">
            <el-option v-for="dict in tournaments_time" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>-->
        <!--        <el-form-item label="报名条件" prop="itemsId">
          <div style="display: flex; align-items: center; gap: 10px; width: 100%">
            <el-select v-model="form.itemsId" placeholder="请选择道具类型" :disabled="dialog.mode === 'view'" style="flex: 1">
              <el-option v-for="item in itemOptions" :key="item.id" :label="item.label" :value="item.id" />
            </el-select>

            <el-form-item prop="itemsNum" style="margin-bottom: 0; flex: 1">
              <el-input v-model.number="form.itemsNum" placeholder="数量" :disabled="dialog.mode === 'view'" style="width: 100%" />
            </el-form-item>
          </div>
        </el-form-item>-->
        <!-- 盲注表 -->
        <el-form-item label="盲注等级" prop="blindStructureId">
          <div style="display: flex; align-items: center">
            <el-select
              v-model="form.blindStructureId"
              placeholder="选项"
              style="width: 200px"
              @change="handleBlindStructureChange"
              :disabled="dialog.mode === 'view'"
            >
              <el-option v-for="item in itemOptionsStructures" :key="item.id" :label="item.label" :value="item.id" />
            </el-select>

            <el-button type="primary" :disabled="dialog.mode === 'view'" @click="handleGoToStructures"> 上传新盲注 </el-button>
            <el-button type="primary" @click="handleViewLevels" :disabled="dialog.mode === 'view'">预览</el-button>
          </div>
        </el-form-item>
        <!-- 报名截止至 -->
        <el-form-item label="起始级别" prop="lateRegistrationLevel">
          <el-select v-model="form.startBlindLevel" placeholder="选项" style="width: 200px" :disabled="dialog.mode === 'view'">
            <el-option v-for="item in itemOptionsStructuresLevel" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </el-form-item>
        <!-- 报名截止至 -->
        <el-form-item label="报名截止至" prop="lateRegistrationLevel">
          <el-select v-model="form.lateRegistrationLevel" placeholder="选项" style="width: 200px" :disabled="dialog.mode === 'view'">
            <el-option v-for="item in itemOptionsStructuresLevel" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="起始记分牌数量" prop="startingChips">
          <el-input v-model="form.startingChips" placeholder="请输入起始记分牌数量" :disabled="dialog.mode === 'view'" />
        </el-form-item>

        <!--        <el-form-item label="级别持续时间" prop="levelDuration" v-if="dialog.mode === 'edit'">
          <el-input v-model="form.levelDuration" placeholder="请输入级别持续时间" />
        </el-form-item>-->

        <!--        <el-form-item label="延迟卡时间" prop="delayCardTime">
          <el-input v-model="form.delayCardTime" placeholder="请输入延迟卡时间" :disabled="dialog.mode === 'view'" />
        </el-form-item>

        <el-form-item label="延迟卡数量" prop="delayCardNum">
          <el-input v-model="form.delayCardNum" placeholder="请输入延迟卡数量" :disabled="dialog.mode === 'view'" />
        </el-form-item>-->
        <el-form-item label="参赛人数" prop="minPlayers">
          <el-input v-model="form.maxPlayers" placeholder="请输入参赛人数" :disabled="dialog.mode === 'view'" />
        </el-form-item>
        <el-form-item label="最小参赛人数" prop="minPlayers">
          <el-input v-model="form.minPlayers" placeholder="请输入最小参赛人数" :disabled="dialog.mode === 'view'" />
        </el-form-item>
        <el-form-item label="报名条件备注">
          <el-input v-model="form.conditionNote" placeholder="请输入报名条件备注" :disabled="dialog.mode === 'view'" />
        </el-form-item>
        <el-form-item label="报名条件" prop="itemsId">
          <div>
            <div v-for="(condition, index) in formConditions.conditions" :key="index" style="display: flex; align-items: center; margin-bottom: 8px">
              <span>第{{ condition.index + 1 }}项</span>

              <!-- 道具选择 -->
              <el-select v-model="condition.itemId" placeholder="选项" style="width: 120px; margin-right: 8px" :disabled="dialog.mode === 'view'">
                <el-option v-for="item in itemOptions" :key="item.id" :label="item.label" :value="item.id" />
              </el-select>

              <!-- 数量输入 -->
              <el-input
                v-model="condition.quantity"
                placeholder="请输入数量"
                style="width: 100px; margin-right: 8px"
                :disabled="dialog.mode === 'view'"
              />

              <!-- 操作按钮 -->
              <el-button type="primary" @click="addCondition" v-if="index === 0 && dialog.mode !== 'view'">+</el-button>
              <el-button type="primary" @click="removeCondition(index)" v-if="index !== 0 && dialog.mode !== 'view'">-</el-button>
            </div>
          </div>
        </el-form-item>
        <!-- 奖励内容 -->
        <el-form-item label="奖励内容">
          <div v-for="(reward, index) in formPrize.rewards" :key="index" style="display: flex; align-items: center; margin-bottom: 8px">
            <span>第{{ reward.ranking }}名</span>

            <!-- 道具选择 -->
            <el-select v-model="reward.itemId" placeholder="选项" style="width: 120px; margin-right: 8px" :disabled="dialog.mode === 'view'">
              <el-option v-for="item in itemPrizeOptions" :key="item.id" :label="item.label" :value="item.id" />
            </el-select>

            <!-- 数量输入 -->
            <el-input v-model="reward.quantity" placeholder="请输入数量" style="width: 100px; margin-right: 8px" :disabled="dialog.mode === 'view'" />

            <!-- 操作按钮 -->
            <el-button type="primary" @click="addReward" v-if="index === 0 && dialog.mode !== 'view'">+</el-button>
            <el-button type="primary" @click="removeReward(index)" v-if="index !== 0 && dialog.mode !== 'view'">-</el-button>
          </div>
        </el-form-item>
        <el-form-item label="赛制详情" prop="tournamentsIntroduction">
          <el-input
            v-model="form.tournamentsIntroduction"
            type="textarea"
            placeholder="请输入赛制详情(比赛规则)"
            :disabled="dialog.mode === 'view'"
            :rows="4"
          />
        </el-form-item>
        <el-form-item label="裁判" prop="judgeId">
          <div style="display: flex; align-items: center">
            <el-select
              v-model="form.judgeId"
              placeholder="选项"
              style="width: 200px"
              :disabled="dialog.mode === 'view'"
              multiple
              collapse-tags
              collapse-tags-tooltip
            >
              <el-option v-for="item in judgeOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </div>
        </el-form-item>

        <el-form-item label="赛事标识" prop="tournamentType">
          <el-select v-model="form.tournamentType" placeholder="请选择" :disabled="dialog.mode === 'view'">
            <el-option v-for="item in tournamentTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="目标赛事" prop="targetTournamentId" v-if="form.tournamentType === 1">
          <el-select
            v-model="form.targetTournamentId"
            placeholder="请选择比赛"
            :disabled="dialog.mode === 'view'"
            remote
            :remote-method="loadTargetTournaments"
            :loading="selectLoading"
            clearable
            filterable
          >
            <el-option v-for="item in selectOptions" :key="item.id" :label="item.label" :value="item.id" />
            <!-- 添加空状态提示 -->
            <template #empty>
              <div v-if="selectLoading" class="el-select-dropdown__empty">
                <span>加载中...</span>
              </div>
              <div v-else-if="selectOptions.length === 0" class="el-select-dropdown__empty">
                <span>暂无数据</span>
              </div>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="晋级条件类型" prop="qualifierType" v-if="form.tournamentType === 1">
          <el-select aria-required="true" v-model="form.qualifierType" placeholder="请选择" :disabled="dialog.mode === 'view'">
            <el-option v-for="dict in qualifier_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="晋级条件值" prop="qualifierValue" v-if="form.tournamentType === 1 && form.qualifierType === '2'">
          <el-input v-model="form.qualifierValue" placeholder="请输入晋级条件值" :disabled="dialog.mode === 'view'" />
        </el-form-item>

        <el-form-item label="晋级级别" prop="qualifierValue" v-if="form.tournamentType === 1 && form.qualifierType === '1'">
          <el-select v-model="form.qualifierValue" placeholder="选项" style="width: 200px" :disabled="dialog.mode === 'view'">
            <el-option v-for="item in itemOptionsStructuresLevel2" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否可以报名" prop="isOffline">
          <el-select v-model="form.isOffline" placeholder="请选择" style="width: 200px" :disabled="dialog.mode === 'view'">
            <el-option label="是" :value="1" />
            <el-option label="否" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="levelsDialogVisible" title="盲注等级列表" width="80%">
      <!-- 使用 component 动态加载目标组件 -->
      <levels-index :blind-structure-id="dialogParams.blindStructureId" :name="dialogParams.name" />
    </el-dialog>
    <!-- 图片预览弹窗 -->
    <el-dialog v-model="previewDialogVisible" title="图片预览" width="50%">
      <img :src="previewDialogSrc" alt="预览图片" style="max-width: 100%; max-height: 80vh" />
    </el-dialog>
    <!-- 图片库选择组件 -->
    <TournamentImageSelect
      v-model="imageSelectVisible"
      :default-type="imageSelectType"
      :default-scene="'online'"
      @confirm="handleImageSelectConfirm"
      @cancel="handleImageSelectCancel"
    />
  </div>
</template>

<script setup name="Tournaments" lang="ts">
import {
  listTournaments,
  getTournaments,
  delTournaments,
  addTournaments,
  updateTournaments,
  updateByTournament,
  selectPhysicalTournamentsLeagueId
} from '@/api/system/physical/tournaments';
import { TournamentsVO, TournamentsQuery, TournamentsForm } from '@/api/system/physical/tournaments/types';
import { selectItemsSelList, selectXianXiaItemsSelList } from '@/api/system/business/items';
import { selectPhysicalBlingStructuresInfo } from '@/api/system/physical/blindStructures';
import { selectPhysicalBlindLevelsById } from '@/api/system/physical/blindLevels';
import { selectPhysicalLeagueTournamentSelList } from '@/api/system/physical/leagueTournament';
import { selectPhysicalJudgeSelList } from '@/api/system/physical/judge';
import { selectCompetitionZoneSelList } from '@/api/system/physical/competitionZone';
import { parseTime } from '@/utils/dateUtils';
import LevelsIndex from '@/views/system/physical/blindLevels/index.vue';
import { LeagueTournamentVO } from '@/api/system/physical/leagueTournament/types';
import { JudgeVO } from '@/api/system/physical/judge/types';
import { ElSelect } from 'element-plus';
import { ref, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { CompetitionZoneVO } from '@/api/system/physical/competitionZone/types';
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { game_variant_type, tournaments_time, physical_tournaments_type, qualifier_type } = toRefs<any>(
  proxy?.useDict('game_variant_type', 'tournaments_time', 'physical_tournaments_type', 'qualifier_type')
);
const tournamentsList = ref<TournamentsVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const tournamentsFormRef = ref<ElFormInstance>();

const dialog = reactive<{
  visible: boolean;
  title: string;
  mode: 'edit' | 'view' | 'add'; // 新增字段
}>({
  visible: false,
  title: '',
  mode: 'edit'
});

const initFormData: TournamentsForm = {
  id: undefined,
  name: undefined,
  startTime: undefined,
  endTime: undefined,
  pauseTime: undefined,
  gameType: undefined,
  gameVariant: '0',
  startingChips: undefined,
  levelDuration: undefined,
  lateRegistrationLevel: undefined,
  maxPlayers: undefined,
  minPlayers: undefined,
  rewardPlayers: undefined,
  totalSignup: undefined,
  robotCount: undefined,
  status: undefined,
  signTime: undefined,
  competitionIcon: undefined,
  competitionBg: undefined,
  tournamentsBiId: undefined,
  updateUserId: undefined,
  updatedAt: undefined,
  createUserId: undefined,
  createdAt: undefined,
  isDelete: undefined,
  delayCardTime: undefined,
  delayCardNum: undefined,
  actionTime: undefined,
  targetTournamentId: undefined,
  qualifierType: undefined,
  qualifierValue: undefined,
  tournamentType: 0,
  isOffline: 1
};
const data = reactive<PageData<TournamentsForm, TournamentsQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    startTime: undefined,
    endTime: undefined,
    pauseTime: undefined,
    gameType: undefined,
    gameVariant: undefined,
    startingChips: undefined,
    levelDuration: undefined,
    lateRegistrationLevel: undefined,
    maxPlayers: undefined,
    minPlayers: undefined,
    rewardPlayers: undefined,
    totalSignup: undefined,
    robotCount: undefined,
    status: undefined,
    signTime: undefined,
    competitionIcon: undefined,
    competitionBg: undefined,
    tournamentsBiId: undefined,
    updateUserId: undefined,
    updatedAt: undefined,
    createUserId: undefined,
    createdAt: undefined,
    isDelete: undefined,
    delayCardTime: undefined,
    delayCardNum: undefined,
    actionTime: undefined,
    targetTournamentId: undefined,
    qualifierType: undefined,
    qualifierValue: undefined,
    params: {},
    leagueTournamentId: undefined, // ← 新增字段
    startTimeOne: ''
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '赛事名称不能为空', trigger: 'blur' }],
    startTime: [{ required: true, message: '比赛开始时间不能为空', trigger: 'blur' }],
    gameType: [{ required: true, message: '游戏类型不能为空', trigger: 'change' }],
    lateRegistrationLevel: [{ required: true, message: '截止报名级别不能为空', trigger: 'change' }],
    leagueTournamentId: [{ required: true, message: '所属联赛不能为空', trigger: 'change' }],
    leagueTournamentRegionId: [{ required: true, message: '所属赛区不能为空', trigger: 'change' }],
    competitionIcon: [{ required: true, message: '比赛图标不能为空', trigger: 'change' }],
    competitionBg: [{ required: true, message: '比赛背景不能为空', trigger: 'change' }],
    signTime: [{ required: true, message: '报名时间不能为空', trigger: 'change' }],
    judgeId: [{ required: true, message: '裁判不能为空', trigger: 'change' }],
    itemsId: [
      {
        validator: (rule, value, callback) => {
          // 当 tournamentType 为 1（卫星赛）时，不进行校验
          if (data.form.tournamentType === 1) {
            callback();
            return;
          }
          callback();
          // 检查是否至少有一个报名条件被设置
          /*  const hasValidCondition = formConditions.conditions.some((condition) => condition.itemId && condition.quantity);
         if (!hasValidCondition) {
            callback(new Error('报名条件不能为空'));
          } else {
            callback();
          }*/
        },
        trigger: 'change'
      }
    ],
    blindStructureId: [{ required: true, message: '盲注等级不能为空', trigger: 'change' }],
    startingChips: [
      { required: true, message: '起始记分牌数量不能为空', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          // 检查是否为字符串类型且包含非数字字符
          if (typeof value === 'string' && !/^\d+$/.test(value)) {
            callback(new Error('起始记分牌数量必须为数字'));
            return;
          }

          const num = Number(value);
          if (isNaN(num) || num <= 0) {
            callback(new Error('起始记分牌数量必须大于0'));
          } else if (!Number.isInteger(num)) {
            callback(new Error('起始记分牌数量必须为整数'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    itemsNum: [
      { required: true, message: '数量不能为空', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          // 检查是否为字符串类型且包含非数字字符
          if (typeof value === 'string' && !/^\d+$/.test(value)) {
            callback(new Error('数量必须为正整数'));
            return;
          }

          const num = Number(value);
          if (isNaN(num) || num <= 0) {
            callback(new Error('数量必须大于0'));
          } else if (!Number.isInteger(num)) {
            callback(new Error('数量必须为整数'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    delayCardTime: [
      { required: false, message: '延迟卡时间不能为空', trigger: 'blur' },
      {
        validator: (rule: any, value: any, callback: any) => {
          const num = Number(value);
          if (!value) {
            callback(new Error('请输入延迟卡时间'));
          } else if (!/^\d+$/.test(value)) {
            callback(new Error('只能输入正整数'));
          } else if (num < 10 || num > 15) {
            callback(new Error('延迟卡时间必须在10-15秒之间'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    delayCardNum: [
      { required: false, message: '延迟卡数量不能为空', trigger: 'blur' },
      {
        validator: (rule: any, value: any, callback: any) => {
          const num = Number(value);
          if (!value) {
            callback(new Error('请输入延迟卡数量'));
          } else if (!/^\d+$/.test(value)) {
            callback(new Error('只能输入正整数'));
          } else if (num < 1 || num > 99) {
            callback(new Error('延迟卡数量必须在1-99之间'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    minPlayers: [
      { required: false, message: '参赛人数不能为空', trigger: 'blur' },
      {
        validator: (rule: any, value: any, callback: any) => {
          const num = Number(value);
          if (!/^\d+$/.test(value)) {
            callback(new Error('只能输入正整数'));
          } else if (num < 0 || num > 999) {
            callback(new Error('参赛人数必须在0-999之间'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    isOffline: [{ required: true, message: '是否可以报名不能为空', trigger: 'change' }]
  }
});
// 控制 Dialog 是否显示
const levelsDialogVisible = ref(false);
// 传递给子组件的参数
const dialogParams = ref({
  blindStructureId: null,
  name: null
});

const { queryParams, form, rules } = toRefs(data);

/** 查询线下赛事列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTournaments(queryParams.value);
  tournamentsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  resetFormPrize();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  tournamentsFormRef.value?.resetFields();
  resetFormConditions();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  // 将所有查询参数重置为空
  queryParams.value.id = '';
  queryParams.value.name = '';
  queryParams.value.startTimeOne = '';
  queryParams.value.tournamentType = '';
  // 重置页码
  queryParams.value.pageNum = 1;
  // 直接执行搜索
  getList();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: TournamentsVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  resetFormPrize();
  form.value.leagueTournamentId = queryParams.value.leagueTournamentId ? Number(queryParams.value.leagueTournamentId) : undefined;
  dialog.visible = true;
  dialog.title = '创建比赛';
  dialog.mode = 'add'; // 设置模式
};
const resetFormPrize = () => {
  // 清空 rewards 并添加默认项
  formPrize.rewards.splice(0); // 清空数组
  formPrize.rewards.push({ ...defaultRewardStructure }); // 添加初始项
};
/** 修改按钮操作 */
const handleUpdate = async (row?: TournamentsVO, mode: 'edit' | 'view' = 'edit') => {
  reset(); // 重置表单
  const _id = row?.id || ids.value[0];
  const res = await getTournaments(_id);
  // 设置表单数据
  Object.assign(form.value, res.data);
  form.value.signTime = String(res.data.signTime);
  form.value.gameType = String(res.data.gameType); // 转为字符串
  form.value.gameVariant = String(res.data.gameVariant); // 转为字符串
  form.value.qualifierType = String(res.data.qualifierType);
  // competitionIcon 和 competitionBg 已通过 Object.assign 自动赋值到 form
  // 处理报名条件数据
  const conditionItems = res.data.itemsConditionList || [];
  if (conditionItems.length > 0) {
    formConditions.conditions = conditionItems.map((item, index) => ({
      index: index,
      itemId: Number(item.itemId),
      quantity: Number(item.quantity)
    }));
  } else {
    formConditions.conditions = [
      {
        index: 0,
        itemId: null,
        quantity: null
      }
    ];
  }
  // 处理奖励表单数据
  const prizeItems = res.data.itemsPrizeList || [];
  if (prizeItems.length > 0) {
    formPrize.rewards = prizeItems.map((item, index) => ({
      ranking: item.ranking || index + 1,
      itemId: Number(item.itemId),
      quantity: Number(item.quantity)
    }));
  } else {
    /*formPrize.rewards = [
      {
        ranking: 1,
        itemId: null,
        quantity: null
      }
    ];*/
  }
  // ✅ 主动触发盲注等级加载
  if (form.value.blindStructureId) {
    await handleBlindStructureChange(form.value.blindStructureId);
  }
  dialog.visible = true;
  dialog.title = mode === 'view' ? '查看比赛' : '编辑比赛';
  dialog.mode = mode; // 设置模式
};

/** 提交按钮 */
const submitForm = () => {
  tournamentsFormRef.value?.validate(async (valid: boolean) => {
    // 校验奖励内容是否至少填写了一项
    /* if (data.form.tournamentType !== 1) {
      if (!formPrize.rewards.some((r) => r.itemId && r.quantity)) {
        ElMessage.warning('请至少填写一项奖励内容');
        return;
      }
    }*/
    if (!valid) return;
    try {
      buttonLoading.value = true;

      // 构造最终要提交的数据对象
      const formData: TournamentsForm = {
        ...data.form,
        competitionIcon: data.form.competitionIcon, // 确保 iconUrl 存在
        // 添加报名条件数据
        itemsConditionList: formConditions.conditions
          .filter((condition) => condition.itemId && condition.quantity) // 过滤掉未填写的条件
          .map((condition) => ({
            ranking: 0,
            itemId: Number(condition.itemId),
            quantity: Number(condition.quantity)
          }))
      };
      // 只有在有奖励数据时才添加 itemsPrizeList
      if (formPrize.rewards && formPrize.rewards.length > 0) {
        formData.itemsPrizeList = formPrize.rewards
          .filter((reward) => reward.itemId && reward.itemId !== 0) // 过滤掉 itemId 为 0 的项
          .map((reward) => ({
            ranking: Number(reward.ranking),
            itemId: Number(reward.itemId),
            quantity: Number(reward.quantity)
          }));
      }
      // 提交数据（区分新增/编辑）
      let response;
      if (formData.id) {
        response = await updateTournaments(formData);
      } else {
        response = await addTournaments(formData);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
      await loadLeagueRelatedTournaments();
    } catch (error) {
      console.error('提交失败:', error);
      proxy?.$modal.msgError('提交失败，请重试');
    } finally {
      buttonLoading.value = false;
    }
  });
};
/** 删除按钮操作 */
const handleDelete = async (row?: TournamentsVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除赛事ID为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delTournaments(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'physical/tournaments/export',
    {
      ...queryParams.value
    },
    `大奖赛${parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}.xlsx`
  );
};
onMounted(() => {
  const route = proxy?.$route;
  if (route.query.leagueTournamentId) {
    queryParams.value.leagueTournamentId = String(route.query.leagueTournamentId);
    form.value.leagueTournamentId = route.query.leagueTournamentId as number;
  }
  getList();
  loadItemOptions();
  loadItemStructuresOptions();
  loadLeagueTournamentOptions();
  loadJudgeOptions();
  loadItemPrizeOptions();
  loadLeagueRelatedTournaments();
  loadCompetitionZoneOptions();
});
// 监听路由变化，重新加载数据
watch(
  () => proxy?.$route.query.leagueTournamentId,
  (newVal) => {
    if (newVal) {
      queryParams.value.leagueTournamentId = String(newVal);
      form.value.leagueTournamentId = Number(newVal);
      getList();
      loadItemOptions();
      loadItemStructuresOptions();
      loadLeagueTournamentOptions();
      loadJudgeOptions();
      loadItemPrizeOptions();
      loadLeagueRelatedTournaments();
      loadCompetitionZoneOptions();
    }
  },
  { immediate: false }
);
// 添加watch监听对话框显示状态，确保打开时数据已加载
watch(
  () => dialog.visible,
  async (newVal) => {
    if (newVal && selectOptions.value.length === 0) {
      // 只有在选项为空时才重新加载，避免重复请求
      await loadLeagueRelatedTournaments();
    }
  }
);
const itemOptions = ref<{ id: number; label: string }[]>([]);
// 加载报名条件选项
const loadItemOptions = async () => {
  try {
    const res = await selectXianXiaItemsSelList();
    if (res.code === 200) {
      // 类型断言
      const data = res.data as unknown as { id: number; name: string }[];

      // 过滤掉 id === 2 的项，并映射为 { id, label }
      itemOptions.value = data
        .filter((item) => item.id !== 2) // ✅ 过滤 id 为 2 的
        .map((item) => ({
          id: item.id,
          label: item.name
        }));
    } else {
      ElMessage.error('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
    ElMessage.error('请求失败，请检查网络');
  }
};
const itemPrizeOptions = ref<{ id: number; label: string }[]>([]);
// 加载报名条件选项
const loadItemPrizeOptions = async () => {
  try {
    const res = await selectItemsSelList();
    if (res.code === 200) {
      // 类型断言
      const data = res.data as unknown as { id: number; name: string }[];

      // 过滤掉 id === 2 的项，并映射为 { id, label }
      itemPrizeOptions.value = data
        .filter((item) => item.id !== 2) // ✅ 过滤 id 为 2 的
        .map((item) => ({
          id: item.id,
          label: item.name
        }));
    } else {
      ElMessage.error('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
    ElMessage.error('请求失败，请检查网络');
  }
};

// 下拉选项数据 selectPhysicalBlingStructuresInfo
const itemOptionsStructures = ref<{ id: number; label: string }[]>([]);
const loadItemStructuresOptions = async () => {
  try {
    const res = await selectPhysicalBlingStructuresInfo();
    if (res.code === 200) {
      // 使用 unknown 中间类型进行类型转换
      const data = res.data as unknown as { id: number; name: string }[];
      const list = [];
      for (let i = 0; i < data.length; i++) {
        const item = data[i];
        list.push({
          id: item.id,
          label: item.name
        });
      }
      itemOptionsStructures.value = list;
    } else {
      alert('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
};

// 下拉选项数据
const itemOptionsStructuresLevel = ref<{ id: number; label: string }[]>([]);
const itemOptionsStructuresLevel2 = ref<{ id: number; label: string }[]>([]);
// 加载报名条件选项
const handleBlindStructureChange = async (value: number) => {
  //data.form.lateRegistrationLevel = null;
  try {
    const res = await selectPhysicalBlindLevelsById(value);
    if (res.code === 200) {
      // 使用 unknown 中间类型进行类型转换
      const data2 = res.data as unknown as { id: number; levelNumber: number; isBreak: number }[];
      const list = [];
      for (let i = 0; i < data2.length; i++) {
        const item = data2[i];
        // 排除 is_break(是Break) 为 1 的项
        if (!item.isBreak) {
          list.push({
            id: item.levelNumber,
            label: item.levelNumber
          });
        }
      }
      itemOptionsStructuresLevel.value = list;
      itemOptionsStructuresLevel2.value = list;
      // 判断当前选择的 lateRegistrationLevel 是否在新列表中
      const currentLevel = data.form.lateRegistrationLevel;
      if (currentLevel && !list.some((item) => item.id === currentLevel)) {
        data.form.lateRegistrationLevel = null;
      }
    } else {
      alert('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
};
// 跳转到盲注表页面，并关闭当前弹窗
const handleGoToStructures = () => {
  dialog.visible = false; // 关闭弹窗
  // 使用 nextTick 确保关闭动画完成后跳转（可选）
  nextTick(() => {
    proxy?.$router.push('/physical/blindStructures');
  });
};
const handleViewLevels = () => {
  const blindStructureId = data.form.blindStructureId;
  if (blindStructureId === null || blindStructureId === undefined) {
    ElMessage.warning('请先选择一个盲注等级');
    return;
  }
  dialogParams.value.blindStructureId = blindStructureId;
  /*  dialogParams.value.name = row.name;*/
  levelsDialogVisible.value = true;
};

const formPrize = reactive({
  // ...其他表单字段
  rewards: [
    {
      ranking: 1,
      itemId: null,
      quantity: null
    }
  ]
});
// 用于保存原始的默认奖励结构
const defaultRewardStructure = {
  ranking: 1,
  itemId: null,
  quantity: null
};

const addReward = () => {
  const currentLength = formPrize.rewards.length;

  // 判断是否超过 itemOptions 的数量限制
  /*  if (currentLength < itemOptions.value.length) {*/
  formPrize.rewards.push({
    ranking: currentLength + 1, // 自动生成排名，从 1 开始
    itemId: null,
    quantity: null
  });
  /*  } else {
    ElMessage.warning(`最多只能添加 ${itemOptions.value.length} 个奖励项`);
  }*/
};

const removeReward = (index: number) => {
  formPrize.rewards.splice(index, 1);
  // 删除后重新设置排名
  formPrize.rewards.forEach((r, i) => {
    r.ranking = i + 1;
  });
};
// 获取奖励提示内容
const getRewardTooltipContent = (rewards: any[]) => {
  return rewards.map((prize) => `第${prize.ranking}名：${prize.quantity} ${prize.itemsName}`).join('\n');
};
// 图片库选择相关变量
const imageSelectVisible = ref(false);
const imageSelectType = ref<'icon' | 'background'>('icon');
const previewDialogVisible = ref(false);
const previewDialogSrc = ref('');

// 打开图片选择对话框
const openIconSelectDialog = (type: 'icon' | 'background') => {
  imageSelectType.value = type;
  imageSelectVisible.value = true;
};

// 图片选择确认回调
const handleImageSelectConfirm = (url: string) => {
  if (imageSelectType.value === 'icon') {
    form.value.competitionIcon = url;
  } else {
    form.value.competitionBg = url;
  }
  imageSelectVisible.value = false;
};

// 图片选择取消回调
const handleImageSelectCancel = () => {
  imageSelectVisible.value = false;
};

// 预览图标点击
const handlePreviewIconClick = () => {
  if (form.value.competitionIcon) {
    previewDialogSrc.value = form.value.competitionIcon;
    previewDialogVisible.value = true;
  }
};

// 预览背景点击
const handlePreviewBgClick = () => {
  if (form.value.competitionBg) {
    previewDialogSrc.value = form.value.competitionBg;
    previewDialogVisible.value = true;
  }
};
/** 修改按钮操作 */
const handleCopy = async (row?: TournamentsVO) => {
  reset(); // 重置表单
  const _id = row?.id || ids.value[0];
  const res = await getTournaments(_id);
  // 设置表单数据
  res.data.id = null;
  Object.assign(form.value, res.data);
  form.value.signTime = String(res.data.signTime);
  form.value.gameType = String(res.data.gameType); // 转为字符串
  form.value.status = 0;
  form.value.id = null;
  form.value.levelDuration = null;

  form.value.delayCardTime = res.data.delayCardTime;
  form.value.delayCardNum = res.data.delayCardNum;

  form.value.gameVariant = String(res.data.gameVariant); // 转为字符串
  // competitionIcon 和 competitionBg 已通过 Object.assign 自动赋值到 form
  // 处理报名条件数据
  const conditionItems = res.data.itemsConditionList || [];
  if (conditionItems.length > 0) {
    formConditions.conditions = conditionItems.map((item, index) => ({
      index: index,
      itemId: Number(item.itemId),
      quantity: Number(item.quantity)
    }));
  } else {
    formConditions.conditions = [
      {
        index: 0,
        itemId: null,
        quantity: null
      }
    ];
  }

  // 处理奖励表单数据
  const prizeItems = res.data.itemsPrizeList || [];
  if (prizeItems.length > 0) {
    formPrize.rewards = prizeItems.map((item, index) => ({
      ranking: item.ranking || index + 1,
      itemId: Number(item.itemId),
      quantity: Number(item.quantity)
    }));
  } else {
    formPrize.rewards = [
      {
        ranking: 1,
        itemId: null,
        quantity: null
      }
    ];
  }
  // ✅ 主动触发盲注等级加载
  if (form.value.blindStructureId) {
    await handleBlindStructureChange(form.value.blindStructureId);
  }
  dialog.mode = 'add'; // 设置为新增模式
  dialog.visible = true;
  dialog.title = '创建比赛';
};
// 响应式变量
const leagueTournamentOptions = ref<LeagueTournamentVO[]>([]);

const loadLeagueTournamentOptions = async () => {
  try {
    const res = await selectPhysicalLeagueTournamentSelList();
    if (res.code === 200 && Array.isArray(res.data)) {
      leagueTournamentOptions.value = res.data;
    } else {
      ElMessage.error('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
    ElMessage.error('请求失败，请检查网络');
  }
};

const judgeOptions = ref<JudgeVO[]>([]);

const loadJudgeOptions = async () => {
  try {
    const res = await selectPhysicalJudgeSelList();
    if (res.code === 200 && Array.isArray(res.data)) {
      judgeOptions.value = res.data;
    } else {
      ElMessage.error('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
    ElMessage.error('请求失败，请检查网络');
  }
};
const competitionZoneOptions = ref<CompetitionZoneVO[]>([]);
const loadCompetitionZoneOptions = async () => {
  try {
    const res = await selectCompetitionZoneSelList();
    if (res.code === 200 && Array.isArray(res.data)) {
      competitionZoneOptions.value = res.data;
    } else {
      ElMessage.error('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
    ElMessage.error('请求失败，请检查网络');
  }
};
// 报名条件数据结构
const formConditions = reactive({
  conditions: [
    {
      index: 0,
      itemId: null,
      quantity: null
    }
  ]
});

// 默认报名条件结构
const defaultCondition = {
  index: 0,
  itemId: null,
  quantity: null
};

// 添加报名条件
const addCondition = () => {
  const currentLength = formConditions.conditions.length;

  formConditions.conditions.push({
    index: currentLength,
    itemId: null,
    quantity: null
  });
};

// 移除报名条件
const removeCondition = (index: number) => {
  formConditions.conditions.splice(index, 1);

  // 重新设置索引
  formConditions.conditions.forEach((c, i) => {
    c.index = i;
  });
};

// 重置报名条件
const resetFormConditions = () => {
  formConditions.conditions.splice(0);
  formConditions.conditions.push({ ...defaultCondition });
};
// 获取报名条件提示内容
const getConditionTooltipContent = (conditions: any[]) => {
  return conditions.map((condition) => `${condition.itemsName} x ${condition.quantity}`).join('\n');
};
const tournamentTypeOptions = ref([
  { value: 0, label: '普通赛' },
  { value: 1, label: '晋级赛' }
]);
const selectOptions = ref<{ id: string | number; label: string }[]>([]); // 👈 类型明确：id 可能是 string/number，name 是必填字段
const selectLoading = ref(false);
const loadLeagueRelatedTournaments = async () => {
  try {
    selectLoading.value = true;
    const res = await selectPhysicalTournamentsLeagueId();
    const data2 = res.data as unknown as { id: number; name: string }[];

    // 使用map方法提高效率和可读性
    selectOptions.value = data2.map((item) => ({
      id: item.id,
      label: item.name
    }));
  } catch (error) {
    console.error('加载联赛关联赛事失败', error);
    ElMessage.error('加载失败');
  } finally {
    selectLoading.value = false;
  }
};
const loadTargetTournaments = (query: string) => {
  if (!query.trim()) {
    selectOptions.value = selectOptions.value;
    return;
  }
  // 这里可加模糊搜索逻辑（如 filter）222
  selectOptions.value = selectOptions.value.filter((item) => item.label.toLowerCase().includes(query.toLowerCase()));
};
const handleCompetitionZoneChange = (value: number) => {
  const selectedZone = competitionZoneOptions.value.find((item) => item.id === value);
  if (selectedZone) {
    form.value.leagueTournamentRegion = selectedZone.zoneName;
  } else {
    form.value.leagueTournamentRegion = '';
  }
};
/** 切换展示/隐藏状态 */
const handleToggleShow = async (row: TournamentsVO) => {
  const newStatus = row.isShow === 1 ? 0 : 1;
  const statusText = newStatus === 1 ? '展示' : '隐藏';

  try {
    await proxy?.$modal.confirm(`确认要${statusText}该赛事吗？`);

    // 使用 updateTournaments 接口，只传入 id 和 isShow 字段
    await updateByTournament({
      id: row.id,
      isShow: newStatus
    } as TournamentsForm);

    proxy?.$modal.msgSuccess(`${statusText}成功`);
    await getList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('切换状态失败:', error);
      proxy?.$modal.msgError(`${statusText}失败，请重试`);
    }
  }
};
/** 查询按钮操作 */
const handleQueryItem = (row: TournamentsVO) => {
  // 跳转到线下报名记录页面
  router.push({
    path: '/physical/participants', // 改对路径！
    query: {
      tournamentId: row.id
    }
  });
};
</script>
