<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="项目名称" prop="projectName">
              <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目归类" prop="classification">
              <el-select v-model="queryParams.classification" placeholder="请选择项目归类" clearable @change="handleQuery">
                <el-option v-for="dict in game_project_classification" :key="dict.value" :label="dict.label" :value="dict.value" />
              </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" class="table-card">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:gameEventProject:add']"> 新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Collection" @click="handleViewProjectLibrary()"> 项目库 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:gameEventProject:edit']"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:gameEventProject:remove']"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:gameEventProject:export']">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table 
        v-loading="loading" 
        border 
        :data="gameEventProjectList" 
        @selection-change="handleSelectionChange"
        max-height="calc(100vh - 280px)"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" fixed="left" type="index" />
        <el-table-column label="项目id" align="center" fixed="left" prop="projectId" v-if="columns[0].visible" />
        <el-table-column label="项目名称" align="center" width="180" fixed="left" prop="projectName" :show-overflow-tooltip="true" v-if="columns[1].visible" />
        <el-table-column label="项目类型" align="center" width="180" prop="projectType" :show-overflow-tooltip="true" v-if="columns[2].visible">
          <template #default="scope">
            <dict-tag :options="game_project_type" :value="scope.row.projectType || ''" />
          </template>
        </el-table-column>
        <el-table-column label="项目归类" align="center" width="105" sortable prop="classification" v-if="columns[3].visible" >
          <template #default="scope">
            <dict-tag :options="game_project_classification" :value="scope.row.classification || '未知'" />
          </template>
        </el-table-column>
        <el-table-column label="比赛场地" align="center" prop="location" v-if="columns[4].visible" />
        <el-table-column label="参赛性别" align="center" width="80" prop="gender" v-if="columns[17]?.visible">
          <template #default="scope">
            <dict-tag :options="sys_group_sex" :value="scope.row.gender || ''" />
          </template>
        </el-table-column>
        <el-table-column label="参赛组别" align="center" width="120" prop="rgName" v-if="columns[18]?.visible" />
        <el-table-column label="比赛阶段" align="center" prop="gameStage" v-if="columns[13].visible">
          <template #default="scope">
            <dict-tag :options="game_stage" :value="scope.row.gameStage || ''" />
          </template>
        </el-table-column>
        <el-table-column label="比赛轮次" align="center" prop="gameRound" v-if="columns[12].visible">
          <template #default="scope">
            <dict-tag :options="game_round" :value="scope.row.gameRound || ''" />
          </template>
        </el-table-column>
        <el-table-column label="成绩类型" align="center" width="105" prop="scoreRule" v-if="columns[5].visible">
          <template #default="scope">
            <dict-tag :options="game_score_type" :value="scope.row.scoreRule || ''" />
          </template>
        </el-table-column>
        <el-table-column label="排名方式" align="center" width="150" prop="orderType" :show-overflow-tooltip="true" v-if="columns[11].visible">
          <template #default="scope">
            <template v-if="scope.row.orderType">
              <dict-tag :options="game_order_type" :value="scope.row.orderType.split(',')" />
            </template>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center" sortable prop="startTime" width="180" v-if="columns[6].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" sortable prop="endTime" width="180" v-if="columns[7].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="录取名次" align="center" prop="roundType" v-if="columns[9].visible" />
        <el-table-column label="积分分值" align="center" prop="scoreValue" :show-overflow-tooltip="true" v-if="columns[11].visible" />
        <!-- <el-table-column label="裁判组" align="center" width="150" prop="refereeGroup" v-if="columns[8].visible">
          <template #default="scope">
            <el-button
              v-if="scope.row.refereeGroups && scope.row.refereeGroups.size > 0"
              type="primary"
              size="small"
              @click="handleViewRefereeGroup(scope.row.refereeGroups, scope.row.projectName)"
            >
              查看裁判组 ({{ scope.row.refereeGroups.length }}人)
            </el-button>
            <span v-else style="color: #999;">暂无裁判</span>
          </template>
        </el-table-column> -->
        <el-table-column label="参赛人数" align="center" sortable width="110" prop="athleteCount" v-if="columns[14].visible">
          <template #default="scope">
            <el-link type="primary" :underline="false" @click="handleViewStats(scope.row, 'athlete')">
              {{ scope.row.athleteCount || 0 }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="代表队数" align="center" sortable width="110" prop="teamCount" v-if="columns[15].visible">
          <template #default="scope">
            <el-link type="primary" :underline="false" @click="handleViewStats(scope.row, 'team')">
              {{ scope.row.teamCount || 0 }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="分组数" align="center" sortable width="110" prop="groupCount" v-if="columns[16].visible">
          <template #default="scope">
            <el-link type="primary" :underline="false" @click="handleViewStats(scope.row, 'group')">
              {{ scope.row.groupCount || 0 }}
            </el-link>
          </template>
        </el-table-column>
        
        
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:gameEventProject:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:gameEventProject:remove']"
              ></el-button>
            </el-tooltip>
          </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="850px" append-to-body>
      <el-form ref="gameEventProjectFormRef" :model="form" :rules="rules" label-width="100px">
        
        <el-divider content-position="left">
          <el-icon style="vertical-align: middle; margin-right: 5px;"><InfoFilled /></el-icon>
          <span style="vertical-align: middle; font-weight: bold;">基础信息</span>
        </el-divider>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目类型" prop="projectType">
              <div style="display: flex; width: 100%; align-items: center">
                <el-select v-model="form.projectType" filterable clearable placeholder="请选择项目类型" style="flex: 1">
                  <el-option v-for="dict in game_project_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
                <el-button link type="primary" icon="Plus" style="margin-left: 5px; font-size: 18px" @click="handleAddProjectType" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="参赛性别" prop="gender">
              <el-radio-group v-model="form.gender">
                <el-radio v-for="dict in sys_group_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="参赛组别" prop="rgId">
              <div style="display: flex; width: 100%; align-items: center">
                <el-select v-model="form.rgId" filterable placeholder="请选择参赛组别" style="flex: 1" @change="handleRankGroupChange">
                  <el-option v-for="item in rankGroupOptions" :key="item.rgId" :label="item.rgName" :value="item.rgId" />
                </el-select>
                <el-button link type="primary" icon="Plus" style="margin-left: 5px; font-size: 18px" @click="handleAddRankGroup" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目归类" prop="classification">
              <el-radio-group v-model="form.classification">
                <el-radio v-for="dict in game_project_classification" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="比赛场地" prop="location">
              <el-input v-model="form.location" placeholder="请输入比赛场地" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">
          <el-icon style="vertical-align: middle; margin-right: 5px;"><Operation /></el-icon>
          <span style="vertical-align: middle; font-weight: bold;">规则配置</span>
        </el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="比赛阶段" prop="gameStage">
              <el-radio-group v-model="form.gameStage">
                <el-radio v-for="dict in game_stage" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="比赛轮次" prop="gameRound">
              <el-radio-group v-model="form.gameRound">
                <el-radio v-for="dict in game_round" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-radio-group>
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <div style="background-color: #f8f9fb; padding: 15px; border-radius: 8px; margin-bottom: 20px;">
              <el-form-item label="成绩类型" prop="scoreRule">
                <el-radio-group v-model="form.scoreRule" style="width: 100%">
                  <el-row :gutter="10" style="width: 100%">
                    <el-col :span="6"><el-radio value="1">计时类</el-radio></el-col>
                    <el-col :span="6"><el-radio value="2">距离类</el-radio></el-col>
                    <el-col :span="6"><el-radio value="3">单次计数</el-radio></el-col>
                    <el-col :span="6"><el-radio value="4">多次计数</el-radio></el-col>
                    <el-col :span="6"><el-radio value="5">排名类</el-radio></el-col>
                    <el-col :span="6"><el-radio value="6">远度距离</el-radio></el-col>
                    <el-col :span="6"><el-radio value="7">高度距离</el-radio></el-col>
                  </el-row>
                </el-radio-group>
              </el-form-item>

              <!-- 子配置项 -->
              <el-row v-if="form.scoreRule === '1' || ['2', '6', '7'].includes(form.scoreRule) || form.scoreRule === '3' || form.scoreRule === '4'">
                <el-col :span="12" v-if="form.scoreRule === '1'">
                  <el-form-item label="计时格式" prop="timingFormat">
                    <el-radio-group v-model="form.timingFormat">
                      <el-radio value="0">00:00:00.000</el-radio>
                      <el-radio value="1">00:00.00</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="['2', '6', '7'].includes(form.scoreRule)">
                  <el-form-item label="距离模式" prop="distanceMode">
                    <el-radio-group v-model="form.distanceMode">
                      <el-radio value="0">单轮最高</el-radio>
                      <el-radio value="1">双轮最高</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="form.scoreRule === '3' || form.scoreRule === '4'">
                  <el-form-item label="计数单位" prop="countUnit">
                    <el-radio-group v-model="form.countUnit">
                      <el-radio label="个">个</el-radio>
                      <el-radio label="分">分</el-radio>
                      <el-radio label="环">环</el-radio>
                      <el-radio label="条">条</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="['2', '4', '6', '7'].includes(form.scoreRule)">
                  <el-form-item label="成绩数量" prop="scoreCount">
                    <template #label>
                      <span>
                        <el-tooltip :content="form.scoreRule === '4' ? '多次计数的总轮次' : '距离类建议根据模式选择，单轮选1，双轮选2'" placement="top">
                          <el-icon style="cursor: pointer; color: #409eff; margin-right: 2px;"><QuestionFilled /></el-icon>
                        </el-tooltip>
                        成绩数量
                      </span>
                    </template>
                    <el-input-number v-model="form.scoreCount" :min="1" :max="20" size="small" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-divider border-style="dashed" style="margin: 12px 0" />

              <el-form-item label="排名方式">
                <div class="order-type-combined">
                  <div class="order-row">
                    <span class="order-label">排序方向：</span>
                    <el-radio-group v-model="orderGroup.val1" clearable @change="handleOrderChange(1)">
                      <el-radio value="0" :disabled="orderGroup.val3 === '4'">升序（1...9）</el-radio>
                      <el-radio value="1" :disabled="orderGroup.val3 === '4'">降序（9...1）</el-radio>
                    </el-radio-group>
                  </div>
                  <div class="order-row" v-if="form.scoreRule === '3'">
                    <span class="order-label">特殊规则：</span>
                    <el-radio-group v-model="orderGroup.val2" clearable @change="handleOrderChange(2)">
                      <el-radio value="2">失误次数A（1...9）</el-radio>
                      <el-radio value="3">失误次数B（9...1）</el-radio>
                    </el-radio-group>
                  </div>
                  <div class="order-row" v-if="['2', '4', '6', '7'].includes(form.scoreRule)">
                    <span class="order-label">统计逻辑：</span>
                    <el-radio-group v-model="orderGroup.val3" clearable @change="handleOrderChange(3)">
                      <el-radio value="4">求和</el-radio>
                      <el-radio value="5">最大值</el-radio>
                      <el-radio value="6">最小值</el-radio>
                      <el-radio value="7">平均值</el-radio>
                    </el-radio-group>
                  </div>
                </div>
              </el-form-item>
            </div>
          </el-col>
        </el-row>

        <el-divider content-position="left">
          <el-icon style="vertical-align: middle; margin-right: 5px;"><Calendar /></el-icon>
          <span style="vertical-align: middle; font-weight: bold;">录取与时间</span>
        </el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="录取名次" prop="roundType">
              <el-input v-model="form.roundType" placeholder="请输入录取名次" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="限报人数" prop="limitPerson">
              <template #label>
                <span>
                  <el-tooltip content="单个项目限报人数，0为不限制" placement="top">
                    <el-icon style="cursor: pointer; color: #409eff; margin-right: 2px;"><QuestionFilled /></el-icon>
                  </el-tooltip>
                  限报人数
                </span>
              </template>
              <el-input-number v-model="form.limitPerson" :min="0" style="width: 100%" controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="积分分值" prop="scoreValue">
              <template #label>
                <span>
                  <el-tooltip content="名次对应积分，逗号分隔。如：10,8,6,5,4,3,2,1" placement="top">
                    <el-icon style="cursor: pointer; color: #409eff; margin-right: 2px;"><QuestionFilled /></el-icon>
                  </el-tooltip>
                  积分分值
                </span>
              </template>
              <el-input v-model="form.scoreValue" type="textarea" :rows="2" placeholder="请输入积分分值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <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="开始时间" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker clearable v-model="form.endTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="结束时间" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">
          <el-icon style="vertical-align: middle; margin-right: 5px;"><User /></el-icon>
          <span style="vertical-align: middle; font-weight: bold;">报名限制</span>
        </el-divider>
        <el-row :gutter="20">
          <template v-if="form.classification === '0'">
            <el-col :span="12">
              <el-form-item label="限报男" prop="limitMale">
                <el-input-number v-model="form.limitMale" :min="0" style="width: 100%" placeholder="限报男生人数" controls-position="right" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="限报女" prop="limitFemale">
                <el-input-number v-model="form.limitFemale" :min="0" style="width: 100%" placeholder="限报女生人数" controls-position="right" />
              </el-form-item>
            </el-col>
          </template>
          <template v-else-if="form.classification === '1'">
            <el-col :span="8">
              <el-form-item label="限报队数" prop="limitTeam">
                <el-input-number v-model="form.limitTeam" :min="0" style="width: 100%" placeholder="限报队伍数" controls-position="right" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="每队限男" prop="limitMale">
                <el-input-number v-model="form.limitMale" :min="0" style="width: 100%" placeholder="每队限报男生" controls-position="right" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="每队限女" prop="limitFemale">
                <el-input-number v-model="form.limitFemale" :min="0" style="width: 100%" placeholder="每队限报女生" controls-position="right" />
              </el-form-item>
            </el-col>
          </template>
        </el-row>
        
        <el-divider content-position="left">
          <el-icon style="vertical-align: middle; margin-right: 5px;"><EditPen /></el-icon>
          <span style="vertical-align: middle; font-weight: bold;">其他</span>
        </el-divider>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm()">确 定</el-button>
          <el-button v-if="!form.projectId" :loading="buttonLoading" type="success" @click="submitForm(true)">保存并继续</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 裁判组查看对话框 -->
    <RefereeGroupDialog ref="refereeGroupDialogRef" />

    <!-- 项目库查看对话框 -->
    <ProjectLibraryDialog ref="projectLibraryDialog" @confirm="handleLibraryConfirm" />

    <!-- 统计详情对话框 -->
    <StatsDetailDialog ref="statsDetailDialogRef" />
  </div>
</template>

<script setup name="GameEventProject" lang="ts">
import {
  listGameEventProject,
  listGameEventProjectWithStats,
  getGameEventProject,
  delGameEventProject,
  addGameEventProject,
  updateGameEventProject,
  BatchAddProject
} from '@/api/system/gameEventProject';
import { addData, listData } from '@/api/system/dict/data';
import { listRankGroup, addRankGroup } from '@/api/system/rankGroup';
import { listGameEventGroup } from '@/api/system/gameEventGroup';
import { GameEventProjectVO, GameEventProjectQuery, GameEventProjectForm } from '@/api/system/gameEventProject/types';
import RefereeGroupDialog from './RefereeGroupDialog.vue';
import ProjectLibraryDialog from './ProjectLibraryDialog.vue';
import StatsDetailDialog from './StatsDetailDialog.vue';
import { ElMessageBox } from 'element-plus';
import { useGameEventStore } from '@/store/modules/gameEvent';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { game_score_type, game_project_type, game_project_classification, game_round, game_stage, sys_group_sex, game_order_type } = toRefs<any>(proxy?.useDict('game_score_type', 'game_project_type', 'game_project_classification', 'game_round', 'game_stage', 'sys_group_sex', 'game_order_type'));

const gameEventGroupList = ref<any[]>([]); // ·б

const gameEventProjectList = ref<GameEventProjectVO[]>([]);
const rankGroupOptions = ref<any[]>([]);
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 gameEventProjectFormRef = ref<ElFormInstance>();

// 定义 RefereeGroupDialog 组件的类型
interface RefereeGroupDialogInstance {
  openDialog: (refereeGroups: string[], projectName: string) => void;
}
// 定义 ProjectLibraryDialog 组件的类型
interface ProjectLibraryDialogInstance {
  openDialog: () => void;
}

const refereeGroupDialogRef = ref<(InstanceType<typeof RefereeGroupDialog> & RefereeGroupDialogInstance) | null>(null);
const projectLibraryDialog = ref<(InstanceType<typeof ProjectLibraryDialog> & ProjectLibraryDialogInstance) | null>(null);
const statsDetailDialogRef = ref<any>(null);

// 排名方式组合逻辑
const orderGroup = reactive({
  val1: null as string | null,
  val2: null as string | null,
  val3: null as string | null
});

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 列显隐数据
const columns = ref<FieldOption[]>([
  { key: 0, label: '项目id', visible: false },
  { key: 1, label: '项目名称', visible: true },
  { key: 2, label: '项目类型', visible: true },
  { key: 3, label: '归类', visible: true },
  { key: 4, label: '比赛场地', visible: true },
  { key: 5, label: '计算规则', visible: true },
  { key: 6, label: '开始时间', visible: true },
  { key: 7, label: '结束时间', visible: true },
  { key: 8, label: '裁判组', visible: true },
  { key: 9, label: '录取名次', visible: true },
  { key: 10, label: '积分分值', visible: true },
  { key: 11, label: '排名方式', visible: true },
  { key: 12, label: '比赛轮次', visible: true },
  { key: 13, label: '比赛阶段', visible: true },
  { key: 14, label: '参赛人数', visible: true },
  { key: 15, label: '代表队数', visible: true },
  { key: 16, label: '分组数', visible: true },
  { key: 17, label: '参赛性别', visible: true },
  { key: 18, label: '参赛组别', visible: true }
]);

const initFormData: GameEventProjectForm = {
  projectId: undefined,
  eventId: undefined,
  projectName: undefined,
  projectType: undefined,
  classification: '0',
  refereeGroups: undefined,
  location: undefined,
  startTime: undefined,
  endTime: undefined,
  groupNum: undefined,
  participateNum: undefined,
  limitPerson: 0,
  roundType: undefined,
  orderType: '0',
  scoreRule: '1',
  scoreValue: undefined,
  award: undefined,
  gameRound: undefined,
  gameStage: undefined,
  gender: undefined,
  rgName: undefined,
  rgId: undefined,
  status: '0',
  remark: undefined,
  timingFormat: '0',
  distanceMode: '0',
  countUnit: '个',
  scoreCount: 1,
  limitMale: 0,
  limitFemale: 0,
  limitTeam: 0
};
const data = reactive<PageData<GameEventProjectForm, GameEventProjectQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    classification: undefined,
    orderByColumn: undefined,
    isAsc: undefined,
  },
  rules: {
    projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
    projectType: [{ required: true, message: '项目类型不能为空', trigger: 'change' }],
    classification: [{ required: true, message: '归类不能为空', trigger: 'change' }],
    orderType: [{ required: true, message: '排序方式不能为空', trigger: 'change' }],
    scoreRule: [{ required: true, message: '成绩类型不能为空', trigger: 'change' }]
  }
});

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

