<template>
  <div class="p-2">
    <!-- 赛事信息展示区域 -->
    <div v-if="tournamentInfo" class="mb-[20px] bg-light-white p-[10px] rounded">
      <div>
        <span style="font-size: 1.2rem; font-weight: bold">{{ tournamentInfo.name }}</span>
        <!-- 大字体 -->
        <span style="font-size: 0.9rem; margin-left: 5px">({{ tournamentInfo.tournamentsBiId }})</span>
        <!-- 小字体，带括号 -->
      </div>
      <div>比赛时间：{{ tournamentInfo.startTime }} ~ {{ tournamentInfo.endTime }}</div>
      <div>参加人数：{{ tournamentInfo.signNum }}人</div>
    </div>

    <!-- 玩家名称和玩家ID搜索框 -->
    <div class="mb-[20px]">
      <el-form :inline="true" @submit.prevent>
        <el-form-item label="">
          <el-input v-model="queryParams.playerNameOrId" placeholder="请输入玩家名称或选手ID" clearable @keyup.enter="handlePlayerSearch" />
        </el-form-item>
        <!-- 报名截止等级 -->
        <el-form-item label="等级范围">
          <el-select v-model="queryParams.startLateRegistrationLevel" placeholder="请选择起始等级" style="width: 200px">
            <!-- 手动添加空选项 -->
            <el-option :value="null" label="全部" />
            <el-option v-for="item in itemOptionsStructuresLevelLeft" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
          至
          <el-select v-model="queryParams.endLateRegistrationLevel" placeholder="请选择结束等级" style="width: 200px">
            <!-- 手动添加空选项 -->
            <el-option :value="null" label="全部" />
            <el-option v-for="item in itemOptionsStructuresLevelRight" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handlePlayerSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 桌次信息展示区域 -->
    <div v-if="tableData.length > 0" class="mb-[20px]">
      <div class="section-title">桌次：</div>
      <el-scrollbar>
        <div class="card-container">
<!--          <div
            v-for="(table, index) in tableData.slice(0, showMore ? tableData.length : 20)"
            :key="index"
            class="table-card"
            :class="{ 'selected': selectedTableId === table.tableId }"
            @click="handleTableClick(table)"
          >
            {{ table.tableId }}
          </div>-->
          <!-- 修改后 -->
          <div
            v-for="(table, index) in tableData.slice(0, showMore ? tableData.length : 20)"
            :key="index"
            class="table-card"
            :class="{ 'selected': selectedTableId === table.tableId }"
            @click="handleTableClick(table)"
          >
            {{ index + 1 }}
          </div>
        </div>
        <div v-if="tableData.length > 20" class="more-button-container">
          <el-button
            @click="showMore = !showMore"
            size="small"
            type="primary"
            style="background-color: #409eff; border-color: #409eff; color: white; font-weight: bold; padding: 8px 16px"
          >
            {{ showMore ? '收起' : '更多' }}
          </el-button>
        </div>
      </el-scrollbar>
      <div class="section-title">局数：</div>
      <el-scrollbar>
        <div class="card-container">
          <div
            v-for="(table, index) in tableNumberData.slice(0, showMoreNumber ? tableNumberData.length : 20)"
            :key="index"
            class="table-card2"
            :class="{ 'selected': selectedTableHandNumberId === table.handNumber }"
            @click="handleTableNumberClick(table)"
          >
            {{ index + 1 }}
          </div>
        </div>
        <div v-if="tableNumberData.length > 20" class="more-button-container">
          <el-button
            @click="showMoreNumber = !showMoreNumber"
            size="small"
            style="background-color: #409eff; border-color: #409eff; color: white; font-weight: bold; padding: 8px 16px"
          >
            {{ showMoreNumber ? '收起' : '更多' }}
          </el-button>
        </div>
      </el-scrollbar>
    </div>

    <!--    <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="handId">
              <el-input v-model="queryParams.handId" placeholder="请输入" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="" prop="tournamentId">
              <el-input v-model="queryParams.tournamentId" placeholder="请输入" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="" prop="handNumber">
              <el-input v-model="queryParams.handNumber" placeholder="请输入" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="" prop="boardCards">
              <el-input v-model="queryParams.boardCards" placeholder="请输入" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="" prop="totalPot">
              <el-input v-model="queryParams.totalPot" placeholder="请输入" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="" prop="handStartTime">
              <el-date-picker clearable v-model="queryParams.handStartTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择" />
            </el-form-item>
            <el-form-item label="" prop="handEndTime">
              <el-date-picker clearable v-model="queryParams.handEndTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择" />
            </el-form-item>
            <el-form-item label="" prop="createdAt">
              <el-date-picker clearable v-model="queryParams.createdAt" 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="24" style="font-size: 14px; color: #333; margin-bottom: 6px;">
            <strong>发牌信息：</strong>
            <span v-html="blindsInfoText"></span>
          </el-col>-->
          <el-col :span="24" style="font-size: 14px; color: #333; margin-bottom: 6px">
            <strong>比赛时间：</strong>
            <span v-html="beginTimeOrEndTime"></span>
            <span style="margin-left: 20px">
              <strong>盲注等级：</strong>
              <span v-html="blindLevelIds"></span>
            </span>
            <span style="margin-left: 20px">
              <strong>比赛开始时人数：</strong>
              <span v-html="beginPeopleIds"></span>
            </span>
            <span style="margin-left: 20px">
              <strong>比赛结束时人数：</strong>
              <span v-html="endPeopleIds"></span>
            </span>
          </el-col>
          <el-col :span="24" style="font-size: 14px; color: #333; margin-bottom: 6px">
            <strong>公共牌：</strong>
            <span v-html="publicInfoText"></span>
          </el-col>
          <!--          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:history:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:history:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:history:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:history:export']">导出</el-button>
          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="historyList" @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="left">
          <template #default="scope">
            <span v-html="highlightBlinds(scope.row.operateText)"></span>
          </template>
        </el-table-column>
        <!--        <el-table-column label="公共牌" align="center" prop="publicBrand" />-->
        <!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          &lt;!&ndash;          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:history:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:history:remove']"></el-button>
            </el-tooltip>
          </template>&ndash;&gt;
        </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="historyFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="" prop="handId">
          <el-input v-model="form.handId" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="" prop="tournamentId">
          <el-input v-model="form.tournamentId" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="" prop="handNumber">
          <el-input v-model="form.handNumber" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="" prop="boardCards">
          <el-input v-model="form.boardCards" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="" prop="totalPot">
          <el-input v-model="form.totalPot" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="" prop="handStartTime">
          <el-date-picker clearable v-model="form.handStartTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="" prop="handEndTime">
          <el-date-picker clearable v-model="form.handEndTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="" prop="createdAt">
          <el-date-picker clearable v-model="form.createdAt" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择">
          </el-date-picker>
        </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>
  </div>
