<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <!--            <el-form-item label="赛事" prop="tournamentId">
              <el-select
                v-model="queryParams.tournamentId"
                placeholder="请选择赛事"
                clearable
                filterable
                style="width: 300px; min-width: 300px"
                @change="handleQuery"
              >
                <el-option v-for="tournament in tournamentOptions" :key="tournament.id" :label="tournament.name" :value="tournament.id" />
              </el-select>
            </el-form-item>-->

            <el-row :gutter="10" class="mb8">
              <el-form-item label="赛事ID" prop="userName">
                <el-input
                  v-model="queryParams.tournamentId"
                  style="width: 300px; min-width: 300px"
                  placeholder="请输入赛事ID"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item label="报名用户" prop="userName">
                <el-input
                  v-model="queryParams.userName"
                  style="width: 300px; min-width: 300px"
                  placeholder="请输入报名用户"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-row>
            <el-row :gutter="10" class="mb8">
              <el-form-item label="手机号" prop="mobile">
                <el-input
                  v-model="queryParams.mobile"
                  style="width: 300px; min-width: 300px"
                  placeholder="请输入手机号"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item label="报名时间" prop="registrationTime">
                <el-date-picker
                  clearable
                  style="width: 300px"
                  v-model="queryParams.registrationTime"
                  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-row>
          </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:participants:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['business:participants:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['business:participants:remove']">删除</el-button>
          </el-col>-->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['business:participants: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="participantsList">
        <el-table-column label="编号" width="60" align="center">
          <template #default="{ $index }">
            {{ $index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize }}
          </template>
        </el-table-column>
        <el-table-column label="赛事ID" align="center" prop="tournamentId" v-if="true" />
        <el-table-column label="赛事名称" align="center" prop="tournamentsName" />
        <el-table-column label="赛事状态" align="center" prop="statusText" />
        <el-table-column label="报名用户" align="center" prop="userName" />
        <el-table-column label="手机号" align="center" prop="phone" />
        <el-table-column label="报名条件" align="center" prop="tournamentCondition" />
        <el-table-column label="报名时间" align="center" prop="registrationTime" />
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="Participants" lang="ts">
import { listParticipants } from '@/api/system/business/participants';
import { ParticipantsVO, ParticipantsQuery, ParticipantsForm } from '@/api/system/business/participants/types';
// 引入赛事相关的 API
import { listTournaments } from '@/api/system/business/tournaments';
import { TournamentsVO } from '@/api/system/business/tournaments/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const participantsList = ref<ParticipantsVO[]>([]);
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 tournamentOptions = ref<TournamentsVO[]>([]);
const queryFormRef = ref<ElFormInstance>();
const participantsFormRef = ref<ElFormInstance>();

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

const initFormData: ParticipantsForm = {
  id: undefined,
  tournamentId: undefined,
  playerId: undefined,
  name: undefined,
  mobile: undefined,
  avatar: undefined,
  currentChips: undefined,
  rebuy: undefined,
  eliminatedTime: undefined,
  registrationTime: undefined,
  status: undefined,
  finalRank: undefined,
  finalReward: undefined
};
const data = reactive<PageData<ParticipantsForm, ParticipantsQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tournamentId: undefined,
    playerId: undefined,
    name: undefined,
    mobile: undefined,
    avatar: undefined,
    currentChips: undefined,
    rebuy: undefined,
    eliminatedTime: undefined,
    registrationTime: undefined,
    status: undefined,
    finalRank: undefined,
    finalReward: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    tournamentId: [{ required: true, message: '不能为空', trigger: 'blur' }],
    playerId: [{ required: true, message: '玩家唯一标识不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '玩家姓名不能为空', trigger: 'blur' }],
    currentChips: [{ required: true, message: '当前记分牌数量不能为空', trigger: 'blur' }]
  }
});

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

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

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

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

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  // 设置默认报名时间为当天
  const today = new Date();
  const formattedDate = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
  queryParams.value.registrationTime = formattedDate;
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ParticipantsVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
import { parseTime } from '@/utils/dateUtils';
/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'business/participants/export',
    {
      ...queryParams.value
    },
    `用户报名记录${parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}.xlsx`
  );
};
/** 查询赛事列表 */
const getTournamentList = async () => {
  try {
    const res = await listTournaments({
      pageNum: 1,
      pageSize: 1000 // 获取足够多的赛事数据
    });
    tournamentOptions.value = res.rows;
  } catch (error) {
    console.error('获取赛事列表失败:', error);
  }
};

onMounted(() => {
  // 设置默认报名时间为当天
  const today = new Date();
  const formattedDate = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
  queryParams.value.registrationTime = formattedDate;
  // getTournamentList(); // 获取赛事列表
  getList();
});
</script>
