<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="赛事名称" 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 label="记分牌数量" prop="startingChips">
              <el-input v-model="queryParams.startingChips" placeholder="请输入起始记分牌数量" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="持续时间" prop="levelDuration">
              <el-input v-model="queryParams.levelDuration" placeholder="请输入级别持续时间" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="报名级别" prop="lateRegistrationLevel">
              <el-input v-model="queryParams.lateRegistrationLevel" placeholder="请输入截止报名级别" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="最大参赛人数" prop="maxPlayers">
              <el-input v-model="queryParams.maxPlayers" placeholder="请输入最大参赛人数" clearable @keyup.enter="handleQuery" />
            </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
            >
          </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="info" plain icon="Operation">
              <router-link to="/business/structures">盲注管理</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">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="" align="center" prop="id" v-if="false" />
        <el-table-column label="赛事名称" align="center" prop="name" />
        <el-table-column label="开始时间" align="center" prop="startTime" width="180">
          <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" prop="gameType" />
        <el-table-column label="起始记分牌数量" align="center" prop="startingChips" />
        <el-table-column label="级别持续时间" align="center" prop="levelDuration" />
        <el-table-column label="截止报名级别" align="center" prop="lateRegistrationLevel" />
        <el-table-column label="最大参赛人数" align="center" prop="maxPlayers" />
        <el-table-column label="赛事状态" align="center" prop="status" />

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看" placement="top">
              <el-button
                link
                type="primary"
                icon="View"
                @click="handleUpdate(scope.row, 'view')"
                v-hasPermi="['business:tournaments:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row, 'edit')"
                v-hasPermi="['business:tournaments:edit']"
              ></el-button>
            </el-tooltip>
            <!--            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:tournaments:remove']"></el-button>
            </el-tooltip>-->

            <!-- 新增：分配按钮 -->
            <el-tooltip content="分配盲注" placement="top">
              <el-button link type="success" icon="Document" @click="openAssignDialog(scope.row)" v-hasPermi="['business:tournaments:assign']">
                分配
              </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="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="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"
              :auto-upload="false"
              :limit="1"
              accept="image/*"
              :disabled="dialog.mode === 'view'"
            >
              <template #trigger>
                <el-button type="primary" :disabled="dialog.mode === 'view'">点击选择图标</el-button>
              </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="报名时间">
          <el-select v-model="form.signTime" placeholder="请选择" :disabled="dialog.mode === 'view'">
            <el-option label="比赛前5分钟" :value="5" />
            <el-option label="比赛前10分钟" :value="10" />
          </el-select>
        </el-form-item>

        <!-- 报名条件 -->
        <el-form-item label="报名条件">
          <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="盲注表">
          <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'">上传新盲注</el-button>
            <el-button type="primary" @click="handleViewLevels" :disabled="dialog.mode === 'view'">预览</el-button>
          </div>
        </el-form-item>

        <!-- 报名截止等级 -->
        <el-form-item label="报名截止等级">
          <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="奖励内容">
          <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>
  </div>
</template>

<script setup name="Tournaments" lang="ts">
import {
  listTournaments,
  getTournaments,
  delTournaments,
  addTournaments,
  updateTournaments,
  getSelectTournamentBlindStructuresList,
  assignTournamentBlindStructures,
  uploadTournament
} from '@/api/system/business/tournaments';
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/tournaments/types';
import { ref } from 'vue';
import LevelsIndex from '@/views/system/business/levels/index.vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

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

// 控制 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) {
      // 使用 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
        });
      }
      itemOptions.value = list;
    } else {
      alert('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', 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 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;
  });
};

// 单选控制变量（用于绑定 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: null,
  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,
    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' }],*/
    startingChips: [{ required: true, message: '起始记分牌数量不能为空', trigger: 'blur' }],
    levelDuration: [{ required: true, message: '级别持续时间不能为空', trigger: 'blur' }],
    lateRegistrationLevel: [{ required: true, message: '截止报名级别不能为空', trigger: 'blur' }],
    maxPlayers: [{ required: true, message: '最大参赛人数不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '赛事状态不能为空', trigger: 'change' }]
  }
});

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

/** 查询【请填写功能名称】列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTournaments(queryParams.value);
  tournamentsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  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();
  dialog.visible = true;
  dialog.title = '创建比赛';
};

/** 修改按钮操作 */
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);

  // 处理奖励表单数据
  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;

      // 1. 创建 FormData 对象
      const formData = new FormData();

      // 2. 添加普通表单字段
      for (const key in data.form) {
        const value = data.form[key];
        if (value !== undefined && value !== null) {
          formData.append(key, String(value));
        }
      }

      // 3. 添加奖励列表（itemsPrizeList）
      const itemsPrizeListJson = JSON.stringify(
        formPrize.rewards.map((reward) => ({
          ranking: reward.ranking,
          itemId: reward.itemId,
          quantity: reward.quantity
        }))
      );
      formData.append('itemsPrizeList', itemsPrizeListJson);

      // 4. 添加图标文件（如果存在）
      if (iconFile.value) {
        formData.append('competitionIcon', iconFile.value);
      }
      debugger;
      // 5. 判断新增或编辑
      let response;
      if (data.form.id) {
        response = await updateTournaments(formData);
      } else {
        response = await addTournaments(formData);
      }

      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    } catch (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 = (file: any) => {
  if (file.raw) {
    iconFile.value = file.raw; // 缓存原始文件对象
  } else {
    iconFile.value = null;
  }
};
/*
const fileList = ref([]);
const handleIconChange = async (file) => {
  const index = fileList.value.findIndex((f) => f.uid === file.uid);
  fileList.value = [];
  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;
      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;
};
</script>
