<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" label-width="100px">
            <el-form-item label="赛事编号" prop="eventCode">
              <el-input v-model="queryParams.eventCode" placeholder="请输入赛事编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="赛事名称" prop="eventName">
              <el-input v-model="queryParams.eventName" placeholder="请输入赛事名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="赛事类型" prop="eventType">
              <el-select v-model="queryParams.eventType" placeholder="请选择赛事类型" clearable>
                <el-option v-for="dict in game_event_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否默认赛事" prop="isDefault">
              <el-select v-model="queryParams.isDefault" placeholder="请选择是否默认赛事" clearable>
                <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option v-for="dict in game_event_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </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="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:gameEvent:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:gameEvent:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:gameEvent:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:gameEvent:export']">导出</el-button>
          </el-col>
          <!-- 新增的操作按钮，基于默认赛事 -->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleDownloadTemplateDefault" v-hasPermi="['system:gameEvent:download']"
              >下载报名表模板
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="FolderOpened" @click="handleImportRegistrationDefault" v-hasPermi="['system:gameEvent:import']"
              >导入报名表
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="User" @click="handleAddParticipantDefault" v-hasPermi="['system:gameEvent:addParticipant']"
              >参赛者
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Avatar" @click="handleAddRefereeDefault" v-hasPermi="['system:gameEvent:addReferee']"
              >裁判
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="View" @click="handlePreviewDefault" v-hasPermi="['system:gameEvent:view']">预览 </el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="DataAnalysis" @click="handleGameDataDefault" v-hasPermi="['system:gameEvent:gameData']"
              >排行榜
            </el-button>
          </el-col> -->
          <!-- <el-col :span="1.5">
            <el-button type="primary" plain icon="EditPen" @click="handleWriteArticleDefault" v-hasPermi="['system:gameEvent:writeArticle']"
              >编写文章
            </el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Download" @click="handleExportNumberTableDefault" v-hasPermi="['system:gameEvent:numberExport']"
              >导出号码对照表
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Postcard" @click="handleGenerateBib" v-hasPermi="['system:gameEvent:numberBib']"
              >生成参赛号码布
            </el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="info" plain icon="List" @click="handleTaskList" v-hasPermi="['system:gameEvent:numberBib']"
              >任务列表
            </el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="gameEventList" @selection-change="handleSelectionChange">
        <!-- 第一列：多选列 -->
        <el-table-column type="selection" width="55" align="center" />
        <!-- 第二列：操作列 -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:gameEvent:edit']"> 修改 </el-button>
            </el-tooltip>
            <el-tooltip content="生成赛事链接" placement="top">
              <el-button link type="warning" icon="Edit" @click="handleUpdateCode(scope.row)" v-hasPermi="['system:gameEvent:edit']"> 生成赛事码 </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="序号" align="center" type="index" />
        <el-table-column label="赛事id" align="center" prop="eventId" v-if="columns[0].visible" />
        <el-table-column label="赛事编号" align="center" prop="eventCode" v-if="columns[1].visible" />
        <el-table-column label="赛事名称" align="center" prop="eventName" v-if="columns[2].visible" />
        <el-table-column label="赛事类型" align="center" prop="eventType" v-if="columns[3].visible">
          <template #default="scope">
            <dict-tag :options="game_event_type" :value="scope.row.eventType" />
          </template>
        </el-table-column>
        <el-table-column label="举办地点" align="center" prop="location" v-if="columns[4].visible" />
        <el-table-column label="用途" align="center" prop="purpose" v-if="columns[5].visible">
          <template #default="scope">
            <dict-tag :options="game_event_purpose" :value="scope.row.purpose" />
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center" prop="startTime" width="180" v-if="columns[6].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" width="180" v-if="columns[7].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="赛事链接" align="center" prop="eventUrl" width="100" v-if="columns[8].visible">
          <template #default="scope">
            <image-preview :src="scope.row.eventUrl" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="裁判码" align="center" prop="refereeUrlUrl" width="100" v-if="columns[9].visible">
          <template #default="scope">
            <image-preview :src="scope.row.refereeUrlUrl" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="举办单位" align="center" prop="unit" v-if="columns[10].visible" />
        <el-table-column label="是否默认赛事" align="center" prop="isDefault" v-if="columns[11].visible">
          <template #default="scope">
            <el-switch v-model="scope.row.isDefault" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)" v-hasPermi="['system:gameEvent:edit']"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" v-if="columns[12].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime" width="180" v-if="columns[13].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" v-if="columns[14].visible">
          <template #default="scope">
            <dict-tag :options="game_event_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[15].visible" />
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 注册 RefereeForm 组件 -->
    <RefereeForm ref="refereeFormRef" />
    <!-- 注册 BibViewerDialog 组件 -->
    <BibViewerDialog ref="bibViewerDialogRef" />

    <!-- 用户导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <span>仅允许导入.xlsx格式文件。</span>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入结果对话框 -->
    <el-dialog v-model="showImportResult" title="导入结果详情" width="800px" append-to-body>
      <div v-if="importResult">
        <el-alert 
          :title="`共处理 ${importResult.totalCount} 条数据，成功 ${importResult.validCount} 条，失败 ${importResult.errorCount} 条`"
          :type="importResult.success ? 'success' : 'warning'"
          :closable="false"
          class="mb-4"
        />
        
        <div v-if="importResult.validationResult && importResult.validationResult.errors.length > 0">
          <h4>失败原因详情：</h4>
          <el-table :data="importResult.validationResult.errors" border max-height="400">
            <el-table-column prop="rowIndex" label="行号" width="80" align="center" />
            <el-table-column prop="athleteName" label="运动员姓名" width="120" />
            <el-table-column prop="teamName" label="队伍名称" width="150" />
            <el-table-column prop="projectName" label="相关项目" width="150" />
            <el-table-column prop="errorMessage" label="失败原因" />
          </el-table>
        </div>
      </div>
  
  <template #footer>
    <div class="dialog-footer">
      <el-button type="primary" @click="showImportResult = false">确定</el-button>
    </div>
  </template>
