<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>
    <!-- 桌次信息展示区域 -->
    <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 : 6)"
            :key="index"
            class="table-card"
            :class="{ 'selected': selectedTableId === table.tableId }"
            @click="handleTableClick(table)"
          >
            {{ table.tableId }}
          </div>
        </div>
        <div v-if="tableData.length > 6" class="more-button-container">
          <el-button @click="showMore = !showMore" size="small">
            {{ 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 : 6)"
            :key="index"
            class="table-card2"
            :class="{ 'selected': selectedTableHandNumberId === table.handNumber }"
            @click="handleTableNumberClick(table)"
          >
            {{ table.handNumber }}
          </div>
        </div>
        <div v-if="tableNumberData.length > 6" class="more-button-container">
          <el-button @click="showMoreNumber = !showMoreNumber" size="small">
            {{ 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="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 { 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 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: 10,
    handId: undefined,
    tournamentId: undefined,
    involvedPlayers: undefined,
    handNumber: undefined,
    boardCards: undefined,
    totalPot: undefined,
    handStartTime: undefined,
    handEndTime: undefined,
    handDetails: undefined,
    createdAt: undefined,
    historyId: undefined,
    params: {}
  },
  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;
  /*  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 = '';
  }

  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 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 = Number(playerId);
    const tournamentIdNum = Number(tournamentId);
    if (!isNaN(playerIdNum) && !isNaN(tournamentIdNum)) {
      queryParams.value.tournamentId = tournamentIdNum;
      queryParams.value.playerId = playerIdNum;
      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;
          queryParams.value.historyId = firstHandTable.id;
          queryParams.value.tournamentId = String(tournamentId);
        }
      }
    } else {
      console.error('Invalid playerId or tournamentId');
    }
  } catch (error) {
    console.error('获取桌次数据失败', error);
  }
};

const tournamentInfo = ref<Partial<TournamentsVO>>({
  id: '',
  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;

    if (tournamentId && playerId) {
      const playerIdNum = Number(playerId);
      const tournamentIdNum = Number(tournamentId);

      if (!isNaN(playerIdNum) && !isNaN(tournamentIdNum)) {
        await getTableData(playerIdNum, tournamentIdNum);
      }
    }

    if (tournamentId) {
      const id = Array.isArray(tournamentId) ? tournamentId[0] : tournamentId;
      try {
        const res = await getTournaments(id);
        if (res.code === 200) {
          tournamentInfo.value = res.data;
        }
      } catch (error) {
        console.error('获取赛事信息失败', error);
      }
    }

    await getList();
  },
  { deep: true, immediate: true }
);

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

const handleTableClick = async (table: any) => {
  // ✅ 加上 async
  selectedTableId.value = table.tableId;
  //queryParams.value.historyId = table.id;
  queryParams.value.tableId = table.tableId;
  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;
  } catch (error) {
    console.error('请求失败:', error);
    // 可选：清空数据或提示用户
    tableNumberData.value = [];
  }

  // 如果 getList 也需要异步等待，也应加上 async/await
  await getList();
};

const selectedTableHandNumberId = ref<number | null>(null);
const handleTableNumberClick = async (table: any) => {
  // ✅ 加上 async
  selectedTableId.value = table.tableId;
  selectedTableHandNumberId.value = table.handNumber; // 添加这行代码
  queryParams.value.historyId = table.id;
  const tournamentId = tournamentInfo.value.id;
  queryParams.value.tournamentId = tournamentId;
  try {
    // 如果 getList 也需要异步等待，也应加上 async/await
    await getList();
  } catch (error) {
    console.error('请求失败:', error);
    // 可选：清空数据或提示用户
    tableNumberData.value = [];
  }
};

// 高亮小盲、大盲
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>