/** 查询赛事项目列表 */
const getList = async () => {
  loading.value = true;
  const res = await listGameEventProjectWithStats(queryParams.value);
  gameEventProjectList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 查询排名分组列表 */
const getRankGroupOptions = async () => {
  const res = await listRankGroup();
  rankGroupOptions.value = res.rows;
};

/** 查询赛事分组列表 */
const getGameEventGroupList = async () => {
  const res = await listGameEventGroup({
    pageNum: 1,
    pageSize: 10,
    orderByColumn: undefined,
    isAsc: undefined,
  });
  gameEventGroupList.value = res.data;
};

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

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

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加赛事项目';
};

/** 修改按钮操作 */
const handleUpdate = (row?: GameEventProjectVO) => {
  reset();
  const projectId = row?.projectId || ids.value.at(0);
    getGameEventProject(projectId).then(response => {
      Object.assign(form.value, response.data);
      // 处理排名方式回显
      nextTick(() => {
        orderGroup.val1 = null; orderGroup.val2 = null; orderGroup.val3 = null;
        if (form.value.orderType) {
          const types = form.value.orderType.split(',');
          types.forEach(t => {
            if (['0', '1'].includes(t)) orderGroup.val1 = t;
            if (['2', '3'].includes(t)) orderGroup.val2 = t;
            if (['4', '5', '6', '7'].includes(t)) orderGroup.val3 = t;
          });
        }
      });
      dialog.visible = true;
      dialog.title = '修改赛事项目';
    });
};