</el-dialog>
  </div>
</template>

<script setup name="GameEvent" lang="ts">
import { listGameEvent, changeEventDefault, delGameEvent, addGameEvent, updateGameEvent, updateGameEventWxCode } from '@/api/system/gameEvent';
import { GameEventVO, GameEventQuery, GameEventForm } from '@/api/system/gameEvent/types';
import { getEventMdByEventAndType, editEventMd } from '@/api/system/eventMd';
import { EventMdVO, EventMdForm } from '@/api/system/eventMd/types';
import { useRouter } from 'vue-router';
import { ref } from 'vue';
import RefereeForm from '@/views/system/gameEvent/RefereeForm.vue';
import BibViewerDialog from '@/views/system/gameEvent/components/bibViewerDialog.vue';
import { useTagsViewStore } from '@/store/modules/tagsView';
import { globalHeaders } from '@/utils/request';
import { useGameEventStore } from '@/store/modules/gameEvent';

const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { game_event_type, game_event_status, sys_yes_no, game_event_purpose } = toRefs<any>(
  proxy?.useDict('game_event_type', 'game_event_status', 'sys_yes_no', 'game_event_purpose')
);

// 定义 RefereeForm 组件的类型
interface RefereeFormInstance {
  openDialog: (eventId: string) => void;
}

const refereeFormRef = ref<(InstanceType<typeof RefereeForm> & RefereeFormInstance) | null>(null);
const bibViewerDialogRef = ref<InstanceType<typeof BibViewerDialog> | null>(null);

