<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-[20px]">
        <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="gameType">
              <el-select aria-required="true" v-model="queryParams.status" placeholder="请选择" :disabled="dialog.mode === 'view'">
                <!-- 添加"全部"选项 -->
                <el-option :value="null" :label="'全部'" />
                <el-option v-for="dict in tournaments_status" :key="dict.value" :label="dict.label" :value="dict.value"> </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable v-model="queryParams.startTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择比赛开始时间" />
            </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="['business:tournaments:add']">创立比赛</el-button>
          </el-col>
          <!--          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['business:tournaments:edit']"
              >编辑</el-button
            >
          </el-col>-->
          <!--          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['business:tournaments:remove']"
              >删除</el-button
            >service/catory
          </el-col>-->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['business:tournaments:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Operation">
              <router-link to="/service/catory">比赛类目管理</router-link>
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Operation">
              <router-link to="/service/tag">比赛标签管理</router-link>
            </el-button>
          </el-col>
          <!-- 新增的 “盲注管理” 按钮 -->
          <!--          <el-col :span="1.5">
            <el-button type="warning" plain icon="Operation" v-hasPermi="['business:tournaments:manager']">
              <router-link to="/tournament/structures">盲注表管理</router-link>
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Operation" v-hasPermi="['business:tournaments:manager']">
              <router-link to="/tournament/config">自动比赛管理</router-link>
            </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"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        :default-sort="{ prop: 'startTime', order: sortData.order }"
      >
        <!--        <el-table-column type="selection" width="55" align="center" />-->
        <el-table-column label="比赛ID" align="center" prop="id" width="70" />
        <el-table-column label="比赛名" align="center" prop="name" />
<!--        <el-table-column label="比赛项目" align="center" prop="projectName" width="150" />-->
<!--        <el-table-column label="比赛项目" align="center" prop="gameVariant">
          <template #default="scope">
            {{ getGameVariantText(scope.row.gameVariant) }}
          </template>
        </el-table-column>-->
<!--        <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="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">
            {{
              scope.row.itemsName && scope.row.itemsNum
                ? `${scope.row.itemsName} x ${scope.row.itemsNum}`
                : scope.row.itemsName || scope.row.itemsNum || '—'
            }}
          </template>
        </el-table-column>
        <el-table-column label="比赛类目" align="center">
          <template #default="scope">
            <span v-if="scope.row.categoryName && scope.row.categoryName.length > 0">
              <el-tag v-for="(category, index) in scope.row.categoryName" :key="index" type="primary" style="margin-right: 4px">
                {{ category }}
              </el-tag>
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column label="比赛标签" align="center">
          <template #default="scope">
            <span v-if="scope.row.tagName && scope.row.tagName.length > 0">
              <el-tag v-for="(tag, index) in scope.row.tagName" :key="index" type="success" style="margin-right: 4px">
                {{ tag }}
              </el-tag>
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column label="截止盲注等级" align="center" prop="lateRegistrationLevel" />
        &lt;!&ndash;        <el-table-column label="盲注表" align="center" prop="blindStructuresName" />&ndash;&gt;

        <el-table-column label="奖励" align="center">
          <template #default="scope">
            <div v-if="scope.row.itemsPrizeList && scope.row.itemsPrizeList.length > 0">
              &lt;!&ndash; 显示第一名奖励 &ndash;&gt;
              <div>
                第{{ scope.row.itemsPrizeList[0].ranking }}名：{{ scope.row.itemsPrizeList[0].quantity }} {{ scope.row.itemsPrizeList[0].itemsName }}
              </div>

              &lt;!&ndash; 如果有更多奖励，用 tooltip 显示 &ndash;&gt;
              <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">
          <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" prop="createdAt" width="150"> </el-table-column>
        <!--        <el-table-column label="是否删除" align="center">
          <template #default="scope">
            <span
              :style="{
                color: [null, undefined, '', ' '].includes(scope.row.isDelete) || scope.row.isDelete === false ? '' : 'red'
              }"
            >
              {{ [null, undefined, '', ' '].includes(scope.row.isDelete) || scope.row.isDelete === false ? '未删除' : '已删除' }}
            </span>
          </template>
        </el-table-column>-->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="320">
          <template #default="scope">
            <div class="operation-buttons-vertical" v-if="scope.row.isDelete === true">
              <el-tooltip content="查看" placement="top" v-hasPermi="['business:tournaments:query']">
                <el-button link type="primary" icon="View" @click="openAuditDialog(scope.row.id, 'view')">查看</el-button>
              </el-tooltip>
              <el-tooltip content="复制" placement="top" v-hasPermi="['business:tournaments:copy']">
                <el-button link type="primary" icon="Files" @click="handleCopy(scope.row)"> 复制 </el-button>
              </el-tooltip>
              <!--              <el-tooltip content="恢复" placement="top">
                <el-button link type="primary" icon="Files" @click="handleRecoverTournament(scope.row)" v-hasPermi="['business:tournaments:query']"
                  >恢复</el-button
                >
              </el-tooltip>-->
              <el-tooltip content="粉碎删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="deleteAllData(scope.row)" v-hasPermi="['business:tournaments:query']"
                  >粉碎删除</el-button
                >
              </el-tooltip>
            </div>
            <div class="operation-buttons-vertical" v-else>
              <el-tooltip content="查看" placement="top" v-hasPermi="['business:tournaments:query']">
                <el-button link type="primary" icon="View" @click="openAuditDialog(scope.row.id, 'view')">查看</el-button>
              </el-tooltip>

              <el-tooltip content="删除" v-if="scope.row.status === 0 && scope.row.isDelete != true" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:tournaments:query']"
                  >删除</el-button
                >
              </el-tooltip>

              <el-tooltip content="编辑" v-if="scope.row.status === 0" placement="top" v-hasPermi="['business:tournaments:query']">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row, 'edit')">编辑</el-button>
              </el-tooltip>

              <el-tooltip content="复制" placement="top" v-hasPermi="['business:tournaments:query']">
                <el-button link type="primary" icon="Files" @click="handleCopy(scope.row)"> 复制 </el-button>
              </el-tooltip>

              <el-tooltip content="复盘" placement="top" v-hasPermi="['business:tournaments:query']">
                <el-button link type="primary" icon="DocumentChecked" @click="handleViewPublicHistory(scope.row)"> 复盘 </el-button>
              </el-tooltip>

              <el-tooltip content="领奖审核" placement="top" v-hasPermi="['business:tournaments:query']">
                <el-button link type="primary" icon="DocumentChecked" @click="openAuditDialog(scope.row.id, 'audit')">领奖审核</el-button>
              </el-tooltip>

              <el-tooltip content="关闭" v-if="scope.row.status === 1" placement="top" v-hasPermi="['business:tournaments:query']">
                <el-button link type="primary" icon="Close" @click="closeSendTournamentOperate(scope.row)">关闭</el-button>
              </el-tooltip>
              <el-tooltip content="发布" v-if="scope.row.status === -1" placement="top" v-hasPermi="['business:tournaments:query']">
                <el-button link type="primary" icon="DocumentChecked" @click="publishToTournament2(scope.row)">发布</el-button>
              </el-tooltip>
            </div>
          </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="500px" append-to-body>
      <el-form ref="tournamentsFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="赛事名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入赛事名称" />
        </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="startingChips">
          <el-input v-model="form.startingChips" placeholder="请输入起始记分牌数量" />
        </el-form-item>
        <el-form-item label="级别持续时间" prop="levelDuration">
          <el-input v-model="form.levelDuration" placeholder="请输入级别持续时间" />
        </el-form-item>
        <el-form-item label="截止报名级别" prop="lateRegistrationLevel">
          <el-input v-model="form.lateRegistrationLevel" placeholder="请输入截止报名级别" />
        </el-form-item>
        <el-form-item label="最大参赛人数" prop="maxPlayers">
          <el-input v-model="form.maxPlayers" placeholder="请输入最大参赛人数" />
        </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 :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="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="configId">
          <el-select v-model="form.configId" placeholder="选项" :disabled="dialog.mode === 'view'">
            <el-option v-for="item in configOptions" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="比赛类型" prop="gameType">
          <el-select aria-required="true" v-model="form.gameType" placeholder="请选择" :disabled="dialog.mode === 'view'">
            <el-option v-for="dict in tournaments_type" :key="dict.value" :label="dict.label" :value="dict.value"> </el-option>
          </el-select>
        </el-form-item>
        <!-- 赛事名称 -->
        <el-form-item label="比赛名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入比赛名称" :disabled="dialog.mode === 'view'" />
        </el-form-item>

        <!-- 比赛图标 -->
        <el-form-item label="比赛图标" prop="icon">
          <div class="upload-container">
            <el-upload
              class="upload-icon"
              action="#"
              :on-change="handleIconChange"
              :on-remove="handleIconRemove"
              :file-list="fileList"
              :auto-upload="false"
              accept="image/*"
              :disabled="dialog.mode === 'view'"
            >
              <template #trigger>
                <el-button type="primary" :disabled="dialog.mode === 'view'">点击选择图标</el-button>
              </template>

              <!-- 预览图区域 -->
              <template #default>
                <div class="preview-area" @click="handlePreviewClick">
                  <!-- 只有当 iconPreviewUrl 或 competitionIcon 存在时才显示 img -->
                  <img
                    v-if="iconPreviewUrl || competitionIcon"
                    :src="iconPreviewUrl || competitionIcon"
                    alt="预览图"
                    style="max-width: 100px; max-height: 100px; margin-top: 10px; cursor: pointer"
                  />
                  <!-- 可选：无图时显示提示文字 -->
                  <div v-else style="margin-top: 10px; color: #999"></div>
                </div>
              </template>

              <template #tip>
                <div class="el-upload__tip">
                  <span v-if="fileList.length > 0">当前已选文件：{{ fileList[0].name }}</span>
                </div>
              </template>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="是否冠名" prop="isSponsor">
          <el-select v-model="form.isSponsor" placeholder="请选择" :disabled="dialog.mode === 'view'">
            <el-option label="是" :value="1"></el-option>
            <el-option label="否" :value="0"></el-option>
          </el-select>
        </el-form-item>

        <!-- 比赛图标 -->
        <el-form-item label="比赛背景" prop="icon" v-if="form.isSponsor === 1">
          <div class="upload-container">
            <el-upload
              class="upload-icon"
              action="#"
              :on-change="handleIconChange2"
              :on-remove="handleIconRemove2"
              :file-list="fileList2"
              :auto-upload="false"
              accept="image/*"
              :disabled="dialog.mode === 'view'"
            >
              <template #trigger>
                <el-button type="primary" :disabled="dialog.mode === 'view'">点击选择背景</el-button>
              </template>

              <!-- 预览图区域 -->
              <template #default>
                <div class="preview-area" @click="handlePreviewClick2">
                  <!-- 只有当 iconPreviewUrl 或 competitionIcon 存在时才显示 img -->
                  <img
                    v-if="iconPreviewUrl2 || competitionBg"
                    :src="iconPreviewUrl2 || competitionBg"
                    alt="预览图"
                    style="max-width: 100px; max-height: 100px; margin-top: 10px; cursor: pointer"
                  />
                  <!-- 可选：无图时显示提示文字 -->
                  <div v-else style="margin-top: 10px; color: #999"></div>
                </div>
              </template>

              <template #tip>
                <div class="el-upload__tip">
                  <span v-if="fileList2.length > 0">当前已选文件：{{ fileList2[0].name }}</span>
                </div>
              </template>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="比赛标签" prop="tagId">
          <div style="display: flex; align-items: center">
            <el-select
              v-model="form.tagId"
              placeholder="选项"
              style="width: 200px"
              :disabled="dialog.mode === 'view'"
              multiple
              collapse-tags
              collapse-tags-tooltip
              :multiple-limit="1"
            >
              <el-option v-for="item in itemOptionsTagList" :key="item.id" :label="item.label" :value="item.id" />
            </el-select>
            <el-button type="primary" :disabled="dialog.mode === 'view'" @click="handleGoToTag"> 标签管理 </el-button>
          </div>
        </el-form-item>
        <el-form-item label="比赛类目" prop="categoryId">
          <div style="display: flex; align-items: center">
            <el-select
              v-model="form.categoryId"
              placeholder="选项"
              style="width: 200px"
              :disabled="dialog.mode === 'view'"
              multiple
              :multiple-limit="1"
              collapse-tags
              collapse-tags-tooltip
            >
              <el-option v-for="item in itemOptionsCategoryList" :key="item.id" :label="item.label" :value="item.id" />
            </el-select>
            <el-button type="primary" :disabled="dialog.mode === 'view'" @click="handleGoToCategory"> 类目管理 </el-button>
          </div>
        </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"
            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="盲注等级" 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="targetTournamentId">
          <el-select
            v-model="form.targetTournamentId"
            placeholder="请选择比赛"
            :disabled="dialog.mode === 'view'"
            @visible-change="handleSelectVisibleChange"
            remote
            :remote-method="remoteMethod"
            :loading="selectLoading"
            clearable
          >
            <el-option v-for="item in selectOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="晋级条件类型" prop="qualifierType">
          <el-select
            aria-required="true"
            v-model="form.qualifierType"
            placeholder="请选择"
            :disabled="dialog.mode === 'view'"
            @change="handleQualifierTypeChange"
          >
            <el-option v-for="dict in qualifier_type" :key="dict.value" :label="dict.label" :value="dict.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="晋级条件值" prop="qualifierValue" v-if="form.qualifierType === '2'">
          <el-input v-model="form.qualifierValue" placeholder="请输入晋级条件值" :disabled="dialog.mode === 'view'" />
        </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">
            <el-select v-model="form.itemsId" placeholder="请选择道具类型" :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="form.itemsNum" prop="itemsNum" :min="1" placeholder="数量" :disabled="dialog.mode === 'view'" />
          </div>
        </el-form-item>-->
        <!--        <el-form-item label="报名条件">
          <div style="display: flex; align-items: center; gap: 10px">
            <el-form-item prop="itemsId" style="margin-bottom: 0">
              <el-select v-model="form.itemsId" placeholder="请选择道具类型" :disabled="dialog.mode === 'view'">
                <el-option v-for="item in itemOptions" :key="item.id" :label="item.label" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item prop="itemsNum" style="margin-bottom: 0">
              <el-input v-model.number="form.itemsNum" placeholder="数量" :disabled="dialog.mode === 'view'"  />
            </el-form-item>
          </div>
        </el-form-item>-->
        <el-form-item label="晋级级别" prop="qualifierValue" v-if="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="startBlindLevel">
          <el-select v-model="form.startBlindLevel" placeholder="选项" style="width: 200px" :disabled="dialog.mode === 'view'">
            <el-option v-for="item in itemOptionsStructuresLevel3" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </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="robotCount" v-if="!isProdEnvironment">
          <el-input v-model="form.robotCount" placeholder="请输入机器人数" :disabled="dialog.mode === 'view'" />
        </el-form-item>-->
        <el-form-item label="延迟看牌" prop="delayShow">
          <el-select v-model="form.delayShow" placeholder="请选择" :disabled="dialog.mode === 'view'">
            <el-option label="开启" :value="1"></el-option>
            <el-option label="关闭" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="延迟卡" prop="isDelay">
          <el-select v-model="form.isDelay" placeholder="请选择" :disabled="dialog.mode === 'view'" @change="handleIsDelayChange">
            <el-option label="是" :value="1"></el-option>
            <el-option label="否" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="延迟卡时间" prop="delayCardTime" v-if="form.isDelay === 1">
          <el-input v-model="form.delayCardTime" placeholder="请输入延迟卡时间" :disabled="dialog.mode === 'view'" />
        </el-form-item>-->
        <!--        <el-form-item label="延迟卡数量" prop="delayCardNum" v-if="form.isDelay === 1">
          <el-input v-model="form.delayCardNum" placeholder="请输入延迟卡数量" :disabled="dialog.mode === 'view'" />
        </el-form-item>-->
        <el-form-item label="重复买入" prop="rebuy">
          <div style="display: flex; align-items: center; gap: 10px; width: 100%">
            <el-select v-model="form.rebuy" placeholder="请选择" :disabled="dialog.mode === 'view'" style="flex: 1">
              <el-option label="不可重复" :value="-1"></el-option>
              <el-option label="不限制" :value="0"></el-option>
              <el-option label="限制次数" :value="1"></el-option>
            </el-select>

            <el-form-item prop="rebuyLimit" style="margin-bottom: 0; flex: 1" v-if="form.rebuy === 1">
              <el-input v-model.number="form.rebuyLimit" placeholder="请输入次数" :disabled="dialog.mode === 'view'" style="width: 100%" />
            </el-form-item>
          </div>
        </el-form-item>
        <!-- 报名截止至 -->
        <el-form-item label="报名截止至" prop="lateRegistrationLevel">
          <el-select v-model="form.lateRegistrationLevel" placeholder="选项" :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="itemsId" v-if="form.gameType !== '3'">
          <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="比赛奖励">
          <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 itemOptions" :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="remark">
          <el-input v-model="form.remark" placeholder="请输入赛事备注" :disabled="dialog.mode === 'view'" type="textarea" :rows="4" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm" v-if="dialog.mode !== 'view'">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 分配模态框 -->
    <el-dialog title="分配盲注信息" v-model="assignDialog.visible" width="800px" append-to-body destroy-on-close>
      <el-form ref="assignFormRef" :model="assignForm" label-width="100px">
        <!-- 可勾选的列表 -->
        <el-form-item label="">
          <div style="display: flex; flex-direction: column; align-items: center; width: 100%">
            <div style="width: 100%; height: 400px; overflow-y: auto; padding: 0">
              <el-table border ref="assignTable" :data="assignList" :row-key="'blindStructuresId'" style="width: 100%">
                <el-table-column label="操作" align="center" width="55">
                  <template #default="{ row }">
                    <el-radio v-model="selectedRadio" :label="row.blindStructuresId">&nbsp;</el-radio>
                  </template>
                </el-table-column>
                <!--                <el-table-column label="blindStructuresId" align="center" prop="blindStructuresId" width="100" show-overflow-tooltip />-->
                <el-table-column prop="blindStructuresName" label="盲注结构名称" align="center" width="150" show-overflow-tooltip />
                <el-table-column prop="blindDescription" label="盲注结构描述" align="center" width="200" show-overflow-tooltip />
                <el-table-column prop="allocationStatus" label="绑定情况" align="center" width="100">
                  <template #default="scope">
                    {{ scope.row.allocationStatus === 0 ? '未绑定' : '已绑定' }}
                  </template>
                </el-table-column>
                <el-table-column prop="tournamentsName" label="赛事名称" align="center" width="150" show-overflow-tooltip />
              </el-table>
            </div>
            <!-- 分页（如果数据量大） -->
            <div style="display: flex; justify-content: center; margin-top: 20px; width: 100%">
              <pagination
                v-if="assignTotal > 0"
                :total="assignTotal"
                v-model:page="assignQuery.pageNum"
                v-model:limit="assignQuery.pageSize"
                @pagination="getAssignList"
              />
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer" style="text-align: center">
          <el-button :loading="buttonLoading" type="primary" @click="submitAssign">保 存</el-button>
          <el-button @click="assignDialog.visible = false">取 消</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="dialogVisible" title="图片预览" width="50%">
      <img :src="previewSrc || iconPreviewUrl || competitionIcon" alt="预览图片" style="max-width: 100%; max-height: 80vh" />
    </el-dialog>

    <el-dialog v-model="dialogVisible2" title="图片预览" width="50%">
      <img :src="previewSrc2 || iconPreviewUrl2 || competitionBg" alt="预览图片" style="max-width: 100%; max-height: 80vh" />
    </el-dialog>

    <el-dialog
      :title="`${tournamentInfo.name} ${tournamentInfo.tournamentsBiId}`"
      v-model="auditDialog.visible"
      width="1000px"
      append-to-body
      @close="cancelAudit"
    >
      <!-- 查看对局记录按钮 -->
      <!--      <div class="dialog-header-actions" v-if="auditDialog.mode === 'view'">
        <el-button type="primary">查看对局记录</el-button>
      </div>-->

      <!-- 比赛信息展示 -->
      <div class="tournament-info" v-if="tournamentInfo.id">
        <p>比赛时间：{{ tournamentInfo.startTime }} ~ {{ tournamentInfo.endTime }}</p>
        <p>参加人数：{{ tournamentInfo.signNum }}人</p>
        <p v-if="auditDialog.mode === 'view'">比赛类型：{{ tournamentInfo.id }}</p>
        <p v-if="auditDialog.mode === 'view'">报名条件：{{ tournamentInfo.itemsName }} x {{ tournamentInfo.itemsNum }}</p>
        <p v-if="auditDialog.mode === 'view'">
          盲注等级：{{ tournamentInfo.blindStructuresName }}
          <el-button type="primary" @click="handleViewLevelsSee(tournamentInfo)">预览</el-button>
        </p>
        <p v-if="auditDialog.mode === 'view'">报名截止至：{{ tournamentInfo.lateRegistrationLevel }}</p>
        <p v-if="tournamentInfo.isComplaints" style="color: red">本场比赛仍有选手存在异议，请处理申述后继续授作。</p>
      </div>

      <!-- 添加导出按钮 -->
      <div style="margin: 10px 0; text-align: right">
        <el-button type="warning" plain icon="Download" @click="handleExportAuditData">导出审核数据</el-button>
      </div>

      <!-- 表格内容 -->
      <el-table :data="auditData" border style="width: 100%">
        <el-table-column prop="id" label="id" align="center" v-if="false"></el-table-column>
        <el-table-column prop="rank" label="排名" align="center"></el-table-column>
        <el-table-column prop="playerName" label="用户名" align="center"></el-table-column>
        <el-table-column prop="phone" label="手机" align="center"></el-table-column>
        <!--        <el-table-column prop="tournamentId" label="tournamentId" align="center"></el-table-column>
        <el-table-column prop="playerId" label="playerId" align="center"></el-table-column>-->
        <el-table-column label="奖励" align="center">
          <template #default="scope">
            <div v-for="(prize, index) in scope.row.rewardVoList" :key="index">{{ prize.itemName }} {{ prize.quantity }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="claimedText" label="状态" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="350" class-name="small-padding fixed-width">
          <template #default="scope">
            <div style="display: flex; justify-content: center; gap: 16px">
              <el-tooltip content="查看牌局" placement="top">
                <el-button link type="primary" icon="View" @click="handleViewHistory(scope.row)">查看牌局</el-button>
              </el-tooltip>
              <el-tooltip content="审核" placement="top">
                <el-button link type="primary" icon="DocumentChecked" @click="handleAudit(scope.row)">审核</el-button>
              </el-tooltip>
              <el-tooltip content="移除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleClaimsDelete(scope.row)">移除</el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <div class="pagination-container" style="margin-top: 20px; text-align: center">
        <el-pagination
          v-model:current-page="auditQueryParams.pageNum"
          v-model:page-size="auditQueryParams.pageSize"
          :total="auditTotal"
          layout="prev, pager, next"
          @current-change="getAuditData"
        />
      </div>
      <!-- 对话框底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelAudit">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="移除获奖名额" v-model="removeDialog.visible" width="30%">
      <span>是否移除用户：{{ removeDialog.playerName }}{{ removeDialog.phone }} 在本次比赛中的获奖名额？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelRemove">取消</el-button>
          <el-button type="danger" @click="confirmRemove">确认移除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tournaments" lang="ts">
import {
  listTournaments,
  getTournaments,
  delTournaments,
  deleteCheckTournament,
  addTournaments,
  updateTournaments,
  getSelectTournamentBlindStructuresList,
  assignTournamentBlindStructures,
  uploadTournament,
  closeSendTournament,
  recoverTournament,
  deleteRelationTournament,
  publishToTournament
} from '@/api/system/business/tournaments';
import { selectTagSelList, selectCategorySelList } from '@/api/system/business/tag';
import { selectItemsSelList } from '@/api/system/business/items';
import { selectBlindLevelsById } from '@/api/system/business/levels';
import { selectBlingStructuresInfo } from '@/api/system/business/structures';
import { listClaims, deleteClaim, auditSendReward } from '@/api/system/business/claims';
import { selectTournamentConfigSelList } from '@/api/system/business/tournamentConfig';
import { TournamentsVO, TournamentsQuery, TournamentsForm, TournamentsBindStructuresVO } from '@/api/system/business/tournaments/types';
import { ref } from 'vue';
import LevelsIndex from '@/views/system/business/levels/index.vue';
import { ClaimsVO } from '@/api/system/business/claims/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { tournaments_type, tournaments_time, tournaments_status, game_variant_type, qualifier_type } = toRefs<any>(
  proxy?.useDict('tournaments_type', 'tournaments_time', 'tournaments_status', 'game_variant_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 iconFile = ref<File | null>(null); // 存储选中的图标文件
const dialog = reactive<{
  visible: boolean;
  title: string;
  mode: 'edit' | 'view' | 'add'; // 新增字段
}>({
  visible: false,
  title: '',
  mode: 'edit'
});

const assignDialog = reactive({
  visible: false,
  title: '分配盲注'
});

const assignForm = reactive({
  tournamentId: undefined as number | undefined,
  selectedIds: [] as number[]
});
const dialogVisible = ref(false);
const previewSrc = ref('');

const dialogVisible2 = ref(false);
const previewSrc2 = ref('');

function openPreview(src: string) {
  previewSrc.value = src;
  dialogVisible.value = true;
}
function openPreview2(src: string) {
  previewSrc2.value = src;
  dialogVisible2.value = true;
}
// 控制 Dialog 是否显示
const levelsDialogVisible = ref(false);
// 传递给子组件的参数
const dialogParams = ref({
  blindStructureId: null,
  name: null
});

// 下拉选项数据 selectBlingStructuresInfo
const itemOptions = ref<{ id: number; label: string }[]>([]);

// 加载报名条件选项
const loadItemOptions = 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 }
      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('请求失败，请检查网络');
  }
};

