<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="赛事ID" prop="id">
              <el-input v-model="queryParams.id" placeholder="请输入赛事ID" clearable @keyup.enter="handleQuery" style="width: 100%" />
            </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="时间">
              <el-date-picker
                v-model="data.queryParams.loginTimeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </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="warning" plain icon="Download" @click="handleExport">导出</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">
        <!-- 序号列 -->
        <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="id" v-if="true" />
        <el-table-column label="赛事名称" align="center" prop="name" />
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <span
              :style="{
                color: scope.row.isDelete ? 'red' : ''
              }"
            >
              {{ scope.row.isDelete ? '已删除' : scope.row.statusText || '' }}
            </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" prop="signNum" />
        <el-table-column label="报名总手数" align="center" prop="totalSignup" />
        <el-table-column label="报名条件" align="center" prop="tournamentCondition" />
        <el-table-column label="条件数" align="center" prop="tournamentConditionValue" />
        <el-table-column label="总报名价值" align="center" prop="signValue" />
        <el-table-column label="奖励" align="center">
          <template #default="scope">
            <div v-if="scope.row.itemsPrizeList && scope.row.itemsPrizeList.length > 0">
              <!-- 显示第一名奖励 -->
              <div>
                第{{ scope.row.itemsPrizeList[0].ranking }}名：{{ scope.row.itemsPrizeList[0].quantity }} {{ scope.row.itemsPrizeList[0].itemsName }}
              </div>

              <!-- 如果有更多奖励，用 tooltip 显示 -->
              <el-tooltip v-if="scope.row.itemsPrizeList.length > 1" :content="getRewardTooltipContent(scope.row.itemsPrizeList)" placement="top">
                <span class="more-rewards">更多</span>
              </el-tooltip>
            </div>
            <span v-else>—</span>
          </template>
        </el-table-column>
        <el-table-column label="奖励人数" align="center" prop="rewardClaimsCount" />
      </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="Tournaments" lang="ts">
import { getStatisticsPageList, getTournaments, delTournaments, addTournaments, updateTournaments } from '@/api/system/business/tournaments';
import { TournamentsVO, TournamentsQuery, TournamentsForm } from '@/api/system/business/tournaments/types';

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 dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

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: undefined
};
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: '赛事状态 0 未开始 1 进行中 2 同步发牌 3 普通暂停 4 完成不能为空', trigger: 'change' }]
  }
});

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

/** 查询【请填写功能名称】列表 */
const getList = async () => {
  loading.value = true;
  const res = await getStatisticsPageList(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;
  //queryParams.value.flagType = '';
  const timeRange = data.queryParams.loginTimeRange;
  if (timeRange && timeRange.length === 2) {
    data.queryParams.startTime = timeRange[0];
    data.queryParams.endTime = timeRange[1];
  } else {
    data.queryParams.startTime = null;
    data.queryParams.endTime = null;
  }
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  // 设置默认开始时间为今天
  const today = new Date();
  const yyyy = today.getFullYear();
  const mm = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以+1
  const dd = String(today.getDate()).padStart(2, '0');
  queryParams.value.startTime = `${yyyy}-${mm}-${dd}`;
  handleQuery();
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: TournamentsVO[]) => {
  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/tournaments/exportStatisticsPageList',
    {
      ...queryParams.value
    },
    `赛事统计${parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}.xlsx`
  );
};
// 获取奖励提示内容
const getRewardTooltipContent = (rewards: any[]) => {
  return rewards.map((prize) => `第${prize.ranking}名：${prize.quantity} ${prize.itemsName}`).join('\n');
};

import { useRoute } from 'vue-router';

const route = useRoute();

onMounted(() => {
  // 设置默认开始时间为今天
  const today = new Date();
  const yyyy = today.getFullYear();
  const mm = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以+1
  const dd = String(today.getDate()).padStart(2, '0');
  const flagType = route.query.timeFilter;
  const startTime = route.query.startTime;
  const endTime = route.query.endTime;
  // 根据参数设置查询条件
  if (startTime) {
    queryParams.value.startTime = startTime as string; // 直接赋值字符串
  } else {
    /* queryParams.value.startTime = `${yyyy}-${mm}-${dd}`;*/
  }
  // 处理结束时间（如果需要）
  if (endTime) {
    queryParams.value.endTime = endTime as string;
  }
  if (flagType) {
    queryParams.value.flagType = flagType as string;
  }
  getList();
});

// 监听路由参数变化
watch(
  () => route.query,
  (newQuery, oldQuery) => {
    const flagType = route.query.timeFilter;
    const startTime = route.query.startTime;
    const endTime = route.query.endTime;
    // 根据参数设置查询条件
    if (startTime) {
      queryParams.value.startTime = startTime as string; // 直接赋值字符串
    } else {
    }
    // 处理结束时间（如果需要）
    if (endTime) {
      queryParams.value.endTime = endTime as string;
    }
    if (flagType) {
      queryParams.value.flagType = flagType as string;
    }
    getList();
  },
  { immediate: true } // 立即执行一次，确保初始参数被处理
);
</script>
<style scoped>
.more-rewards {
  cursor: pointer;
  color: #409eff;
  margin-left: 5px;
}
</style>