const gameEventList = ref<GameEventVO[]>([]);
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 columns = ref<FieldOption[]>([
  { key: 0, label: '赛事id', visible: false },
  { key: 1, label: '赛事编号', visible: true },
  { key: 2, label: '赛事名称', visible: true },
  { key: 3, label: '赛事类型', visible: true },
  { key: 4, label: '举办地点', visible: true },
  { key: 5, label: '用途', visible: true },
  { key: 6, label: '开始时间', visible: true },
  { key: 7, label: '结束时间', visible: true },
  { key: 8, label: '赛事链接', visible: true },
  { key: 9, label: '裁判码', visible: true },
  { key: 10, label: '举办单位', visible: true },
  { key: 11, label: '是否默认赛事', visible: true },
  { key: 12, label: '创建时间', visible: true },
  { key: 13, label: '更新时间', visible: true },
  { key: 14, label: '状态', visible: true },
  { key: 15, label: '备注', visible: true }
]);

const queryFormRef = ref<ElFormInstance>();
const gameEventFormRef = ref<ElFormInstance>();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const uploadRef = ref<ElUploadInstance>();

/*** 用户导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/system/enroll/importData'
});

const importResult = ref(null);
const showImportResult = ref(false);

const initFormData: GameEventForm = {
  eventId: undefined,
  eventCode: undefined,
  eventName: undefined,
  eventType: undefined,
  location: undefined,
  purpose: undefined,
  startTime: undefined,
  endTime: undefined,
  eventUrl: undefined,
  refereeUrl: undefined,
  registerUrl: undefined,
  unit: undefined,
  isDefault: undefined,
  status: undefined,
  remark: undefined
};
const data = reactive<PageData<GameEventForm, GameEventQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    eventCode: undefined,
    eventName: undefined,
    eventType: undefined,
    purpose: undefined,
    startTime: undefined,
    isDefault: undefined,
    status: undefined,
    params: {},
    orderByColumn: '',
    isAsc: ''
  },
  rules: {
    eventCode: [{ required: true, message: '赛事编号不能为空', trigger: 'blur' }],
    eventName: [{ required: true, message: '赛事名称不能为空', trigger: 'blur' }],
    eventType: [{ required: true, message: '赛事类型不能为空', trigger: 'change' }]
  }
});

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

// 使用gameEvent store
const gameEventStore = useGameEventStore();

/** 查询赛事基本信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listGameEvent(queryParams.value);
  gameEventList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: GameEventVO[]) => {
  ids.value = selection.map((item) => item.eventId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  router.push('/system/gameEvent/add');
};

/** 修改按钮操作 */
const handleUpdate = async (row?: GameEventVO) => {
  const _eventId = row?.eventId || ids.value[0];
  router.push(`/system/gameEvent/edit/${_eventId}`);
};

/** 生成赛事码按钮操作 */
const handleUpdateCode = async (row?: GameEventVO) => {
  const _eventId = row?.eventId || ids.value[0];
  await updateGameEventWxCode(_eventId);
  await getList();
};

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

/** 删除按钮操作 */
const handleDelete = async (row?: GameEventVO) => {
  const _ids = row?.eventId || ids.value;

  if (!_ids || (Array.isArray(_ids) && _ids.length === 0)) {
    proxy?.$modal.msgError('请选择要删除的赛事');
    return;
  }

  // 如果是单个删除，需要检查时间限制
  if (row) {
    const endTime = new Date(row.endTime);
    const currentTime = new Date();
    const daysDiff = Math.floor((currentTime.getTime() - endTime.getTime()) / (1000 * 60 * 60 * 24));

    if (daysDiff < 100) {
      proxy?.$modal.msgError(`该赛事结束时间不足100天，无法删除。距离可删除时间还有 ${100 - daysDiff} 天。`);
      return;
    }

    await proxy?.$modal.confirm('是否确认删除赛事编号为"' + row.eventCode + '"的数据项？').finally(() => (loading.value = false));
    await delGameEvent(row.eventId);
    proxy?.$modal.msgSuccess('删除成功');
  } else {
    // 批量删除
    const selectedEvents = gameEventList.value.filter((event) => ids.value.includes(event.eventId));
    const invalidEvents = selectedEvents.filter((event) => {
      const endTime = new Date(event.endTime);
      const currentTime = new Date();
      const daysDiff = Math.floor((currentTime.getTime() - endTime.getTime()) / (1000 * 60 * 60 * 24));
      return daysDiff < 100;
    });

    if (invalidEvents.length > 0) {
      const eventNames = invalidEvents.map((event) => event.eventName).join('、');
      proxy?.$modal.msgError(`以下赛事结束时间不足100天，无法删除：${eventNames}`);
      return;
    }

    const eventCodes = selectedEvents.map((event) => event.eventCode).join('、');
    await proxy?.$modal.confirm(`是否确认删除以下赛事：${eventCodes}？`).finally(() => (loading.value = false));
    await delGameEvent(ids.value);
    proxy?.$modal.msgSuccess(`成功删除 ${selectedEvents.length} 个赛事`);
  }

  await getList();
};
/** 判断是否可以删除赛事 */
const canDelete = (row: GameEventVO): boolean => {
  const endTime = new Date(row.endTime);
  const currentTime = new Date();
  const daysDiff = Math.floor((currentTime.getTime() - endTime.getTime()) / (1000 * 60 * 60 * 24));
  return daysDiff >= 100;
};

