<template>
  <div class="game-event-edit">
    <el-card shadow="never">
      <template #header>
        <div class="page-header">
          <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
          <span class="page-title">{{ isEdit ? '编辑赛事' : '新增赛事' }}</span>
        </div>
      </template>

      <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
        <!-- 基本信息标签页 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-form ref="basicFormRef" :model="basicForm" :rules="basicRules" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="赛事编号" prop="eventCode">
                  <el-input v-model="basicForm.eventCode" placeholder="请输入赛事编号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="赛事名称" prop="eventName">
                  <el-input v-model="basicForm.eventName" placeholder="请输入赛事名称" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="赛事类型" prop="eventType">
                  <el-select v-model="basicForm.eventType" placeholder="请选择赛事类型" style="width: 100%">
                    <el-option v-for="dict in game_event_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用途" prop="purpose">
                  <el-select v-model="basicForm.purpose" placeholder="请选择用途" style="width: 100%">
                    <el-option v-for="dict in game_event_purpose" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="开始时间" prop="startTime">
                  <el-date-picker
                    v-model="basicForm.startTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="请选择开始时间"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结束时间" prop="endTime">
                  <el-date-picker
                    v-model="basicForm.endTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="请选择结束时间"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="举办地点" prop="location">
                  <el-input v-model="basicForm.location" placeholder="请输入举办地点" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="举办单位" prop="unit">
                  <el-input v-model="basicForm.unit" placeholder="请输入举办单位" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="是否默认赛事" prop="isDefault">
                  <el-radio-group v-model="basicForm.isDefault" >
                    <el-radio
                      v-for="dict in sys_yes_no"
                      :key="dict.value"
                      :value="dict.value"
                    >{{ dict.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态" prop="status">
                  <el-radio-group v-model="basicForm.status">
                    <el-radio v-for="dict in game_event_status" :key="dict.value" :value="dict.value">{{ dict.label }} </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="赛事链接" prop="eventUrl">
                  <image-upload-cropper v-model="basicForm.eventUrl" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="裁判码" prop="refereeUrl">
                  <image-upload-cropper v-model="basicForm.refereeUrl" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12" v-for="item in imageConfigItems" :key="item.configKey">
                <el-form-item :label="item.configDesc">
                  <image-upload-cropper v-model="item.configValue" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="备注" prop="remark">
              <el-input v-model="basicForm.remark" type="textarea" placeholder="请输入备注" :rows="3" />
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 赛事菜单标签页 -->
        <el-tab-pane label="赛事菜单" name="menu">
          <div class="menu-config">
            <div class="menu-header">
              <h3>赛事菜单</h3>
              <el-button type="primary" @click="addMenuItem" icon="Plus">添加菜单项</el-button>
            </div>

            <el-table :data="menuItems" border style="width: 100%">
              <el-table-column label="菜单名称" prop="menuName">
                <template #default="scope">
                  <el-input v-model="scope.row.menuName" placeholder="请输入菜单名称" />
                </template>
              </el-table-column>
              <el-table-column label="活动类型" prop="activityStatus">
                <template #default="scope">
                  <el-radio-group v-model="scope.row.activityStatus">
                    <el-radio :value="0">赛前</el-radio>
                    <el-radio :value="1">赛中</el-radio>
                    <el-radio :value="2">赛后</el-radio>
                  </el-radio-group>
                </template>
              </el-table-column>
              <el-table-column label="图标" prop="icon">
                <template #default="scope">
                  <el-input v-model="scope.row.icon" placeholder="请输入图标" />
                </template>
              </el-table-column>
              <el-table-column label="颜色" prop="color">
                <template #default="scope">
                  <el-input v-model="scope.row.color" placeholder="请输入颜色" />
                </template>
              </el-table-column>
              <el-table-column label="是否站外" prop="isFrame">
                <template #default="scope">
                  <el-radio-group v-model="scope.row.isFrame">
                    <el-radio :value="1">站内</el-radio>
                    <el-radio :value="0">站外</el-radio>
                  </el-radio-group>
                </template>
              </el-table-column>
              <el-table-column label="链接" prop="siteLink">
                <template #default="scope">
                  <el-input v-model="scope.row.siteLink" placeholder="请输入链接" />
                </template>
              </el-table-column>
              <el-table-column label="排序" prop="orderNum">
                <template #default="scope">
                  <el-input-number v-model="scope.row.orderNum" :min="1" :max="999" />
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button type="danger" size="small" @click="removeMenuItem(scope.$index)" icon="Delete">删除 </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 赛事项目标签页 -->
        <el-tab-pane label="赛事项目" name="projects">
          <div class="project-config">
            <div class="project-header">
              <h3>赛事项目配置</h3>
              <el-button type="primary" @click="addProjectItem" icon="Plus">添加项目</el-button>
            </div>

            <el-table :data="projectItems" border style="width: 100%">
              <el-table-column label="項目类型" prop="projectType">
                <template #default="scope">
                  <el-select v-model="scope.row.projectType" placeholder="请选择項目类型" style="width: 100%">
                    <el-option v-for="dict in game_project_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="项目名称" prop="projectName">
                <template #default="scope">
                  <el-input v-model="scope.row.projectName" placeholder="请输入项目名称" />
                </template>
              </el-table-column>
              <el-table-column label="项目组别" prop="groupType">
                <template #default="scope">
                  <el-select v-model="scope.row.groupType" placeholder="请选择项目组别" style="width: 100%">
                    <el-option v-for="group in groupItems" :key="group.groupId" :label="group.groupName" :value="group.groupName" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="排序" prop="orderType">
                <template #default="scope">
                  <el-radio-group v-model="scope.row.orderType">
                    <el-radio value="0">降序</el-radio>
                    <el-radio value="1">升序</el-radio>
                  </el-radio-group>
                </template>
              </el-table-column>
              <el-table-column label="比赛地点" prop="location">
                <template #default="scope">
                  <el-input v-model="scope.row.location" placeholder="请输入比赛地点" />
                </template>
              </el-table-column>
              <el-table-column label="录取名次" prop="roundType">
                <template #default="scope">
                  <el-input v-model="scope.row.roundType" placeholder="请输入录取名次" />
                </template>
              </el-table-column>
              <el-table-column label="分数" prop="scoreValue">
                <template #default="scope">
                  <el-input v-model="scope.row.scoreValue" placeholder="请输入分数" />
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button type="danger" size="small" @click="removeProjectItem(scope.$index)" icon="Delete">移除 </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 配置信息标签页 -->
        <el-tab-pane label="配置信息" name="config">
          <div class="config-info">
            <div class="config-header">
              <h3>赛事配置信息</h3>
              <el-button type="primary" @click="addConfigItem" icon="Plus">添加配置</el-button>
            </div>

            <el-table :data="configItems" border style="width: 100%">
              <el-table-column label="配置类型" prop="configType" width="150">
                <template #default="scope">
                  <el-select v-model="scope.row.configType" placeholder="请选择配置类型" style="width: 100%">
                    <el-option
                      v-for="type in configTypes"
                      :key="type.typeCode"
                      :label="type.typeName"
                      :value="type.typeCode"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="配置键" prop="configKey" width="200">
                <template #default="scope">
                  <el-input v-model="scope.row.configKey" placeholder="请输入配置键" />
                </template>
              </el-table-column>
              <el-table-column label="配置值" prop="configValue">
                <template #default="scope">
                  <image-or-url-input v-model="scope.row.configValue" />
                </template>
              </el-table-column>
              <el-table-column label="配置描述" prop="configDesc">
                <template #default="scope">
                  <el-input v-model="scope.row.configDesc" placeholder="请输入配置描述" />
                </template>
              </el-table-column>
              <!-- <el-table-column label="是否启用" prop="isEnabled">
                <template #default="scope">
                  <el-switch v-model="scope.row.isEnabled" />
                </template>
              </el-table-column> -->
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button type="danger" size="small" @click="removeConfigItem(scope.$index)" icon="Delete">删除 </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 参赛队伍标签页 -->
        <el-tab-pane label="参赛队伍" name="teams">
          <div class="team-config">
            <div class="team-header">
              <h3>参赛队伍</h3>
              <el-button type="primary" @click="addTeamItem" icon="Plus">新增队伍</el-button>
            </div>

            <el-table :data="teamItems" border style="width: 100%">
              <el-table-column label="单位名称" prop="teamName">
                <template #default="scope">
                  <el-input v-model="scope.row.teamName" placeholder="请输入单位名称" />
                </template>
              </el-table-column>
              <el-table-column label="编号" prop="teamCode">
                <template #default="scope">
                  <el-input v-model="scope.row.teamCode" placeholder="请输入编号" />
                </template>
              </el-table-column>
              <el-table-column label="团队描述" prop="teamDescribe">
                <template #default="scope">
                  <el-input v-model="scope.row.teamDescribe" placeholder="请描述一下你的团队吧~" />
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button type="danger" size="small" @click="removeTeamItem(scope.$index)" icon="Delete">删除 </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 赛事分组标签页 -->
        <el-tab-pane label="赛事分组" name="groups">
          <div class="group-config">
            <div class="group-header">
              <h3>赛事分组</h3>
              <el-button type="primary" @click="addGroupItem" icon="Plus">添加分组</el-button>
            </div>

            <el-table :data="groupItems" border style="width: 100%">
              <el-table-column label="分组名称" prop="groupName">
                <template #default="scope">
                  <el-input v-model="scope.row.groupName" placeholder="请输入分组名称" />
                </template>
              </el-table-column>
              <el-table-column label="成员性别" prop="memberGender">
                <template #default="scope">
                  <el-radio-group v-model="scope.row.memberGender">
                    <el-radio value="0">不分男女</el-radio>
                    <el-radio value="1">男</el-radio>
                    <el-radio value="2">女</el-radio>
                  </el-radio-group>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button type="danger" size="small" @click="removeGroupItem(scope.$index)" icon="Delete">删除 </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- 底部操作按钮 -->
      <div class="form-actions">
        <el-button @click="goBack">取消</el-button>
        <el-button type="primary" @click="saveEvent" :loading="saveLoading">保存</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup name="GameEventEdit" lang="ts">
import { getGameEvent, addGameEvent, updateGameEvent,changeEventDefault } from '@/api/system/gameEvent';
import { GameEventVO, GameEventForm } from '@/api/system/gameEvent/types';
import { listGameEventConfig, addGameEventConfig, updateGameEventConfig, delGameEventConfig } from '@/api/system/gameEventConfig';
import { GameEventConfigVO, GameEventConfigForm } from '@/api/system/gameEventConfig/types';
import { listGameEventConfigType } from '@/api/system/gameEventConfigType'; // 添加导入
import { GameEventConfigTypeVO } from '@/api/system/gameEventConfigType/types'; // 添加导入
import { useRoute, useRouter } from 'vue-router';
import { listGameEventMenu, addGameEventMenu, updateGameEventMenu, delGameEventMenu } from '@/api/system/gameEventMenu';
import { GameEventMenuVO, GameEventMenuForm } from '@/api/system/gameEventMenu/types';
import { listGameTeam, addGameTeam, updateGameTeam, delGameTeam } from '@/api/system/gameTeam';
import { GameTeamVO, GameTeamForm } from '@/api/system/gameTeam/types';
import { listGameEventGroup, addGameEventGroup, updateGameEventGroup, delGameEventGroup } from '@/api/system/gameEventGroup';
import { GameEventGroupForm, GameEventGroupVO } from '@/api/system/gameEventGroup/types';
import { addGameEventProject, listGameEventProject, updateGameEventProject, delGameEventProject } from '@/api/system/gameEventProject';
import { GameEventProjectForm, GameEventProjectVO } from '@/api/system/gameEventProject/types';

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

// 页面状态
const isEdit = ref(false);
const activeTab = ref('basic');
const saveLoading = ref(false);

// 判断是否为默认赛事操作
const isDefaultEventOperation = () => {
  return basicForm.value.isDefault === '0';
};

// 获取有效的赛事ID（默认赛事返回空字符串，否则返回实际ID）
const getEffectiveEventId = (eventId?: string | number): string => {
  if (isDefaultEventOperation()) {
    return '';
  }
  return String(eventId || (route.params.id as string) || '');
};

// 表单引用
const basicFormRef = ref<ElFormInstance>();

// 基本信息表单
const basicForm = ref<GameEventForm>({
  eventCode: '',
  eventName: '',
  eventType: '',
  location: '',
  purpose: '',
  startTime: '',
  endTime: '',
  eventUrl: '',
  refereeUrl: '',
  registerUrl: '',
  unit: '',
  isDefault: '0',
  status: '0',
  remark: ''
});

// 表单验证规则
const basicRules = {
  eventCode: [{ required: true, message: '请输入赛事编号', trigger: 'blur' }],
  eventName: [{ required: true, message: '请输入赛事名称', trigger: 'blur' }],
  eventType: [{ required: true, message: '请选择赛事类型', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
};

// 初始化页面
onMounted(async () => {
  const eventId = route.params.id as string;
  if (eventId) {
    isEdit.value = true;
    await loadEventData(eventId);
  } else {
    // 新增模式，加载图片配置模板
    // await loadImageConfigTemplates();
  }
  // 加载配置类型选项
  await loadConfigTypes();
  // console.log('Initial image configs:', imageConfigItems.value); // 添加调试信息
});

// 加载赛事数据
const loadEventData = async (eventId: string | number) => {
  try {
    const res = await getGameEvent(eventId);
    const data = res.data;

    // 填充基本信息
    Object.assign(basicForm.value, data);

    // 获取有效的赛事ID
    const effectiveEventId = getEffectiveEventId(eventId);

    // 加载图片配置数据
    try {
      await loadImageConfigData(effectiveEventId);
    } catch (error) {
      console.warn('加载图片配置数据失败，继续加载其他数据:', error);
      // 不中断其他数据的加载
    }

    await loadMenuData(effectiveEventId); // 加载菜单数据
    await loadGroupData(effectiveEventId); // 加载分组数据
    await loadProjectData(effectiveEventId); // 加载项目数据
    await loadTeamData(effectiveEventId); // 加载队伍数据
    await loadConfigData(effectiveEventId); // 加载配置数据
  } catch (error) {
    proxy?.$modal.msgError('加载赛事数据失败');
  }
};

/** 状态修改  */
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 loadEventData(row.eventId);
    proxy?.$modal.msgSuccess(text + '成功');
  } catch {
    return;
  } finally {
    row.isDefault = row.isDefault === '0' ? '1' : '0';
  }
};

// 赛事分组数据
const groupItems = ref<GameEventGroupForm[]>([]);
// 加载项目分组数据
const loadGroupData = async (eventId: string | number) => {
  try {
    const res = await listGameEventGroup({
      eventId: eventId === '' ? '' : eventId,
      pageNum: 1,
      pageSize: 1000,
      orderByColumn: '',
      isAsc: ''
    });
    groupItems.value = Array.isArray(res.rows) ? res.rows : [];
  } catch (error) {
    proxy?.$modal.msgError('加载项目分组数据失败');
  }
};
// 添加赛事分组项
const addGroupItem = () => {
  groupItems.value.push({
    groupId: '',
    eventId: getEffectiveEventId(),
    groupName: '',
    memberGender: ''
  });
};
// 删除赛事分组项
const removeGroupItem = (index: number) => {
  const groupItem = groupItems.value[index];
  if (groupItem.groupId) {
    delGameEventGroup(groupItem.groupId).then(() => {
      groupItems.value.splice(index, 1);
    });
  } else {
    groupItems.value.splice(index, 1);
  }
};
// 保存赛事分组数据
const saveGroupData = async (eventId: string | number) => {
  try {
    for (const item of groupItems.value) {
      // 确保eventId被正确设置
      const groupData = { ...item, eventId };

      if (item.groupId) {
        // 更新现有分组
        await updateGameEventGroup(groupData);
      } else if (item.groupName) {
        // 只有有名称的新分组才保存
        await addGameEventGroup(groupData);
      }
    }
  } catch (error) {
    console.error('保存赛事分组数据失败:', error);
    throw new Error('保存赛事分组失败');
  }
};

// 菜单列表数据
const menuItems = ref<GameEventMenuForm[]>([]);
// 加载菜单数据
const loadMenuData = async (eventId: string | number) => {
  try {
    const res = await listGameEventMenu({
      eventId: eventId === '' ? '' : eventId,
      pageNum: 1,
      pageSize: 10,
      orderByColumn: undefined,
      isAsc: undefined,
    });
    menuItems.value = Array.isArray(res.rows) ? res.rows : [];
  } catch (error) {
    proxy?.$modal.msgError('加载菜单数据失败');
  }
};
// 添加菜单项
const addMenuItem = () => {
  menuItems.value.push({
    menuId: '',
    parentId: 0,
    menuName: '',
    activityStatus: 0,
    icon: '',
    color: '',
    isFrame: 1,
    siteLink: '',
    orderNum: menuItems.value.length + 1,
    eventId: getEffectiveEventId() // 使用有效的赛事ID
  });
};
// 删除菜单项
const removeMenuItem = (index: number) => {
  const menuItem = menuItems.value[index];
  if (menuItem.menuId) {
    delGameEventMenu(menuItem.menuId).then(() => {
      menuItems.value.splice(index, 1);
    });
  } else {
    menuItems.value.splice(index, 1);
  }
};
// 保存菜单数据
const saveMenuData = async (eventId: string | number) => {
  try {
    for (const item of menuItems.value) {
      // 确保eventId被正确设置
      const menuData = { ...item, eventId };

      if (item.menuId) {
        // 更新现有菜单
        await updateGameEventMenu(menuData);
      } else if (item.menuName) {
        // 只有有名称的新菜单才保存
        await addGameEventMenu(menuData);
      }
    }
  } catch (error) {
    console.error('保存菜单数据失败:', error);
    throw new Error('保存菜单失败');
  }
};

// 图片配置数据
const imageConfigItems = ref<GameEventConfigForm[]>([]);
// 加载图片配置数据（用于编辑模式）
const loadImageConfigData = async (eventId: string | number) => {
  try {
    // 先查询所有image类型的配置模板（不限制eventId，获取所有可用的图片配置项）
    const templateRes = await listGameEventConfig({
      configType: 'IMAGE',
      pageNum: 1,
      pageSize: 100,
      orderByColumn: '',
      isAsc: ''
    });
    
    // 获取所有图片配置模板
    const allImageConfigs = Array.isArray(templateRes.rows) ? templateRes.rows : [];
    
    // 查询当前赛事的图片配置数据（如果是默认赛事，eventId为空字符串）
    const eventRes = await listGameEventConfig({
      eventId: eventId === '' ? '' : eventId,
      configType: 'IMAGE',
      pageNum: 1,
      pageSize: 100,
      orderByColumn: '',
      isAsc: ''
    });

    const eventImageConfigs = Array.isArray(eventRes.rows) ? eventRes.rows : [];
    
    // 合并配置：以模板为基础，用当前赛事的数据覆盖
    imageConfigItems.value = allImageConfigs.map((template) => {
      const existingConfig = eventImageConfigs.find((item) => item.configKey === template.configKey);
      return {
        ...template,
        eventId: eventId,
        configValue: existingConfig?.configValue || '',
        isEnabled: existingConfig?.isEnabled || template.isEnabled || '0',
        status: existingConfig?.status || template.status || '0',
        configId: existingConfig?.configId
      };
    });
    
  } catch (error) {
    console.error('加载图片配置数据失败:', error);
    proxy?.$modal.msgError('加载图片配置数据失败: ' + (error as Error).message);
    imageConfigItems.value = [];
  }
};
// 刷新图片配置
const refreshImageConfigs = async () => {
  const eventId = route.params.id as string;
  if (eventId && eventId !== 'add') {
    await loadImageConfigData(getEffectiveEventId(eventId));
  } else {
    // 新增模式，只加载配置模板
    // await loadImageConfigTemplates();
  }
};
// 加载图片配置模板（用于新增模式）
// const loadImageConfigTemplates = async () => {
//   try {
//     const res = await listGameEventConfig({
//       eventId: '',
//       configType: 'IMAGE',
//       pageNum: 1,
//       pageSize: 100
//     });

//     // console.log('Template response (new mode):', res);

//     const imageData = Array.isArray(res.rows) ? res.rows : []; // 修改此处，确保正确访问数组数据
//     // console.log('Image data (new mode):', imageData);

//     imageConfigItems.value = imageData.map(item => ({
//       ...item,
//       configValue: item.configValue || '', // 确保 configValue 初始化正确
//       isEnabled: item.isEnabled || '0', // 确保 isEnabled 初始化正确
//       status: item.status || '0' // 确保 status 初始化正确
//     }));

//     // console.log('Image config items (new mode):', imageConfigItems.value);
//   } catch (error) {
//     console.error('加载图片配置模板失败:', error);
//     proxy?.$modal.msgError('加载图片配置模板失败: ' + (error as Error).message);
//     imageConfigItems.value = [];
//   }
// };
// 保存图片配置数据
const saveImageConfigData = async (eventId?: string | number) => {
  try {
    // 如果是默认赛事操作，使用空字符串作为eventId
    const targetEventId = eventId === '' ? '' : (eventId || (route.params.id as string));
    const updates: GameEventConfigForm[] = [];
    const adds: GameEventConfigForm[] = [];

    // 收集需要更新和添加的数据
    for (const item of imageConfigItems.value) {
      if (item.configKey) {
        const configData: GameEventConfigForm = {
          ...item,
          eventId: targetEventId,
          configType: 'IMAGE'
        };

        if (item.configId && item.configValue) {
          updates.push(configData);
        } else if (!item.configId && item.configValue) {
          adds.push(configData);
        }
      }
    }

    // 批量更新
    if (updates.length > 0) {
      await Promise.all(updates.map(updateGameEventConfig));
    }

    // 批量添加
    if (adds.length > 0) {
      await Promise.all(adds.map(addGameEventConfig));
    }
  } catch (error) {
    console.error('保存图片配置数据失败:', error);
    throw new Error('保存图片配置失败');
  }
};

// 处理标签页切换
const handleTabClick = () => {
  // 可以在这里添加标签页切换的逻辑
};

// 项目数据
const projectItems = ref<GameEventProjectForm[]>([]);
// 加载项目数据
const loadProjectData = async (eventId: string | number) => {
  try {
    const res = await listGameEventProject({
      eventId: eventId === '' ? '' : eventId,
      pageNum: 1,
      pageSize: 1000,
      orderByColumn: '',
      isAsc: ''
    });
    projectItems.value = Array.isArray(res.rows) ? res.rows : [];
  } catch (error) {
    proxy?.$modal.msgError('加载项目数据失败');
  }
};
// 添加项目项
const addProjectItem = () => {
  projectItems.value.push({
    eventId: getEffectiveEventId(),
    projectId: '',
    projectName: '',
    projectType: '',
    remark: '',
    location: '',
    scoreValue: '',
    groupType: ''
  });
};
// 删除项目项
const removeProjectItem = (index: number) => {
  const projectItem = projectItems.value[index];
  if (projectItem.projectId) {
    delGameEventProject(projectItem.projectId).then(() => {
      projectItems.value.splice(index, 1);
    });
  } else {
    projectItems.value.splice(index, 1);
  }
};
//保存项目数据
const saveProjectData = async (eventId: string | number) => {
  try {
    for (const item of projectItems.value) {
      // 确保eventId被正确设置
      const projectData = { ...item, eventId };

      if (item.projectId) {
        // 更新现有队伍
        await updateGameEventProject(projectData);
      } else if (item.projectName) {
        // 只有有名称的新队伍才保存
        await addGameEventProject(projectData);
      }
    }
  } catch (error) {
    console.error('保存赛事项目数据失败:', error);
    throw new Error('保存赛事项目失败');
  }
};

// 配置信息数据
const configItems = ref<GameEventConfigForm[]>([]);
// 配置类型选项
const configTypes = ref<GameEventConfigTypeVO[]>([]);

// 加载配置类型数据
const loadConfigTypes = async () => {
  try {
    const res = await listGameEventConfigType({
      pageNum: 1,
      pageSize: 1000,
      orderByColumn: '',
      isAsc: ''
    });
    configTypes.value = Array.isArray(res.rows) ? res.rows : [];
  } catch (error) {
    proxy?.$modal.msgError('加载配置类型数据失败');
  }
};

// 加载赛事配置数据
const loadConfigData = async (eventId: string | number) => {
  try {
    const res = await listGameEventConfig({
      eventId: eventId === '' ? '' : eventId,
      pageNum: 1,
      pageSize: 10,
      orderByColumn: '',
      isAsc: ''
    });
    configItems.value = Array.isArray(res.rows) ? res.rows : [];
  } catch (error) {
    console.error('加载赛事配置数据失败:', error);
    proxy?.$modal.msgError('加载赛事配置数据失败: ' + (error as Error).message);
  }
};

// 添加配置项
const addConfigItem = () => {
  configItems.value.push({
    configKey: '',
    configValue: '',
    configDesc: '',
    configType: '', // 添加配置类型字段
  });
};

// 删除配置项
const removeConfigItem = (index: number) => {
  const configItem = configItems.value[index];
  if (configItem.configId) {
    delGameEventConfig(configItem.configId).then(() => {
      configItems.value.splice(index, 1);
    });
  } else {
    configItems.value.splice(index, 1);
  }
};

// 保存赛事配置数据
const saveconfigData = async (eventId: string | number) => {
  try {
    for (const item of configItems.value) {
      // 确保eventId被正确设置
      const configData = { ...item, eventId };

      if (item.configId) {
        // 更新现有队伍
        await updateGameEventConfig(configData);
      } else if (item.configDesc) {
        // 只有有名称的新队伍才保存
        await addGameEventConfig(configData);
      }
    }
  } catch (error) {
    console.error('保存赛事配置信息失败:', error);
    throw new Error('保存赛事配置信息失败');
  }
};

// 参赛队伍数据
const teamItems = ref<GameTeamForm[]>([]);
// 加载队伍数据
const loadTeamData = async (eventId: string | number) => {
  try {
    const res = await listGameTeam({
      eventId: eventId === '' ? '' : eventId,
      pageNum: 1,
      pageSize: 1000,
      orderByColumn: '',
      isAsc: ''
    });
    teamItems.value = Array.isArray(res.rows) ? res.rows : [];
  } catch (error) {
    proxy?.$modal.msgError('加载队伍数据失败');
  }
};
// 添加参赛队伍项
const addTeamItem = () => {
  teamItems.value.push({
    teamName: '',
    teamCode: '',
    eventId: getEffectiveEventId(),
    teamDescribe: '',
    remark: ''
  });
};
// 删除参赛队伍项
const removeTeamItem = (index: number) => {
  const teamItem = teamItems.value[index];
  if (teamItem.teamId) {
    delGameTeam(teamItem.teamId).then(() => {
      teamItems.value.splice(index, 1);
    });
  } else {
    teamItems.value.splice(index, 1);
  }
};
// 保存参赛队伍数据
const saveTeamData = async (eventId: string | number) => {
  try {
    for (const item of teamItems.value) {
      // 确保eventId被正确设置
      const teamData = { ...item, eventId };

      if (item.teamId) {
        // 更新现有队伍
        await updateGameTeam(teamData);
      } else if (item.teamName) {
        // 只有有名称的新队伍才保存
        await addGameTeam(teamData);
      }
    }
  } catch (error) {
    console.error('保存参赛队伍数据失败:', error);
    throw new Error('保存参赛队伍失败');
  }
};

// 保存赛事信息
const saveEvent = async () => {
  try {
    // 验证基本信息表单
    await basicFormRef.value?.validate();

    saveLoading.value = true;

    // 合并表单数据
    const formData: GameEventForm = {
      ...basicForm.value
    };

    let savedEventId: string;
    // 如果设置为默认赛事，则取消其他赛事的默认状态
    if(basicForm.value.isDefault === '0'){
      handleStatusChange({ 
        eventId: basicForm.value.eventId, 
        isDefault: basicForm.value.isDefault,
        eventName: basicForm.value.eventName 
      } as GameEventVO);
    }

    // 保存基本信息
    if (isEdit.value) {
      await updateGameEvent(formData);
      savedEventId = route.params.id as string;
    } else {
      const addRes = await addGameEvent(formData);
      // 假设返回的数据中包含新创建的赛事ID
      savedEventId = addRes?.data as string;
    }

    // 获取有效的赛事ID用于保存相关数据
    const effectiveEventId = getEffectiveEventId(savedEventId);

    // 保存图片配置数据
    await saveImageConfigData(effectiveEventId);
    // 保存赛事配置项数据
    await saveconfigData(effectiveEventId);
    // 保存菜单数据
    await saveMenuData(effectiveEventId);
    // 保存参赛队伍数据
    await saveTeamData(effectiveEventId);
    // 保存赛事项目分组数据
    await saveGroupData(effectiveEventId);
    // 保存赛事项目数据
    await saveProjectData(effectiveEventId);

    proxy?.$modal.msgSuccess('保存成功');

    // 保存成功后，设置一个标识，表示需要刷新列表数据
    sessionStorage.setItem('needRefreshGameEventList', 'true');
    goBack();
  } catch (error) {
    console.error('保存失败:', error);
    proxy?.$modal.msgError('保存失败');
  } finally {
    saveLoading.value = false;
  }
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};
</script>

<style lang="scss" scoped>
.game-event-edit {
  .page-header {
    display: flex;
    align-items: center;
    gap: 16px;

    .page-title {
      font-size: 18px;
      font-weight: 600;
    }
  }

  .menu-config,
  .project-config,
  .config-info,
  .image-config {
    .menu-header,
    .project-header,
    .config-header,
    .image-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
      }
    }
  }

  .image-config {
    .config-info {
      margin-top: 8px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }

  .team-config {
    .team-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
      }
    }
  }

  .group-config {
    .group-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
      }
    }
  }

  .form-actions {
    display: flex;
    justify-content: center;
    gap: 16px;
    margin-top: 32px;
    padding-top: 24px;
    border-top: 1px solid #ebeef5;
  }
}

:deep(.el-tabs__content) {
  padding: 20px 0;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}
</style>
