<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="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>
          <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="比赛名" align="center" prop="name" />
        <el-table-column label="比赛Logo" align="center">
          <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" 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">
          <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" prop="lateRegistrationLevel" />
        <el-table-column label="盲注表" align="center" prop="blindStructuresName" />

        <el-table-column label="奖励" align="center">
          <template #default="scope">
            <div v-for="(prize, index) in scope.row.itemsPrizeList" :key="index">
              第{{ prize.ranking }}名：{{ prize.quantity }} {{ prize.itemsName }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="状态" align="center" prop="statusText" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="320">
          <template #default="scope">
            <div class="operation-buttons-vertical">
              <el-tooltip content="查看" placement="top">
                <el-button link type="primary" @click="handleUpdate(scope.row, 'view')" icon="View">查看</el-button>
              </el-tooltip>

              <el-tooltip content="编辑" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row, 'edit')">编辑</el-button>
              </el-tooltip>

              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(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="600px" append-to-body @close="cancel">
      <el-form ref="tournamentsFormRef" :model="form" :rules="rules" label-width="120px">
        <!-- 赛事名称 -->
        <el-form-item label="比赛名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入比赛名称" :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"
              :limit="1"
              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="startTime">
          <el-date-picker
            clearable
            v-model="form.startTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择开始时间"
            :disabled="dialog.mode === 'view'"
          />
        </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="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" :min="1" placeholder="数量" :disabled="dialog.mode === 'view'" />
          </div>
        </el-form-item>

        <!-- 盲注表 -->
        <el-form-item label="盲注表" prop="blindStructureId">
          <div style="display: flex; align-items: center">
            <el-select
              v-model="form.blindStructureId"
              placeholder="选项"
              style="width: 200px"
              @change="handleBlindStructureChange"
              :disabled="dialog.mode === 'view'"
            >
              <el-option v-for="item in itemOptionsStructures" :key="item.id" :label="item.label" :value="item.id" />
            </el-select>

            <el-button type="primary" :disabled="dialog.mode === 'view'" @click="handleGoToStructures"> 上传新盲注 </el-button>
            <el-button type="primary" @click="handleViewLevels" :disabled="dialog.mode === 'view'">预览</el-button>
          </div>
        </el-form-item>

        <!-- 报名截止等级 -->
        <el-form-item label="报名截止等级" prop="lateRegistrationLevel">
          <el-select v-model="form.lateRegistrationLevel" placeholder="选项" style="width: 200px" :disabled="dialog.mode === 'view'">
            <el-option v-for="item in itemOptionsStructuresLevel" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </el-form-item>

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

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

        <el-form-item label="机器人数" prop="robotCount">
          <el-input v-model="form.robotCount" placeholder="请输入机器人数" :disabled="dialog.mode === 'view'" />
        </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>

      <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>
  </div>
</template>

<script setup name="Tournaments" lang="ts">
import {
  listTournaments,
  getTournaments,
  delTournaments,
  addTournaments,
  updateTournaments,
  getSelectTournamentBlindStructuresList,
  assignTournamentBlindStructures,
  uploadTournament
} from '@/api/system/business/tournamentsTemplate';
import { selectItemsSelList } from '@/api/system/business/items';
import { selectBlindLevelsById } from '@/api/system/business/levels';
import { selectBlingStructuresInfo } from '@/api/system/business/structures';
import { TournamentsVO, TournamentsQuery, TournamentsForm, TournamentsBindStructuresVO } from '@/api/system/business/tournamentsTemplate/types';
import { ref } from 'vue';
import LevelsIndex from '@/views/system/business/levels/index.vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { tournaments_type, tournaments_time } = toRefs<any>(proxy?.useDict('tournaments_type', 'tournaments_time'));

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'; // 新增字段
}>({
  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('');

function openPreview(src: string) {
  previewSrc.value = src;
  dialogVisible.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;
    } else {
      alert('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
};

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

// 加载报名条件选项
const handleBlindStructureChange = async (value: number) => {
  try {
    const res = await selectBlindLevelsById(value);
    if (res.code === 200) {
      // 使用 unknown 中间类型进行类型转换
      const data = res.data as unknown as { id: number; levelNumber: number }[];
      const list = [];
      for (let i = 0; i < data.length; i++) {
        const item = data[i];
        list.push({
          id: item.levelNumber,
          label: item.levelNumber
        });
      }
      itemOptionsStructuresLevel.value = list;
    } 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([]);

// 单选控制变量（用于绑定 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,
  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: []
};
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' }],
    gameType: [{ required: true, message: '游戏类型不能为空', trigger: 'change' }],
    lateRegistrationLevel: [{ required: true, message: '截止报名级别不能为空', trigger: 'change' }],
    signTime: [{ required: true, message: '报名时间不能为空', trigger: 'change' }],
    itemsId: [{ required: true, message: '报名条件不能为空', trigger: 'change' }],
    blindStructureId: [{ required: true, message: '盲注表不能为空', trigger: 'change' }]
  }
});

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 = ''; // 如果需要清除后台加载的图标，可以在这里设置为空字符串
  dialog.visible = false;
};

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

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

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

/** 多选框选中数据 */
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 = ''; // 如果需要清除后台加载的图标，可以在这里设置为空字符串
  dialog.visible = true;
  dialog.title = '创建自动比赛模版';
  dialog.mode = 'edit'; // 设置模式
};
// 重置函数
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);
  // 确保 gameType 是 number 类型
  const gameType = Number(res.data.gameType);
  const signTime = Number(res.data.signTime);
  // 设置表单数据
  Object.assign(form.value, res.data);
  form.value.gameType = gameType; // 确保赋值正确
  form.value.signTime = signTime;

  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
      }
    ];
  }

  dialog.visible = true;
  dialog.title = mode === 'view' ? '查看自动比赛模版' : '编辑自动比赛模版';
  dialog.mode = mode; // 设置模式
};

/** 提交按钮 */
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;

      // 构造最终要提交的数据对象
      const formData: TournamentsForm = {
        ...data.form,
        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('是否确认删除【赛事信息】编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delTournaments(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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

onMounted(() => {
  getList();
  loadItemOptions();
  loadItemStructuresOptions();
});

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(
  () => 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 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 handleIconRemove = (file, updatedFileList) => {
  fileList.value = updatedFileList;
  // 清除预览图和临时链接
  iconPreviewUrl.value = '';
  competitionIcon.value = ''; // 如果需要清除后台加载的图标，可以在这里设置为空字符串
};

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

/**
 * 处理排序变化
 */
const handleSortChange = ({ prop, order }) => {
  if (prop === 'startTime') {
    sortData.value = {
      prop,
      order
    };
    // 触发重新加载数据
    getList();
  }
};
// 跳转到盲注表页面，并关闭当前弹窗
const handleGoToStructures = () => {
  dialog.visible = false; // 关闭弹窗
  // 使用 nextTick 确保关闭动画完成后跳转（可选）
  nextTick(() => {
    proxy?.$router.push('/business/structures');
  });
};
</script>