/** 获取删除按钮的提示信息 */
const getDeleteTooltip = (row: GameEventVO): string => {
  if (canDelete(row)) {
    return '删除';
  } else {
    const endTime = new Date(row.endTime);
    const currentTime = new Date();
    const daysDiff = Math.floor((currentTime.getTime() - endTime.getTime()) / (1000 * 60 * 60 * 24));
    return `赛事结束时间不足100天，无法删除。距离可删除时间还有 ${100 - daysDiff} 天。`;
  }
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/gameEvent/export',
    {
      ...queryParams.value
    },
    `赛事列表.xlsx`
  );
};

/* 下载模板 */
const handleDownloadTemplate = (row: GameEventVO) => {
  proxy?.download(
    'system/enroll/importTemplate',
    {
      eventId: row.eventId
    },
    `${row.eventCode}_报名表模板.xlsx`
  );
};

// 导入报名表逻辑
const handleImportRegistration = (row) => {
  upload.url = import.meta.env.VITE_APP_BASE_API + `/system/enroll/importDataWithValidation/${row.eventId}`;
  upload.title = '报名表导入';
  upload.open = true;
};
/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  
  if (response.code === 200) {
    const result = response.data;
    importResult.value = result;
    showImportResult.value = true;
    
    // 显示导入结果
    if (result.success) {
      proxy?.$modal.msgSuccess(`导入成功！共处理${result.totalCount}条数据，成功${result.validCount}条，失败${result.errorCount}条`);
    } else {
      proxy?.$modal.msgWarning(`导入完成！共处理${result.totalCount}条数据，成功${result.validCount}条，失败${result.errorCount}条`);
    }
  } else {
    proxy?.$modal.msgError('导入失败：' + response.msg);
  }
  
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

// 添加参赛者操作
const handleAddParticipant = (row: GameEventVO) => {
  // 跳转到新增或编辑参赛者信息页面，并传递 eventName 参数
  router.push({
    name: 'GameEventAthlete',
    params: { eventId: row.eventId, eventName: row.eventName }
  });
};

// 添加裁判按钮操作
const handleAddReferee = async (row: GameEventVO) => {
  try {
    if (!row.eventId) {
      proxy?.$modal.msgError('赛事ID不能为空');
      return;
    }
    
    if (!refereeFormRef.value) {
      proxy?.$modal.msgError('裁判表单组件未初始化');
      return;
    }
    
    // 打开裁判表单对话框并传递 eventId
    refereeFormRef.value.openDialog(String(row.eventId));
  } catch (error) {
    console.error('添加裁判失败:', error);
    proxy?.$modal.msgError('添加裁判失败');
  }
};

// 预览按钮点击事件
const handlePreview = (row: GameEventVO) => {
  // 跳转到赛事详情页面
  router.push({
    name: 'GameEventDetail',
    params: { eventId: row.eventId }
  });
};