/** 提交按钮 */
const submitForm = (isContinue = false) => {
  gameEventProjectFormRef.value?.validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      const submitData = { ...form.value };
      
      // 合并排名方式
      const orderTypes = [];
      if (orderGroup.val1) orderTypes.push(orderGroup.val1);
      if (orderGroup.val2) orderTypes.push(orderGroup.val2);
      if (orderGroup.val3) orderTypes.push(orderGroup.val3);
      submitData.orderType = orderTypes.join(',');

      if (submitData.projectId !== undefined) {
        updateGameEventProject(submitData).then(response => {
          proxy?.$modal.msgSuccess('修改成功');
          dialog.visible = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addGameEventProject(submitData).then(response => {
          proxy?.$modal.msgSuccess('新增成功');
          if (isContinue) {
            // 保存并继续：不关闭弹窗，并确保 projectId 为空
            form.value.projectId = undefined;
          } else {
            dialog.visible = false;
          }
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
};

/** 监听成绩类型变化，重置子配置和排名方式建议 */
watch(() => form.value.scoreRule, (newVal) => {
  // 如果是修改模式且已经有值，不进行重置初始化
  if (form.value.projectId) return;

  orderGroup.val1 = null; orderGroup.val2 = null; orderGroup.val3 = null;
  if (newVal === '1') { // 计时类
    form.value.timingFormat = '0';
    orderGroup.val1 = '0'; // 计时通常升序
  } else if (['2', '6', '7'].includes(newVal)) { // 距离相关类
    form.value.distanceMode = '0';
    form.value.scoreCount = 1; // 距离类默认1轮
    orderGroup.val1 = '1'; // 距离通常降序
  } else if (newVal === '3') { // 单次计数
    form.value.countUnit = '个';
    orderGroup.val1 = '1';
  } else if (newVal === '4') { // 多次计数
    form.value.countUnit = '个';
    form.value.scoreCount = 3; // 多次计数默认给3轮
    orderGroup.val3 = '4'; // 默认求和
  } else if (newVal === '5') { // 排名类
    orderGroup.val1 = '0';
  }
});

/** 参赛组别切换 */
const handleRankGroupChange = (val: string | number) => {
  const group = rankGroupOptions.value.find(item => item.rgId === val);
  if (group) {
    form.value.rgName = group.rgName;
  } else {
    form.value.rgName = undefined;
  }
};

/** 处理排名方式切换逻辑 */
const handleOrderChange = (type: number) => {
  if (type === 3 && orderGroup.val3 === '4') {
    // 选中求和，清空第一层
    orderGroup.val1 = null;
  }
};

/** 删除按钮操作 */
const handleDelete = (row?: GameEventProjectVO) => {
  const projectIds = row?.projectId || ids.value;
  proxy?.$modal.confirm('是否确认删除赛事项目ID为"' + projectIds + '"的数据项？').then(function () {
    return delGameEventProject(projectIds);
  }).then(() => {
    getList();
    proxy?.$modal.msgSuccess('删除成功');
  }).catch(() => {proxy?.$modal.msgSuccess('删除失败');});
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/gameEventProject/export',
    {
      ...queryParams.value
    },
    `${useGameEventStore().defaultEventInfo?.eventCode || ''}_项目列表.xlsx`
  );
};

/** 查看裁判组 */
const handleViewRefereeGroup = (refereeGroups: string[], projectName: string) => {
  refereeGroupDialogRef.value?.openDialog(refereeGroups, projectName);
};

/** 查看项目库 */
const handleViewProjectLibrary = () => {
  projectLibraryDialog.value?.openDialog();
};

/** 查看统计详情 */
const handleViewStats = (row: GameEventProjectVO, type: 'athlete' | 'team' | 'group') => {
  statsDetailDialogRef.value?.openDialog(row.projectId, row.projectName, type);
};

/** 处理项目库选择确认 */
const handleLibraryConfirm = async (projects: GameEventProjectVO[]) => {
  try {
      // 调用添加接口
      await BatchAddProject(projects);
    } catch (error) {
      console.error('添加项目失败:', error);
      proxy?.$modal.msgError(`添加项目失败`);
    }
  
  proxy?.$modal.msgSuccess(`成功添加${projects.length}个项目`);
  getList(); // 刷新列表
};

/** 添加项目类型 */
const handleAddProjectType = () => {
  ElMessageBox.prompt('请输入新的项目类型名称', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\S+/,
    inputErrorMessage: '项目类型名称不能为空'
  }).then(async ({ value }) => {
    try {
      // 1. 实时获取最新的字典数据，避免缓存导致的冲突
      const res = await listData({
        dictType: 'game_project_type',
        pageNum: 1,
        pageSize: 100
      } as any);
      
      const latestDicts = res.rows || [];
      
      // 2. 计算当前最大值和排序
      let maxSort = 0;
      let maxValue = 0;
      latestDicts.forEach((item: any) => {
        const val = parseInt(item.dictValue);
        if (!isNaN(val) && val > maxValue) {
          maxValue = val;
        }
        const sort = item.dictSort;
        if (sort !== undefined && sort !== null && sort > maxSort) {
          maxSort = sort;
        }
      });

      const newValue = (maxValue + 1).toString();
      const newSort = maxSort + 1;

      const newDict: any = {
        dictLabel: value,
        dictValue: newValue,
        dictSort: newSort,
        dictType: 'game_project_type',
        status: '0'
      };

      // 3. 提交新增
      await addData(newDict);
      proxy?.$modal.msgSuccess('添加成功');

      // 4. 更新当前页面的字典数据（用于下拉框显示）
      game_project_type.value.push({
        label: value,
        value: newValue,
        elTagType: 'default',
        elTagClass: ''
      });
      
      // 5. 自动选中新添加的项目类型
      form.value.projectType = newValue;
    } catch (error: any) {
      if (error !== 'cancel') {
        console.error('添加项目类型失败:', error);
        proxy?.$modal.msgError(error.msg || '添加项目类型失败');
      }
    }
  });
};

/** 添加排名分组 */
const handleAddRankGroup = () => {
  ElMessageBox.prompt('请输入新的组别名称', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\S+/,
    inputErrorMessage: '组别名称不能为空'
  }).then(async ({ value }) => {
    try {
      const newGroup: any = {
        rgName: value,
        parentId: 0,
        sortNum: 0,
        status: '0'
      };
      await addRankGroup(newGroup);
      proxy?.$modal.msgSuccess('添加组别成功');
      // 刷新组别列表
      await getRankGroupOptions();
    } catch (error: any) {
      if (error !== 'cancel') {
        proxy?.$modal.msgError(error.msg || '添加组别失败');
      }
    }
  });
};

onMounted(() => {
  getList();
  getRankGroupOptions();
  // getGameEventGroupList();
});

</script>

<style scoped>
.order-type-combined {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.order-row {
  display: flex;
  align-items: center;
}
.order-label {
  font-size: 13px;
  color: #606266;
  width: 85px;
  flex-shrink: 0;
}
.order-divider {
  margin: 0 10px;
  color: #dcdfe6;
}
:deep(.el-divider__text) {
  font-size: 15px;
  color: #303133;
  font-weight: bold;
}
:deep(.el-form-item__label) {
  font-weight: 500;
}
.table-card :deep(.el-card__body) {
  padding: 10px;
}
.el-table {
  margin-bottom: 10px;
}
</style>