// 下拉选项数据 selectBlingStructuresInfo
const itemOptionsStructures = ref<{ id: number; label: string }[]>([]);

// 加载报名条件选项
const loadItemStructuresOptions = async () => {
  try {
    const res = await selectBlingStructuresInfo();
    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;

      // Automatically select the first option if form is in add mode and no value is set
      if (!form.value.blindStructureId && list.length > 0) {
        form.value.blindStructureId = list[0].id;
        // Trigger the change event to load corresponding levels
        handleBlindStructureChange(list[0].id);
      }
    } else {
      alert('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
};
// 下拉选项数据
const itemOptionsStructuresLevel = ref<{ id: number; label: string }[]>([]);
const itemOptionsStructuresLevel2 = ref<{ id: number; label: string }[]>([]);
const itemOptionsStructuresLevel3 = ref<{ id: number; label: string }[]>([]);
// 加载报名条件选项
const handleBlindStructureChange = async (value: number) => {
  //data.form.lateRegistrationLevel = null;
  try {
    const res = await selectBlindLevelsById(value);
    if (res.code === 200) {
      // 使用 unknown 中间类型进行类型转换
      const data2 = res.data as unknown as { id: number; levelNumber: number }[];
      const list = [];
      for (let i = 0; i < data2.length; i++) {
        const item = data2[i];
        list.push({
          id: item.levelNumber,
          label: item.levelNumber
        });
      }
      itemOptionsStructuresLevel.value = list;
      itemOptionsStructuresLevel2.value = list;
      itemOptionsStructuresLevel3.value = list;
      // 判断当前选择的 lateRegistrationLevel 是否在新列表中
      const currentLevel = data.form.lateRegistrationLevel;
      if (currentLevel && !list.some((item) => item.id === currentLevel)) {
        data.form.lateRegistrationLevel = null;
        data.form.lateRegistrationLevel = null;
      }
    } else {
      alert('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
};
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 iconPreviewUrl = ref('');
const competitionIcon = ref('');
const fileList = ref([]);

//预览图标需要
const iconPreviewUrl2 = ref('');
const competitionBg = ref('');
const fileList2 = ref([]);

import { parseTime } from '@/utils/dateUtils';
import { ElSelect } from 'element-plus';
// 单选控制变量（用于绑定 el-radio）
const selectedRadio = ref<number | null>(null);

const assignList = ref<TournamentsBindStructuresVO[]>([]);
const assignSelectedList = ref<TournamentsBindStructuresVO[]>([]);
const assignTotal = ref(0);

const assignQuery = reactive<{
  pageNum: number;
  pageSize: number;
  tournamentId: number | undefined;
}>({
  pageNum: 1,
  pageSize: 10,
  tournamentId: undefined
});

const initFormData: TournamentsForm = {
  id: undefined,
  name: undefined,
  startTime: undefined,
  gameType: undefined,
  gameVariant: null,
  qualifierType: '0',
  startingChips: undefined,
  levelDuration: undefined,
  lateRegistrationLevel: undefined,
  maxPlayers: undefined,
  status: undefined,
  createdAt: undefined,
  updatedAt: undefined,
  signTime: undefined,
  competitionIcon: null,
  itemsId: null,
  itemsNum: null,
  blindStructureId: null,
  itemsPrizeList: [],
  delayCardNum: 4,
  delayCardTime: 15,
  isSponsor: 1, // 添加赞助商标识，默认为否
  isDelay: 1,
  rebuyLimit: null,
  tagId: [], // 修改为数组形式以支持多选
  categoryId: []
};
const data = reactive<PageData<TournamentsForm, TournamentsQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    startTime: undefined,
    gameType: undefined,
    startingChips: undefined,
    levelDuration: undefined,
    lateRegistrationLevel: undefined,
    maxPlayers: undefined,
    status: undefined,
    createdAt: undefined,
    updatedAt: undefined,
    id: undefined,
    params: {}
  },

  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '赛事名称不能为空', trigger: 'blur' }],
    startTime: [{ required: true, message: '比赛开始时间不能为空', trigger: 'blur' }],
    configId: [{ required: true, message: '不能为空', trigger: 'blur' }],
    gameType: [{ required: true, message: '游戏类型不能为空', trigger: 'change' }],
    gameVariant: [{ required: true, message: '玩法类型不能为空', trigger: 'change' }],
    qualifierType: [{ required: true, message: '晋级条件类型不能为空', trigger: 'change' }],
    lateRegistrationLevel: [{ required: true, message: '截止报名级别不能为空', trigger: 'change' }],
    signTime: [{ required: true, message: '报名时间不能为空', trigger: 'change' }],
    itemsId: [
      {
        required: true,
        message: '报名条件不能为空',
        trigger: 'change',
        validator: (rule: any, value: any, callback: any) => {
          // 如果 gameType 为 3，则不进行校验
          if (data.form.gameType === '3') {
            callback();
            return;
          }
          // 其他情况执行默认校验
          if (!value) {
            callback(new Error('报名条件不能为空'));
          } else {
            callback();
          }
        }
      }
    ],
    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: any, value: any, callback: any) => {
          // 如果 gameType 为 3，则不进行校验
          if (data.form.gameType === '3') {
            callback();
            return;
          }

          // 检查是否为字符串类型且包含非数字字符
          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();
          }
        }
      }
    ],
    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'
      }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);