// 比赛成绩按钮点击事件
const handleGameData = (row: GameEventVO) => {
  router.push({
    name: 'RankingBoardPage',
    params: { eventId: row.eventId }
  });
};

// 文章编写相关数据
const articleDialog = reactive({
  visible: false,
  title: '',
  currentEventId: undefined as string | number | undefined
});

const activeTab = ref('competition-process');

// 标签页与类型值的映射关系
const tabTypeMapping: Record<string, number> = {
  'competition-process': 1, // 竞赛流程
  'competition-items': 2, // 竞赛项目
  'activity-agenda': 3, // 活动议程
  'project-introduction': 4, // 项目介绍
  'competition-flow': 5, // 竞赛流程
  'event-grouping': 6, // 赛事分组
  'athlete-handbook': 7, // 运动员号码簿
  'project-venue': 8, // 项目场地
  'traffic-guide': 9, // 交通指示
  'quick-registration': 10, // 快捷报名
  'registration-consultation': 11 // 报名咨询
};
const articleData = reactive({
  competitionProcess: { id: undefined, title: '', content: '', remark: '' },
  competitionItems: { id: undefined, title: '', content: '', remark: '' },
  activityAgenda: { id: undefined, title: '', content: '', remark: '' },
  projectIntroduction: { id: undefined, title: '', content: '', remark: '' },
  competitionFlow: { id: undefined, title: '', content: '', remark: '' },
  eventGrouping: { id: undefined, title: '', content: '', remark: '' },
  athleteHandbook: { id: undefined, title: '', content: '', remark: '' },
  projectVenue: { id: undefined, title: '', content: '', remark: '' },
  trafficGuide: { id: undefined, title: '', content: '', remark: '' },
  quickRegistration: { id: undefined, title: '', content: '', remark: '' },
  registrationConsultation: { id: undefined, title: '', content: '', remark: '' }
});
// 打开排行榜组件并传递赛事ID
// const openRankingBoard = (eventId: string) => {
//   currentEventId.value = eventId;
//   rankingBoardVisible.value = true;
// };

/** 状态修改  */
const handleStatusChange = async (row: GameEventVO) => {
  const text = row.isDefault === '0' ? '启用' : '停用';
  try {
    await proxy?.$modal.confirm('确认要"' + text + '""' + row.eventName + '"为默认赛事吗?');
    await changeEventDefault(row.eventId, row.isDefault);
    await getList();
    // 更新全局默认赛事信息
    await gameEventStore.fetchDefaultEvent();
    // localStorage.setItem('defaultEventId', row.eventId);
    proxy?.$modal.msgSuccess(text + '成功');
    // 刷新当前标签页
    await useTagsViewStore().delOthersViews(router.currentRoute.value);
  } catch {
    return;
  } finally {
    row.isDefault = row.isDefault === '0' ? '1' : '0';
  }
};

/** 编写文章按钮操作 */
const handleWriteArticle = async (row: GameEventVO) => {
  articleDialog.title = `编写文章 - ${row.eventName}`;
  articleDialog.currentEventId = row.eventId;
  articleDialog.visible = true;
  activeTab.value = 'competition-process';

  // 加载默认标签页（竞赛流程）的数据
  await loadTabData('competition-process');
};

/** 加载指定标签页的数据 */
const loadTabData = async (tabName: string) => {
  const type = tabTypeMapping[tabName];

  if (articleDialog.currentEventId && type) {
    try {
      const response = await getEventMdByEventAndType(articleDialog.currentEventId, type);
      const eventMd = response.data;

      const dataKey = getDataKeyByTabName(tabName);
      if (dataKey && articleData[dataKey]) {
        if (eventMd) {
          articleData[dataKey].id = eventMd.id;
          articleData[dataKey].title = eventMd.title || '';
          articleData[dataKey].content = eventMd.content || '';
          articleData[dataKey].remark = eventMd.remark || '';
        } else {
          articleData[dataKey].id = undefined;
          articleData[dataKey].title = '';
          articleData[dataKey].content = '';
          articleData[dataKey].remark = '';
        }
      }
    } catch (error) {
      const dataKey = getDataKeyByTabName(tabName);
      if (dataKey && articleData[dataKey]) {
        articleData[dataKey].id = undefined;
        articleData[dataKey].title = '';
        articleData[dataKey].content = '';
        articleData[dataKey].remark = '';
      }
    }
  }
};

