<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-row :gutter="10" class="mb8">
              <el-form-item label="赛事ID" prop="tournamentId">
                <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.name"
                  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-date-picker>
              </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="warning" plain icon="Download" @click="handleExport" v-hasPermi="['physical: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" @selection-change="handleSelectionChange">
        <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-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="晋级" placement="top">
              <el-button link type="primary" icon="Edit" @click="getNextTournament(scope.row)">晋级</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="participantsFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="" prop="tournamentId">
          <el-input v-model="form.tournamentId" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="玩家唯一标识" prop="playerId">
          <el-input v-model="form.playerId" placeholder="请输入玩家唯一标识" />
        </el-form-item>
        <el-form-item label="玩家姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入玩家姓名" />
        </el-form-item>
        <el-form-item label="玩家手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入玩家手机号" />
        </el-form-item>
        <el-form-item label="头像地址" prop="avatar">
          <el-input v-model="form.avatar" placeholder="请输入头像地址" />
        </el-form-item>
        <el-form-item label="当前记分牌数量" prop="currentChips">
          <el-input v-model="form.currentChips" placeholder="请输入当前记分牌数量" />
        </el-form-item>
        <el-form-item label="rebuy次数" prop="rebuy">
          <el-input v-model="form.rebuy" placeholder="请输入rebuy次数" />
        </el-form-item>
        <el-form-item label="淘汰时间，用于重启后排名" prop="eliminatedTime">
          <el-date-picker
            clearable
            v-model="form.eliminatedTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择淘汰时间，用于重启后排名"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="报名时间" prop="registrationTime">
          <el-date-picker clearable v-model="form.registrationTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择报名时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="最终名次" prop="finalRank">
          <el-input v-model="form.finalRank" placeholder="请输入最终名次" />
        </el-form-item>
        <el-form-item label="获得奖励" prop="finalReward">
          <el-input v-model="form.finalReward" 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>
  </div>
</template>

<script setup name="Participants" lang="ts">
import { ref, reactive, onMounted, toRefs, watch } from 'vue';
import { useRoute } from 'vue-router';  // 添加这一行
import { ElFormInstance } from 'element-plus';
import { ComponentInternalInstance, getCurrentInstance } from 'vue';
const route = useRoute();  // 添加这一行
import {
  listParticipants,
  getParticipants,
  delParticipants,
  addParticipants,
  updateParticipants,
  promoteTournament
} from '@/api/system/physical/participants';
import { ParticipantsVO, ParticipantsQuery, ParticipantsForm } from '@/api/system/physical/participants/types';
import { parseTime } from '@/utils/dateUtils';

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 queryFormRef = ref<ElFormInstance>();
const participantsFormRef = ref<ElFormInstance>();