/** 查询【请填写功能名称】列表 */
const getList = async () => {
  loading.value = true;
  const params = {
    ...queryParams.value,
    sortBy: sortData.value.prop,
    isAsc: sortData.value.order === 'ascending'
  };
  const res = await listTournaments(params);
  tournamentsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  resetFormPrize();
  fileList.value = [];
  // 清除预览图和临时链接
  iconPreviewUrl.value = '';
  competitionIcon.value = ''; // 如果需要清除后台加载的图标，可以在这里设置为空字符串

  iconPreviewUrl2.value = '';
  competitionBg.value = '';
  dialog.visible = false;
};

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

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

/** 重置按钮操作 */
const resetQuery = () => {
  // 将所有查询参数重置为空
  queryParams.value.id = '';
  queryParams.value.name = '';
  queryParams.value.status = '';
  queryParams.value.startTime = '';
  // 重置页码
  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();
  fileList.value = [];
  // 清除预览图和临时链接
  iconPreviewUrl.value = '';
  competitionIcon.value = ''; // 如果需要清除后台加载的图标，可以在这里设置为空字符串
  iconPreviewUrl2.value = '';
  competitionBg.value = '';
  dialog.visible = true;
  dialog.title = '创建比赛';
  dialog.mode = 'add'; // 设置模式
  // Load structures and automatically select first option
  nextTick(() => {
    loadItemStructuresOptions();
  });
};
// 重置函数
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.gameVariant = String(res.data.gameVariant);
  form.value.qualifierType = String(res.data.qualifierType);
  form.value.gameType = String(res.data.gameType); // 转为字符串
  competitionIcon.value = res.data.competitionIcon;
  competitionBg.value = res.data.competitionBg;

  // 清空文件列表，避免残留
  fileList.value = [];
  fileList2.value = [];

  // 如果有图片URL，创建虚拟文件对象以便显示
  if (res.data.competitionIcon) {
    fileList.value = [
      {
        name: '已上传图片',
        url: res.data.competitionIcon,
        status: 'success'
      }
    ];
  }

  if (res.data.competitionBg) {
    fileList2.value = [
      {
        name: '已上传背景图',
        url: res.data.competitionBg,
        status: 'success'
      }
    ];
  }

  if (res.data.delayCardTime == 0 && res.data.delayCardNum == 0) {
    form.value.isDelay = 0;
  }
  if (res.data.competitionBg == null) {
    form.value.isSponsor = 0;
  }
  // 处理rebuy和rebuyLimit的显示逻辑
  if (res.data.rebuy > 0) {
    // 如果rebuy值>=0，说明是限制次数的情况
    form.value.rebuy = 1; // 设置为"限制次数"选项
    form.value.rebuyLimit = res.data.rebuy; // 将原值保存到rebuyLimit
  } else {
    // 否则保持原来的值(-1表示不可重复，0表示不限制)
    form.value.rebuy = res.data.rebuy;
    form.value.rebuyLimit = null;
  }
  // 确保tagId是数组格式
  if (!Array.isArray(form.value.tagId)) {
    form.value.tagId = form.value.tagId ? [form.value.tagId] : [];
  }

  // 确保categoryId是数组格式
  if (!Array.isArray(form.value.categoryId)) {
    form.value.categoryId = form.value.categoryId ? [form.value.categoryId] : [];
  }

  // 处理奖励表单数据
  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; // 设置模式
  nextTick(() => {
    loadItemStructuresOptions();
  });
};

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

    if (!valid) return;
    try {
      buttonLoading.value = true;
      // 当rebuy为1(限制次数)时，将rebuyLimit的值赋给rebuy
      let submitRebuyValue = data.form.rebuy;
      if (data.form.rebuy === 1) {
        submitRebuyValue = data.form.rebuyLimit;
      }
      // 确保tagId始终是数组格式
      let submitTagId = data.form.tagId;
      if (!Array.isArray(submitTagId)) {
        submitTagId = submitTagId ? [submitTagId] : [];
      }
      // 确保categoryId是数组格式
      if (!Array.isArray(form.value.categoryId)) {
        form.value.categoryId = form.value.categoryId ? [form.value.categoryId] : [];
      }
      // 构造最终要提交的数据对象
      const formData: TournamentsForm = {
        ...data.form,
        tagId: submitTagId, // 使用处理后的tagId值
        rebuy: submitRebuyValue, // 使用处理后的rebuy值
        competitionIcon: data.form.competitionIcon, // 确保 iconUrl 存在
        itemsPrizeList: formPrize.rewards.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();
    } 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 deleteCheckTournament(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 恢复比赛按钮操作 */
const handleRecoverTournament = async (row?: TournamentsVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认恢复比赛ID为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await recoverTournament(_ids);
  proxy?.$modal.msgSuccess('恢复成功');
  await getList();
};

/** 删除按钮操作 */
const deleteAllData = async (row?: TournamentsVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除比赛ID为"' + _ids + '"的所有关联数据项？').finally(() => (loading.value = false));
  await deleteRelationTournament(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};
const publishToTournament2 = async (row?: TournamentsVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否发布比赛ID为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await publishToTournament(_ids);
  proxy?.$modal.msgSuccess('发布成功');
  await getList();
};
/** 删除按钮操作 */
const closeSendTournamentOperate = async (row?: TournamentsVO) => {
  // 1. 获取要关闭的 ID 列表
  const _ids = row ? [row.id] : ids.value; // 始终为 number[]

  if (!_ids || _ids.length === 0) {
    proxy?.$modal.msgWarning('请至少选择一条记录');
    return;
  }

  // 2. 确认操作
  try {
    await proxy?.$modal.confirm(`是否确认关闭比赛ID为 "${_ids.join(', ')}" 的比赛？`);

    // 3. 批量关闭（假设 closeSendTournament 支持传数组）
    await closeSendTournament(_ids); // 推荐：API 支持批量

    // 如果 API 只支持单个，则用循环：
    // for (const id of _ids) {
    //   await closeSendTournament(id);
    // }

    proxy?.$modal.msgSuccess('操作成功');
    await getList();
  } catch (error) {
    // 用户取消或请求失败
    console.log('取消操作或操作失败');
  } finally {
    loading.value = false;
  }
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'business/tournaments/export',
    {
      ...queryParams.value
    },
    `赛事列表${parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}.xlsx`
  );
};

//导出审核数据
// 修改导出审核数据函数，传入比赛ID
const handleExportAuditData = () => {
  proxy?.download(
    'business/claims/export',
    {
      tournamentId: auditQueryParams.tournamentId
    },
    `领奖审核列表${parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}.xlsx`
  );
};

onMounted(() => {
  // 设置默认开始时间为今天
  const today = new Date();
  const yyyy = today.getFullYear();
  const mm = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以+1
  const dd = String(today.getDate()).padStart(2, '0');
  queryParams.value.startTime = `${yyyy}-${mm}-${dd}`;

  console.log('tournaments_type:', tournaments_type.value);
  console.log('tournaments_time:', tournaments_time.value);
  getList();
  loadItemOptions();
  loadItemStructuresOptions();

  // 直接调用 loadSelectData 来加载初始数据
  loadSelectData('');

  loadTagOptions();
  loadCategoryOptions();
  loadConfigOptions();
});

async function getAssignList() {
  const res = await getSelectTournamentBlindStructuresList(assignQuery);
  assignList.value = res.rows;
  assignTotal.value = res.total;
}

async function openAssignDialog(row: TournamentsVO) {
  assignForm.tournamentId = Number(row.id);
  assignQuery.tournamentId = Number(row.id); // 这里明确转成 number
  // 加载盲注列表

  assignDialog.visible = true;
  // 请求分配盲注结构列表
  getAssignList().then(() => {
    nextTick(() => {
      initSelectedRows(); // 等待 DOM 完全渲染后再初始化选中状态
    });
  });
}

function handleAssignSelectionChange(selection: TournamentsBindStructuresVO[]) {
  assignSelectedList.value = selection;
  assignForm.selectedIds = selection.map((item) => item.blindStructuresId);
}

async function submitAssign() {
  if (!assignForm.tournamentId || assignForm.selectedIds.length === 0) {
    proxy?.$modal.msgError('请选择至少一个盲注结构');
    return;
  }
  buttonLoading.value = true;
  try {
    await assignTournamentBlindStructures({
      tournamentId: assignForm.tournamentId,
      blindStructureIds: assignForm.selectedIds
    });

    proxy?.$modal.msgSuccess('分配成功');
    assignDialog.visible = false;
  } catch (err) {
    proxy?.$modal.msgError('分配失败');
  } finally {
    buttonLoading.value = false;
  }
}

const assignTable = ref(); // 对应 el-table 的 ref

// 初始化选中行
function initSelectedRows() {
  const selected = assignList.value.find((item) => item.allocationStatus === 1);
  if (selected) {
    selectedRadio.value = selected.blindStructuresId;
    assignForm.selectedIds = [selected.blindStructuresId];
  }
}
watch(
  () => form.value.gameType,
  (newVal) => {
    if (newVal === '3') {
      form.value.itemsId = null;
      form.value.itemsNum = null;
    }
  }
);
watch(
  () => assignList.value,
  (newVal) => {
    if (newVal.length > 0) {
      nextTick(() => {
        initSelectedRows();
      });
    }
  },
  { deep: true, immediate: true }
);

watch(
  () => selectedRadio.value,
  (newVal) => {
    if (newVal !== null) {
      assignForm.selectedIds = [newVal];
    } else {
      assignForm.selectedIds = [];
    }
  }
);

const handleIconChange = async (file) => {
  const index = fileList.value.findIndex((f) => f.uid === file.uid);
  fileList.value = [];

  if (file.raw) {
    iconPreviewUrl.value = URL.createObjectURL(file.raw);
  }

  if (index === -1) {
    // 如果文件不在列表中，则添加进去
    fileList.value.push(file);
  }

  try {
    const rawFile = file.raw;
    const res = await uploadTournament(rawFile);
    if (res.code === 200) {
      // 更新文件状态为成功
      fileList.value[index] = {
        ...file,
        status: 'success',
        response: res.data.url
      };
      data.form.competitionIcon = fileList.value[index].response;
      iconPreviewUrl.value = fileList.value[index].response;
      ElMessage.success('上传成功');
    } else {
      throw new Error(res.msg);
    }
  } catch (error) {
    // 更新文件状态为失败
    fileList.value[index] = {
      ...file,
      status: 'fail',
      error: '上传失败'
    };
    ElMessage.error('上传失败，请重试');
  }
};

const handleIconChange2 = async (file) => {
  const index = fileList2.value.findIndex((f) => f.uid === file.uid);
  fileList2.value = [];

  if (file.raw) {
    iconPreviewUrl2.value = URL.createObjectURL(file.raw);
  }

  if (index === -1) {
    // 如果文件不在列表中，则添加进去
    fileList2.value.push(file);
  }

  try {
    const rawFile = file.raw;
    const res = await uploadTournament(rawFile);
    if (res.code === 200) {
      // 更新文件状态为成功
      fileList2.value[index] = {
        ...file,
        status: 'success',
        response: res.data.url
      };
      data.form.competitionBg = fileList2.value[index].response;
      iconPreviewUrl2.value = fileList2.value[index].response;
      ElMessage.success('上传成功');
    } else {
      throw new Error(res.msg);
    }
  } catch (error) {
    // 更新文件状态为失败
    fileList2.value[index] = {
      ...file,
      status: 'fail',
      error: '上传失败'
    };
    ElMessage.error('上传失败，请重试');
  }
};

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 handlePreviewClick = () => {
  const currentSrc = iconPreviewUrl.value || competitionIcon.value;
  if (currentSrc) {
    dialogVisible.value = true;
  }
};
// 点击预览图触发放大
const handlePreviewClick2 = () => {
  const currentSrc = iconPreviewUrl2.value || competitionBg.value;
  if (currentSrc) {
    dialogVisible2.value = true;
  }
};

// 删除文件处理函数
const handleIconRemove = (file, updatedFileList) => {
  fileList.value = updatedFileList;
  // 清除预览图和临时链接
  iconPreviewUrl.value = '';
  competitionIcon.value = ''; // 如果需要清除后台加载的图标，可以在这里设置为空字符串
  // 同时清空表单数据中的图标链接
  data.form.competitionIcon = null;
};

// 删除文件处理函数
const handleIconRemove2 = (file, updatedFileList) => {
  fileList2.value = updatedFileList;
  // 清除预览图和临时链接
  iconPreviewUrl2.value = '';
  competitionBg.value = ''; // 如果需要清除后台加载的图标，可以在这里设置为空字符串
  // 同时清空表单数据中的背景图链接
  data.form.competitionBg = null;
};

// 排序字段和顺序
const sortData = ref({
  prop: 'startTime',
  order: 'descending' as 'ascending' | 'descending' | null
});

/**
 * 处理排序变化
 */
const handleSortChange = ({ prop, order }) => {
  if (prop === 'startTime') {
    sortData.value = {
      prop,
      order
    };
    // 触发重新加载数据
    getList();
  }
};

const auditDialog = ref({
  visible: false,
  title: '',
  mode: 'view' as 'view' | 'audit'
});

const tournamentInfo = ref<Partial<TournamentsVO>>({
  id: '',
  startTime: '',
  endTime: '',
  itemsNum: 0,
  itemsName: '',
  blindStructureId: 0,
  blindStructuresName: '',
  lateRegistrationLevel: 0,
  tournamentsBiId: '',
  signNum: 0,
  isComplaints: false
});

const auditData = ref<ClaimsVO[]>([]);
// 创建新的查询参数对象，不影响原始 queryParams
const auditQueryParams = {
  pageNum: 1,
  pageSize: 10,
  tournamentId: null as number | null
};
const auditTotal = ref(0);
// 模拟打开对话框并获取数据
const openAuditDialog = async (row: TournamentsVO | number, mode: 'view' | 'audit' = 'view') => {
  auditDialog.value.visible = true;
  auditDialog.value.mode = mode; // 设置模式

  let tournamentId: number;

  if (typeof row === 'number') {
    tournamentId = row;
  }

  auditQueryParams.tournamentId = tournamentId;
  await getAuditData(1);

  try {
    const res = await getTournaments(tournamentId);
    if (res.code === 200) {
      tournamentInfo.value = res.data;
    }
  } catch (error) {
    console.error('获取数据失败', error);
  }
};
const getAuditData = async (pageNum: number) => {
  try {
    auditQueryParams.pageNum = pageNum;
    const res = await listClaims(auditQueryParams);
    auditData.value = res.rows;
    auditTotal.value = res.total;
  } catch (error) {
    console.error('获取审核数据失败', error);
  }
};
// 关闭对话框
const cancelAudit = () => {
  auditDialog.value.visible = false;
  /*tournamentInfo.value = {};
  auditData.value = [];*/
};

const removeDialog = ref({
  visible: false,
  id: null,
  tournamentId: null,
  playerName: '',
  phone: ''
});

const handleClaimsDelete = (row: ClaimsVO) => {
  removeDialog.value.visible = true;
  removeDialog.value.id = row.id; // 假设 row 中有 id 字段
  removeDialog.value.tournamentId = row.tournamentId; // 假设 row 中有 tournamentId 字段
  removeDialog.value.playerName = row.playerName; // 假设 row 中有 playerName 字段
  removeDialog.value.phone = row.phone;
};

const cancelRemove = () => {
  removeDialog.value.visible = false;
};

const confirmRemove = async () => {
  try {
    const res = await deleteClaim({
      id: removeDialog.value.id,
      tournamentId: removeDialog.value.tournamentId
    });
    if (res.code === 200) {
      ElMessage.success('移除成功');
      // 重新加载审核数据
      const auditQueryParams = {
        pageNum: 1,
        pageSize: 10,
        tournamentId: tournamentInfo.value.id
      };
      const res2 = await listClaims(auditQueryParams);
      auditData.value = res2.rows;
      getAuditData(1);
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    ElMessage.error('移除失败，请重试');
  } finally {
    removeDialog.value.visible = false;
  }
};

// 审核操作
const handleAudit = async (row: ClaimsVO) => {
  try {
    await ElMessageBox.confirm('确定要审核该记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 用户点击了【确定】
    await auditSendReward(row); // 调用接口，假设接口接受 id 参数
    ElMessage.success('审核成功');
    getAuditData(1);
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消审核');
    } else {
      ElMessage.error('审核失败');
    }
  }
};

const handleViewLevelsSee = (tournamentsVO: TournamentsVO | undefined | null) => {
  if (!tournamentsVO || !tournamentsVO.blindStructureId) {
    proxy?.$modal.msgWarning('该赛事未绑定盲注等级');
    return;
  }

  dialogParams.value.blindStructureId = tournamentsVO.blindStructureId;
  dialogParams.value.name = tournamentsVO.blindStructuresName ?? '';
  levelsDialogVisible.value = true;
};

/** 修改按钮操作 */
const handleCopy = async (row?: TournamentsVO) => {
  reset(); // 重置表单
  const _id = row?.id || ids.value[0];
  const res = await getTournaments(_id);
  // 设置表单数据
  res.data.id = null;
  res.data.status = null;
  Object.assign(form.value, res.data);
  form.value.signTime = String(res.data.signTime);
  form.value.gameVariant = String(res.data.gameVariant);
  form.value.qualifierType = String(res.data.qualifierType);
  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;

  competitionIcon.value = res.data.competitionIcon;
  // 处理奖励表单数据
  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 handleViewHistory = (row: ClaimsVO) => {
  const tournamentId = row.tournamentId;
  const playerId = row.playerId;
  // 判断 playerId 是否有效（非 null、undefined）
  const playerIdStr = playerId != null ? String(playerId) : '';
  proxy?.$router.push({
    path: '/service/history',
    query: { tournamentId: String(tournamentId), playerId: playerIdStr }
  });
  auditDialog.value.visible = false;
};

const handleViewPublicHistory = (row: TournamentsVO) => {
  const tournamentId = row.id;
  const playerId = null;
  // 判断 playerId 是否有效（非 null、undefined）
  const playerIdStr = playerId != null ? String(playerId) : '';
  proxy?.$router.push({
    path: '/service/history',
    query: { tournamentId: String(tournamentId), playerId: playerIdStr }
  });
};

// 跳转到盲注表页面，并关闭当前弹窗
const handleGoToStructures = () => {
  dialog.visible = false; // 关闭弹窗
  // 使用 nextTick 确保关闭动画完成后跳转（可选）
  nextTick(() => {
    proxy?.$router.push('/tournament/structures');
  });
};
const handleGoToTag = () => {
  dialog.visible = false; // 关闭弹窗
  // 使用 nextTick 确保关闭动画完成后跳转（可选）
  nextTick(() => {
    proxy?.$router.push('/service/tag');
  });
};
const handleGoToCategory = () => {
  dialog.visible = false; // 关闭弹窗
  // 使用 nextTick 确保关闭动画完成后跳转（可选）
  nextTick(() => {
    proxy?.$router.push('/service/catory');
  });
};
// 获取奖励提示内容
const getRewardTooltipContent = (rewards: any[]) => {
  return rewards.map((prize) => `第${prize.ranking}名：${prize.quantity} ${prize.itemsName}`).join('\n');
};
// 判断是否为正式环境
const isProdEnvironment = computed(() => {
  // 根据实际项目中的环境变量判断是否为正式环境
  return import.meta.env.MODE === 'production' || import.meta.env.VITE_APP_ENV === 'prod';
});
// 在 setup 中添加
const selectOptions = ref<TournamentsVO[]>([]);
const selectLoading = ref(false);
const selectPageNum = ref(1);
const selectPageSize = ref(100); // 每页数量
const selectTotal = ref(0);
// 远程搜索方法
const remoteMethod = async (query: string) => {
  if (query !== '') {
    selectPageNum.value = 1;
    await loadSelectData(query);
  } else {
    selectOptions.value = [];
  }
};

// 加载数据（支持分页）
const loadSelectData = async (query: string) => {
  selectLoading.value = true;
  const params = {
    pageNum: selectPageNum.value,
    pageSize: selectPageSize.value,
    status: 0, // 只查 status=0
    name: query, // 搜索关键词
    sortBy: 'name',
    isAsc: true
  };

  try {
    const res = await listTournaments(params);
    const rows = res.rows || [];
    if (selectPageNum.value === 1) {
      selectOptions.value = rows;
    } else {
      selectOptions.value.push(...rows);
    }

    selectTotal.value = res.total;
  } catch (error) {
    console.error('加载比赛列表失败:', error);
  } finally {
    selectLoading.value = false;
  }
};

// 监听下拉框展开时触发加载
const handleSelectVisibleChange = async (visible: boolean) => {
  if (visible && selectOptions.value.length === 0) {
    await remoteMethod('');
  }
};

const handleQualifierTypeChange = (value: string) => {
  // Clear the qualifierValue when qualifierType changes
  form.value.qualifierValue = null;
};

// 下拉选项数据 selectBlingStructuresInfo
const itemOptionsTagList = ref<{ id: number; label: string }[]>([]);

// 加载报名条件选项
const loadTagOptions = async () => {
  try {
    const res = await selectTagSelList();
    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
        });
      }
      itemOptionsTagList.value = list;
    } else {
      alert('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
};
// 下拉选项数据 selectBlingStructuresInfo
const itemOptionsCategoryList = ref<{ id: number; label: string }[]>([]);

// 加载报名条件选项
const loadCategoryOptions = async () => {
  try {
    const res = await selectCategorySelList();
    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
        });
      }
      itemOptionsCategoryList.value = list;
    } else {
      alert('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
};
const handleIsDelayChange = (value: number) => {
  if (value === 0) {
    // 当选择"否"时，将延迟卡时间和数量设置为0
    form.value.delayCardTime = 0;
    form.value.delayCardNum = 0;
  } else {
    form.value.delayCardTime = 15;
    form.value.delayCardNum = 4;
  }
};
const getGameVariantText = (value: string | number | null | undefined): string => {
  const numValue = Number(value);
  switch (numValue) {
    case 0:
      return '德州扑克';
    case 1:
      return '奥马哈';
    case 2:
      return '短牌';
    default:
      return '未知';
  }
};
// 下拉选项数据 selectBlingStructuresInfo
const configOptions = ref<{ id: number; label: string }[]>([]);

// 加载报名条件选项
const loadConfigOptions = async () => {
  try {
    const res = await selectTournamentConfigSelList();
    if (res.code === 200) {
      // 类型断言
      const data = res.data as unknown as { id: number; name: string }[];
      // 过滤掉 id === 2 的项，并映射为 { id, label }
      configOptions.value = data.map((item) => ({
        id: item.id,
        label: item.name
      }));
    } else {
      ElMessage.error('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
    ElMessage.error('请求失败，请检查网络');
  }
};
</script>
<style scoped>
.more-rewards {
  cursor: pointer;
  color: #409eff;
  margin-left: 5px;
}
</style>