/** 标签页点击事件 */
const handleTabClick = async (tab: any) => {
  const tabName = tab.props.name;
  await loadTabData(tabName);
};

/** 根据标签页名称获取数据键名 */
const getDataKeyByTabName = (tabName: string): keyof typeof articleData | null => {
  const mapping: Record<string, keyof typeof articleData> = {
    'competition-process': 'competitionProcess',
    'competition-items': 'competitionItems',
    'activity-agenda': 'activityAgenda',
    'project-introduction': 'projectIntroduction',
    'competition-flow': 'competitionFlow',
    'event-grouping': 'eventGrouping',
    'athlete-handbook': 'athleteHandbook',
    'project-venue': 'projectVenue',
    'traffic-guide': 'trafficGuide',
    'quick-registration': 'quickRegistration',
    'registration-consultation': 'registrationConsultation'
  };
  return mapping[tabName] || null;
};

/** 关闭文章编写对话框 */
const handleCloseArticleDialog = () => {
  // 清空所有文章数据
  Object.keys(articleData).forEach((key) => {
    const dataKey = key as keyof typeof articleData;
    articleData[dataKey].id = undefined;
    articleData[dataKey].title = '';
    articleData[dataKey].content = '';
    articleData[dataKey].remark = '';
  });

  // 重置对话框状态
  articleDialog.visible = false;
  articleDialog.currentEventId = undefined;
  activeTab.value = 'competition-process';
};

/** 保存文章 */
const handleSaveArticle = async () => {
  if (!articleDialog.currentEventId) {
    proxy?.$modal.msgError('赛事ID不能为空');
    return;
  }

  const currentTabName = activeTab.value;
  const type = tabTypeMapping[currentTabName];
  const dataKey = getDataKeyByTabName(currentTabName);

  if (!dataKey || !articleData[dataKey]) {
    proxy?.$modal.msgError('获取当前标签页数据失败');
    return;
  }

  const currentData = articleData[dataKey];

  if (!currentData.title?.trim()) {
    proxy?.$modal.msgError('标题不能为空');
    return;
  }

  try {
    const formData: EventMdForm = {
      id: currentData.id,
      eventId: articleDialog.currentEventId,
      title: currentData.title,
      content: currentData.content || '',
      type: type,
      remark: currentData.remark || ''
    };

    await editEventMd(formData);
    proxy?.$modal.msgSuccess('文章保存成功');

    // 重新加载当前标签页数据以获取最新的ID
    await loadTabData(currentTabName);
  } catch (error) {
    console.error('保存文章失败:', error);
    proxy?.$modal.msgError('保存文章失败');
  }
};

// 基于默认赛事的操作函数
/** 下载模板（默认赛事） */
const handleDownloadTemplateDefault = async () => {
  const defaultEvent = gameEventStore.defaultEventInfo;
  if (!defaultEvent) {
    proxy?.$modal.msgError('请先设置默认赛事');
    return;
  }
  handleDownloadTemplate(defaultEvent);
};

/** 导入报名信息（默认赛事） */
const handleImportRegistrationDefault = async () => {
  const defaultEvent = gameEventStore.defaultEventInfo;
  if (!defaultEvent) {
    proxy?.$modal.msgError('请先设置默认赛事');
    return;
  }
  handleImportRegistration(defaultEvent);
};

/** 添加参赛者（默认赛事） */
const handleAddParticipantDefault = async () => {
  const defaultEvent = gameEventStore.defaultEventInfo;
  if (!defaultEvent) {
    proxy?.$modal.msgError('请先设置默认赛事');
    return;
  }
  handleAddParticipant(defaultEvent);
};