const dialog = reactive({
  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
};

interface PageData<T, Q> {
  form: T;
  queryParams: Q & { pageNum: number; pageSize: number; params?: {} };
  rules: Record<string, unknown[]>;
}

const data = reactive<PageData<ParticipantsForm, ParticipantsQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tournamentId: '',
    playerId: undefined,
    name: '',
    mobile: '',
    avatar: undefined,
    currentChips: undefined,
    rebuy: undefined,
    eliminatedTime: undefined,
    registrationTime: '',
    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 () => {
  console.log('=== getList 开始 ===');
  console.log('当前 loading:', loading.value);
  console.log('查询参数:', queryParams.value);
  
  loading.value = true;
  console.log('设置 loading 为 true:', loading.value);
  
  try {
    console.log('准备调用 API...');
    const res = await listParticipants(queryParams.value);
    console.log('API 返回成功');
    console.log('完整 API 响应:', res);
    console.log('响应码:', res.code);
    console.log('数据:', res.data);
    
    // 检查响应结构
    if (res.code === 200) {
      // 如果 data 是数组，直接使用；如果是对象且有 rows 属性，使用 rows
      if (Array.isArray(res.data)) {
        participantsList.value = res.data;
        total.value = res.total || res.data.length;
        console.log('使用 Array.isArray(res.data)，列表长度:', res.data.length);
      } else if (res.data && res.data.rows) {
        participantsList.value = res.data.rows;
        total.value = res.data.total || 0;
        console.log('使用 res.data.rows，列表长度:', res.data.rows.length);
      } else if (res.rows) {
        // 兼容旧格式
        participantsList.value = res.rows;
        total.value = res.total || 0;
        console.log('使用 res.rows，列表长度:', res.rows.length);
      } else {
        console.warn('未知的数据结构:', res);
        participantsList.value = [];
        total.value = 0;
      }
    } else {
      console.error('响应码不是 200:', res.code, res.msg);
      proxy?.$modal.msgError(res.msg || '获取数据失败');
      participantsList.value = [];
      total.value = 0;
    }
  } catch (error: any) {
    console.error('捕获到异常:', error);
    console.error('错误信息:', error.message);
    console.error('错误堆栈:', error.stack);
    proxy?.$modal.msgError(error.message || '获取数据失败，请检查网络连接或权限');
    participantsList.value = [];
    total.value = 0;
  } finally {
    console.log('进入 finally 块');
    loading.value = false;
    console.log('设置 loading 为 false:', loading.value);
    console.log('=== getList 结束 ===');
  }
};

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

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

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value.tournamentId = '';
  queryParams.value.name = '';
  queryParams.value.mobile = '';
  queryParams.value.registrationTime = '';
  queryParams.value.pageNum = 1;
  getList();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ParticipantsVO[]) => {
  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?: ParticipantsVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getParticipants(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改线下用户报名';
};

//晋级
const getNextTournament = async (row?: ParticipantsVO) => {
  try {
    await proxy?.$modal.confirm('是否确认将该选手晋级？');
    const _row = row || participantsList.value.find((item) => item.id === ids.value[0]);
    if (!_row) {
      proxy?.$modal.msgError('未找到对应的参赛记录');
      return;
    }
    await promoteTournament({
      id: _row.id,
      tournamentId: _row.tournamentId,
      playerId: _row.playerId
    } as ParticipantsForm);
    proxy?.$modal.msgSuccess('晋级成功');
    await getList();
  } catch (error) {
    if (error !== 'cancel') {
      proxy?.$modal.msgError('晋级失败:' + (error as Error).message);
    }
  }
};

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

/** 删除按钮操作 */
const handleDelete = async (row?: ParticipantsVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除线下用户报名编号为"' + _ids + '"的数据项？');
  loading.value = true;
  try {
    await delParticipants(_ids);
    proxy?.$modal.msgSuccess('删除成功');
    await getList();
  } catch (error) {
    console.error('删除失败:', error);
    proxy?.$modal.msgError('删除失败');
  } finally {
    loading.value = false;
  }
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'physical/participants/export',
    {
      ...queryParams.value
    },
    `用户报名记录${parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}.xlsx`
  );
};

// 监听路由变化
watch(
  () => route.query,
  (newQuery) => {
    console.log('路由参数变化:', newQuery);
    if (newQuery && newQuery.tournamentId) {
      // 手动重置所有查询参数（不调用 resetQuery，因为它会自动 getList）
      queryParams.value.tournamentId = '';
      queryParams.value.name = '';
      queryParams.value.mobile = '';
      queryParams.value.registrationTime = '';
      queryParams.value.pageNum = 1;
      // 然后设置 tournamentId
      queryParams.value.tournamentId = newQuery.tournamentId;
      console.log('设置 tournamentId:', queryParams.value.tournamentId);
      getList();
    }
  },
  { immediate: false }  // 改为 false，不在组件挂载时立即执行
);

// 组件挂载时的处理
onMounted(() => {
  console.log('组件已挂载');
  // 检查是否有路由参数
  if (route.query.tournamentId) {
    console.log('检测到路由参数 tournamentId:', route.query.tournamentId);
    queryParams.value.tournamentId = route.query.tournamentId;
  }
  // 调用 getList 加载数据
  getList();
});
</script>