</template>

<script setup name="History" lang="ts">
import {
  listHistory,
  getHistory,
  delHistory,
  addHistory,
  updateHistory,
  listHistory2,
  selectAllHandZhuoCi2,
  selectAllHandNumber
} from '@/api/system/business/history';
import { getTournaments } from '@/api/system/business/tournaments';
import { selectBlindLevelsByTournament } from '@/api/system/business/levels';
import { HistoryVO, HistoryQuery, HistoryForm } from '@/api/system/business/history/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const historyList = ref<HistoryVO[]>([]);
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 historyFormRef = ref<ElFormInstance>();
const showMore = ref(false); // 定义 showMore 状态
const showMoreNumber = ref(false); // 定义 showMore 状态
// 响应式变量
const blindsInfoText = ref<string>('');
//公共牌
const publicInfoText = ref<string>('');
//比赛开始时间-结束时间
const beginTimeOrEndTime = ref<string>('');

//比赛开始时间-结束时间
const blindLevelIds = ref<string>('');
//开始时人数
const beginPeopleIds = ref<string>('');
//结束时人数
const endPeopleIds = ref<string>('');

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

const initFormData: HistoryForm = {
  id: undefined,
  handId: undefined,
  tournamentId: undefined,
  involvedPlayers: undefined,
  handNumber: undefined,
  boardCards: undefined,
  totalPot: undefined,
  handStartTime: undefined,
  handEndTime: undefined,
  handDetails: undefined,
  createdAt: undefined
};
const data = reactive<PageData<HistoryForm, HistoryQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    handId: undefined,
    tournamentId: undefined,
    involvedPlayers: undefined,
    handNumber: undefined,
    boardCards: undefined,
    totalPot: undefined,
    handStartTime: undefined,
    handEndTime: undefined,
    handDetails: undefined,
    createdAt: undefined,
    historyId: undefined,
    params: {},
    playerNameOrId: undefined
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    handId: [{ required: true, message: '不能为空', trigger: 'blur' }],
    tournamentId: [{ required: true, message: '不能为空', trigger: 'blur' }],
    involvedPlayers: [{ required: true, message: '不能为空', trigger: 'blur' }],
    handNumber: [{ required: true, message: '不能为空', trigger: 'blur' }],
    totalPot: [{ required: true, message: '不能为空', trigger: 'blur' }],
    handStartTime: [{ required: true, message: '不能为空', trigger: 'blur' }],
    handDetails: [{ required: true, message: '不能为空', trigger: 'blur' }],
    createdAt: [{ required: true, message: '不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
import { useRoute } from 'vue-router';
import { ref } from 'vue';
import { TournamentsVO } from '@/api/system/business/tournaments/types';

const route = useRoute();
/** 查询【请填写功能名称】列表 */
const getList = async () => {
  // 从 URL 参数中获取 tournamentId 和 playerId
  const { tournamentId, playerId } = route.query;
  // 设置到 queryParams 中
  if (tournamentId) {
    queryParams.value.tournamentId = String(tournamentId);
  }
  if (playerId) {
    //queryParams.value.playerId = String(playerId);
  }
  loading.value = true;
  if (queryParams.value.startLateRegistrationLevel != undefined && queryParams.value.startLateRegistrationLevel != null) {
    queryParams.value.blindStructureId = blindStructureId.value;
  } else {
    queryParams.value.blindStructureId = null;
  }

  /*  queryParams.value.tournamentId = 5147;
  queryParams.value.historyId = 46569;*/
  const res = await listHistory2(queryParams.value);

  // ✅ 提取第一条数据的 parseBlindsInfo
  if (res.rows && res.rows.length > 0 && res.rows[0]?.parseBlindsInfo) {
    blindsInfoText.value = highlightBlinds(res.rows[0].parseBlindsInfo);
  } else {
    blindsInfoText.value = '';
  }
  if (res.rows && res.rows.length > 0 && res.rows[0]?.publicBrand) {
    publicInfoText.value = highlightBlinds(res.rows[0].publicBrand);
  } else {
    publicInfoText.value = '';
  }

  if (res.rows && res.rows.length > 0 && res.rows[0]?.handStartTime) {
    beginTimeOrEndTime.value = res.rows[0].handStartTime + ' ~ ' + res.rows[0].handEndTime;
  } else {
    beginTimeOrEndTime.value = '';
  }

  if (res.rows && res.rows.length > 0 && res.rows[0]?.blindLevelIds) {
    blindLevelIds.value = res.rows[0].blindLevelIds;
  } else {
    blindLevelIds.value = '';
  }

  if (res.rows && res.rows.length > 0 && res.rows[0]?.beginPeopleIds) {
    beginPeopleIds.value = res.rows[0].beginPeopleIds;
  } else {
    beginPeopleIds.value = '';
  }

  if (res.rows && res.rows.length > 0 && res.rows[0]?.endPeopleIds) {
    endPeopleIds.value = res.rows[0].endPeopleIds;
  } else {
    endPeopleIds.value = '';
  }

  historyList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

const resetQueryParams = () => {
  const defaults = {
    pageNum: 1,
    pageSize: 10,
    handId: undefined,
    //tournamentId: undefined,
    involvedPlayers: undefined,
    handNumber: undefined,
    boardCards: undefined,
    totalPot: undefined,
    handStartTime: undefined,
    handEndTime: undefined,
    handDetails: undefined,
    createdAt: undefined,
    historyId: undefined,
    params: {},
    playerNameOrId: undefined
  };
  Object.assign(data.queryParams, defaults);
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: HistoryVO[]) => {
  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?: HistoryVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getHistory(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改【请填写功能名称】';
};

/** 提交按钮 */
const submitForm = () => {
  historyFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateHistory(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addHistory(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: HistoryVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除【请填写功能名称】编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delHistory(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/history/export',
    {
      ...queryParams.value
    },
    `history_${new Date().getTime()}.xlsx`
  );
};
const tableData = ref<any[]>([]);
const tableNumberData = ref<any[]>([]);
const getTableData = async (playerId: string | number, tournamentId: string | number) => {
  try {
    // 确保 playerId 和 tournamentId 为 number 类型
    const playerIdNum = String(playerId);
    const tournamentIdNum = String(tournamentId);
    /*    if (!isNaN(playerIdNum) && !isNaN(tournamentIdNum)) {*/
    queryParams.value.tournamentId = tournamentIdNum;
    if (playerIdNum !== null && playerIdNum !== undefined && playerIdNum != '') {
      queryParams.value.playerId = playerIdNum;
      queryParams.value.handId = null;
    } else {
      queryParams.value.playerId = null;
    }
    const res = await selectAllHandZhuoCi2(queryParams.value);
    if (res.code === 200) {
      tableData.value = res.data;
      // ✅ 默认选中第一个桌次
      if (tableData.value.length > 0) {
        const firstTable = tableData.value[0];
        selectedTableId.value = firstTable.tableId;

        //默认加载这桌下面的局数
        queryParams.value.tournamentId = tournamentIdNum;
        queryParams.value.tableId = firstTable.tableId;
        const res = await selectAllHandNumber(queryParams.value);
        tableNumberData.value = res.data;
        const firstHandTable = tableNumberData.value[0];
        selectedTableHandNumberId.value = firstHandTable.handNumber;
        if (playerIdNum !== null && playerIdNum !== undefined && playerIdNum != '') {
          queryParams.value.historyId = firstHandTable.id;
          queryParams.value.handId = null;
        } else {
          //拼接handId
          const tid = tournamentId ?? 'unknown';
          const tableId = firstTable.tableId ?? 'unknown';
          const handNum = firstHandTable.handNumber ?? 'unknown';
          queryParams.value.handId = `${tid}-${tableId}-${handNum}`;
          queryParams.value.playerId = null;
          if (queryParams.value.handId != null) {
            queryParams.value.historyId = '';
          }
        }
        queryParams.value.tournamentId = String(tournamentId);
      }
    } else {
      resetQueryParams();
    }
    /*   } else {
      console.error('Invalid playerId or tournamentId');
    }*/
  } catch (error) {
    console.error('获取桌次数据失败', error);
  }
};

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

/*onMounted(async () => {
  // 将回调函数定义为 async 函数
  // 获取 URL 参数中的 tournamentId
  // 获取 URL 参数中的 tournamentId 和 playerId
  const { tournamentId, playerId } = route.query;

  if (tournamentId && playerId) {
    // 确保 tournamentId 和 playerId 为 number 类型
    const playerIdNum = Number(playerId);
    const tournamentIdNum = Number(tournamentId);

    if (!isNaN(playerIdNum) && !isNaN(tournamentIdNum)) {
      // 调用 getTableData 方法获取桌次数据
      await getTableData(playerIdNum, tournamentIdNum);
    } else {
      console.error('Invalid playerId or tournamentId in URL params');
    }
  }

  // 确保 tournamentId 是字符串类型
  if (tournamentId) {
    let id: string | number = '';

    if (Array.isArray(tournamentId)) {
      // 如果是数组，取第一个元素
      id = tournamentId[0];useRoute
    } else {
      // 否则直接赋值
      id = tournamentId;
    }

    try {
      const res = await getTournaments(id);
      if (res.code === 200) {
        tournamentInfo.value = res.data;
      }
    } catch (error) {
      console.error('获取数据失败', error);
    }
  }
  // 初始化列表数据
  await getList(); // 如果 getList 也是异步函数，这里也使用 await
});*/

watch(
  () => route.query,
  async (newQuery) => {
    const { tournamentId, playerId } = newQuery;

    // 判断 tournamentId 是否存在（字符串非空）
    const isValidTournamentId = tournamentId && (typeof tournamentId === 'string' ? tournamentId.trim() !== '' : true);

    if (isValidTournamentId) {
      // 处理 tournamentId 可能是数组的情况
      const tid = Array.isArray(tournamentId) ? tournamentId[0] : tournamentId;
      const playerIdStr = playerId != null ? (Array.isArray(playerId) ? playerId[0] : playerId) : null;

      try {
        // 1. 获取表格数据
        await getTableData(String(playerIdStr), String(tid));

        // 2. 获取赛事详情
        const res = await getTournaments(tid);
        if (res.code === 200) {
          tournamentInfo.value = res.data;
        }

        // 3. 处理盲注结构
        handleBlindStructureChange(Number(tid));
      } catch (error) {
        console.error('数据加载失败', error);
      }
    }

    // ✅ 条件：只有当有查询参数时才调用 getList
    // 比如：你想在打开“历史记录”页面时才加载列表
    if (isValidTournamentId || playerId) {
      await getList();
    } else {
      // 没有参数，可能是初始进入页面，可选：清空数据 or 不操作
      // tournamentInfo.value = null;
      // tableData.value = [];
    }
  },
  { deep: true, immediate: true }
);
// 添加节流时间戳
const lastClickTime = ref(0);
const CLICK_DELAY = 500; // 500ms 内不能重复点击

const selectedTableId = ref<number | null>(null);

const handleTableClick = async (table: any) => {
  const now = Date.now();
  if (now - lastClickTime.value < CLICK_DELAY) {
    proxy?.$modal.msgError('点击过快');
    return;
  }
  lastClickTime.value = now;
  // ✅ 加上 async
  selectedTableId.value = table.tableId;
  //queryParams.value.historyId = table.id;
  queryParams.value.tableId = table.tableId;
  queryParams.value.pageNum = 1;
  const tournamentId = tournamentInfo.value.id;
  queryParams.value.tournamentId = tournamentId;
  try {
    const res = await selectAllHandNumber(queryParams.value);
    console.log('请求成功', res);
    tableNumberData.value = [];
    tableNumberData.value = res.data;
    //加载列表
    const firstHandTable = tableNumberData.value[0];
    //选中对应的变颜色底部
    selectedTableHandNumberId.value = firstHandTable.handNumber; // 添加这行代码
    queryParams.value.historyId = firstHandTable.id;
    if (firstHandTable.id == undefined) {
      const tid = tournamentId ?? 'unknown';
      const tableId = table.tableId ?? 'unknown';
      const handNum = firstHandTable.handNumber ?? 'unknown';
      queryParams.value.handId = `${tid}-${tableId}-${handNum}`;
    } else {
      queryParams.value.handId = null;
    }
  } catch (error) {
    console.error('请求失败:', error);
    // 可选：清空数据或提示用户
    tableNumberData.value = [];
  }
  // 如果 getList 也需要异步等待，也应加上 async/await
  await getList();
};

const selectedTableHandNumberId = ref<number | null>(null);
const handleTableNumberClick = async (table: any) => {
  const now = Date.now();
  if (now - lastClickTime.value < CLICK_DELAY) {
    console.log('点击过快，请稍后再试');
    proxy?.$modal.msgError('点击过快，请稍后再试');
    return;
  }
  lastClickTime.value = now;
  // ✅ 加上 async
  //selectedTableId.value = table.tableId;
  selectedTableHandNumberId.value = table.handNumber; // 添加这行代码
  queryParams.value.historyId = table.id;
  const tournamentId = tournamentInfo.value.id;
  queryParams.value.tournamentId = tournamentId;
  queryParams.value.pageNum = 1;
  const tid = tournamentId ?? 'unknown';
  const tableId = selectedTableId.value ?? 'unknown';
  const handNum = table.handNumber ?? 'unknown';
  queryParams.value.handId = `${tid}-${tableId}-${handNum}`;
  if (queryParams.value.handId != null) {
    queryParams.value.historyId = null;
  }
  try {
    // 如果 getList 也需要异步等待，也应加上 async/await
    await getList();
  } catch (error) {
    console.error('请求失败:', error);
    // 可选：清空数据或提示用户
    tableNumberData.value = [];
  }
};

const handlePlayerSearch = async () => {
  // 获取当前赛事的 tournamentId
  const tournamentId = tournamentInfo.value.id;
  if (!tournamentId) {
    proxy?.$modal.msgError('请先选择赛事');
    return;
  }

  // 设置 queryParams 的 tournamentId
  queryParams.value.tournamentId = tournamentId;

  // 获取玩家名称或ID
  const playerNameOrId = queryParams.value.playerNameOrId;
  /*  if (!playerNameOrId) {
    proxy?.$modal.msgError('请输入玩家名称或选手ID');
    return;
  }*/

  try {
    // 调用 API 获取桌次数据
    const res = await selectAllHandZhuoCi2(queryParams.value);
    if (res.code === 200) {
      tableData.value = res.data;
      // 如果有桌次数据，进一步获取局数数据
      if (tableData.value.length > 0) {
        const firstTable = tableData.value[0];
        selectedTableId.value = firstTable.tableId;
        // 更新 queryParams 以获取局数数据
        queryParams.value.tableId = firstTable.tableId;
        const res = await selectAllHandNumber(queryParams.value);
        tableNumberData.value = res.data;
        // 默认选中第一个局数
        if (tableNumberData.value.length > 0) {
          const firstHandTable = tableNumberData.value[0];
          selectedTableHandNumberId.value = firstHandTable.handNumber;

          queryParams.value.historyId = firstHandTable.id;

          const tid = tournamentId ?? 'unknown';
          const tableId = firstTable.tableId ?? 'unknown';
          const handNum = firstHandTable.handNumber ?? 'unknown';
          queryParams.value.handId = `${tid}-${tableId}-${handNum}`;
          if (queryParams.value.handId != null) {
            queryParams.value.historyId = null;
          }
        }
        // 刷新历史列表
        await getList();
      } else {
        tableNumberData.value = [];
        // 清空所有显示字段
        beginTimeOrEndTime.value = '';
        blindLevelIds.value = '';
        beginPeopleIds.value = '';
        endPeopleIds.value = '';
        publicInfoText.value = '';
        blindsInfoText.value = '';
        historyList.value = [];
        resetQueryParams();
        // 重置分页信息
        total.value = 0;
        queryParams.value.pageNum = 1;
      }
    } else {
      historyList.value = [];
      // 清空所有显示字段
      beginTimeOrEndTime.value = '';
      blindLevelIds.value = '';
      beginPeopleIds.value = '';
      endPeopleIds.value = '';
      publicInfoText.value = '';
      blindsInfoText.value = '';
      // 重置分页信息
      total.value = 0;
      queryParams.value.pageNum = 1;
      //resetQueryParams();
      proxy?.$modal.msgError('获取桌次数据失败');
    }
  } catch (error) {
    console.error('搜索玩家数据失败', error);
    proxy?.$modal.msgError('搜索玩家数据失败');
  }
};

// 下拉选项数据
const itemOptionsStructuresLevelLeft = ref<{ id: number; label: string }[]>([]);
const itemOptionsStructuresLevelRight = ref<{ id: number; label: string }[]>([]);
const blindStructureId = ref<number | null>(null); // 用于存储选中的结构ID
// 加载报名条件选项
const handleBlindStructureChange = async (value: number) => {
  try {
    const res = await selectBlindLevelsByTournament(value);
    if (res.code === 200) {
      // 使用 unknown 中间类型进行类型转换
      const data = res.data as unknown as {
        id: number;
        levelNumber: number;
        smallBlind: number;
        bigBlind: number;
        ante: number;
        blindStructureId: number;
      }[];
      // ✅ 取第一条数据的 id，赋值给公共变量
      blindStructureId.value = data[0].id;
      const list = data.map((item) => {
        const { levelNumber, smallBlind, bigBlind, ante } = item;
        const blindText = `${smallBlind}/${bigBlind} (${ante})`;
        return {
          id: levelNumber,
          label: `等级${levelNumber} ${blindText}`
        };
      });

      /*  itemOptionsStructuresLevel.value = list;

      for (let i = 0; i < data.length; i++) {
        const item = data[i];
        let smallBlind=item.smallBlind;
        let bigBlind=item.bigBlind;
        let ante=item.ante;
        let pubvar=smallBlind+"/"+bigBlind+" "+"("+ante+")";
        list.push({
          id: item.levelNumber,
          label: item.levelNumber
        })*/
      itemOptionsStructuresLevelLeft.value = list;
      itemOptionsStructuresLevelRight.value = list;
    } else {
      alert('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
};

// 高亮小盲、大盲
function highlightBlinds(text: string): string {
  if (!text) return '';
  return text
    .replace(/小盲/g, '<span style="color: blue; font-weight: bold;">小盲</span>')
    .replace(/大盲/g, '<span style="color: red; font-weight: bold;">大盲</span>');
}
</script>

<style scoped>
.section-title {
  font-size: 14px;
  color: #333;
  margin-bottom: 10px;
  font-weight: bold;
}

.card-container {
  display: flex;
  flex-wrap: nowrap; /* 不换行 */
  gap: 8px;
  margin-bottom: 10px;
  overflow-x: auto; /* 横向滚动 */
  padding: 5px 0;
}

.table-card,
.table-card2 {
  cursor: pointer;
  transition: all 0.3s ease;
  width: 40px;
  height: 40px;
  min-width: 40px; /* 防止压缩 */
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  box-sizing: border-box;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  font-size: 14px;
  flex-shrink: 0; /* 防止压缩 */
}

.table-card:hover,
.table-card2:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-card.selected,
.table-card2.selected {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.more-button-container {
  display: flex;
  justify-content: center;
  margin-top: 5px;
}

/* 滚动条样式优化 */
:deep(.el-scrollbar) {
  margin-bottom: 15px;
}

:deep(.el-scrollbar .el-scrollbar__wrap) {
  overflow-x: hidden; /* 隐藏横向滚动条，因为我们自己实现了 */
}
</style>