/** 添加裁判（默认赛事） */
const handleAddRefereeDefault = async () => {
  try {
    const defaultEvent = gameEventStore.defaultEventInfo;
    
    if (!defaultEvent) {
      proxy?.$modal.msgError('请先设置默认赛事');
      return;
    }
    
    await handleAddReferee(defaultEvent);
  } catch (error) {
    console.error('默认赛事添加裁判失败:', error);
    proxy?.$modal.msgError('添加裁判失败');
  }
};

/** 预览（默认赛事） */
const handlePreviewDefault = async () => {
  const defaultEvent = gameEventStore.defaultEventInfo;
  if (!defaultEvent) {
    proxy?.$modal.msgError('请先设置默认赛事');
    return;
  }
  handlePreview(defaultEvent);
};

/** 比赛数据（默认赛事） */
const handleGameDataDefault = async () => {
  const defaultEvent = gameEventStore.defaultEventInfo;
  if (!defaultEvent) {
    proxy?.$modal.msgError('请先设置默认赛事');
    return;
  }
  handleGameData(defaultEvent);
};

/** 编写文章（默认赛事） */
const handleWriteArticleDefault = async () => {
  const defaultEvent = gameEventStore.defaultEventInfo;
  if (!defaultEvent) {
    proxy?.$modal.msgError('请先设置默认赛事');
    return;
  }
  router.push({
    name: 'ArticleEditor',
    params: { eventId: defaultEvent.eventId }
  });
  // handleWriteArticle(defaultEvent);
};

const handleExportNumberTableDefault = async () => {
  await proxy?.download('system/number/export', {}, `${gameEventStore.defaultEventInfo?.eventCode || ''}_号码对照表.xlsx`);
};

// 生成参赛证相关 - 已移动到 BibViewerDialog 组件中

// 生成参赛证按钮处理
const handleGenerateBib = () => {
  if (bibViewerDialogRef.value) {
    bibViewerDialogRef.value.bibDialog.visible = true;
  }
};

// 任务列表按钮处理
const handleTaskList = () => {
  router.push('/system/gameEvent/taskList');
};

onMounted(() => {
  // 获取默认赛事信息
  gameEventStore.fetchDefaultEvent();
  getList();
});

// 监听路由变化，当从编辑页返回时检查是否需要刷新列表
onActivated(() => {
  // 检查是否有需要刷新的标识
  const needRefresh = sessionStorage.getItem('needRefreshGameEventList');
  if (needRefresh === 'true') {
    // 清除标识
    sessionStorage.removeItem('needRefreshGameEventList');
    // 刷新列表数据
    getList();
  }
});
</script>

<style scoped>
.operation-buttons {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: center;
  min-width: 200px;
}

.button-row {
  display: flex;
  gap: 6px;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}

.operation-buttons .el-button {
  min-width: 28px;
  min-height: 28px;
  padding: 4px 6px;
  border-radius: 4px;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.operation-buttons .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
}

.operation-buttons .el-button[disabled] {
  opacity: 0.5;
  cursor: not-allowed;
}

.operation-buttons .el-button[disabled]:hover {
  transform: none;
  box-shadow: none;
}

/* 为不同类型的按钮设置不同的颜色主题 */
.operation-buttons .el-button--primary {
  color: #409eff;
}

.operation-buttons .el-button--danger {
  color: #f56c6c;
}

.operation-buttons .el-button--warning {
  color: #e6a23c;
}

.operation-buttons .el-button--info {
  color: #909399;
}

.operation-buttons .el-button--success {
  color: #67c23a;
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .operation-buttons {
    min-width: 180px;
  }

  .button-row {
    gap: 4px;
  }

  .operation-buttons .el-button {
    min-width: 24px;
    min-height: 24px;
    padding: 3px 5px;
  }
}

@media (max-width: 1200px) {
  .operation-buttons {
    min-width: 160px;
    gap: 2px;
  }

  .button-row {
    gap: 2px;
  }

  .operation-buttons .el-button {
    min-width: 22px;
    min-height: 22px;
    padding: 2px 4px;
  }
}
</style>
