<template>
  <div class="competition-container">
    <!-- 列表视图 -->
    <div v-if="currentView === 'list'" class="list-view">
      <el-card shadow="hover">
        <div class="list-header">
          <h2 class="page-title">赛事管理</h2>
          <el-button type="primary" icon="el-icon-plus" @click="handleCreate">
            新建赛事
          </el-button>
        </div>

        <el-table
          :data="competitionList"
          border
          stripe
          style="width: 100%"
          class="data-table"
          v-loading="loading"
        >
          <el-table-column
            type="index"
            label="序号"
            width="60"
            align="center"
          />

          <el-table-column
            prop="competitionName"
            label="赛事名称"
            min-width="200"
            show-overflow-tooltip
          />

          <el-table-column
            prop="competitionCode"
            label="比赛编码"
            width="150"
            align="center"
          >
            <template #default="scope">
              <el-tag
                v-if="scope.row.competitionCode"
                type="success"
                effect="dark"
                size="default"
                style="font-family: monospace; font-weight: bold; cursor: pointer;"
                @click="copyToClipboard(scope.row.competitionCode, '比赛编码')"
              >
                {{ scope.row.competitionCode }}
              </el-tag>
              <el-tag v-else type="info" size="small">未设置</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            prop="organizer"
            label="主办单位"
            min-width="150"
            show-overflow-tooltip
          />

          <el-table-column
            prop="location"
            label="举办地点"
            width="120"
          />

          <el-table-column
            prop="competitionTime"
            label="比赛时间"
            width="180"
          />

          <el-table-column
            prop="registrationTime"
            label="报名时间"
            width="180"
          />

          <el-table-column
            label="状态"
            width="100"
            align="center"
          >
            <template #default="scope">
              <el-tag
                :type="getStatusType(scope.row.status)"
                size="small"
              >
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            width="220"
            fixed="right"
            align="center"
          >
            <template #default="scope">
              <el-button
                type="primary"
                link
                size="small"
                icon="el-icon-view"
                @click="handleView(scope.row)"
              >
                查看
              </el-button>
              <el-button
                type="warning"
                link
                size="small"
                icon="el-icon-edit"
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                link
                size="small"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-if="pagination.total > 0"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          :current-page="pagination.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.size"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          style="margin-top: 20px; text-align: right"
        />
      </el-card>
    </div>

    <!-- 表单视图 -->
    <div v-else class="form-view">
      <el-card shadow="hover" v-loading="loading">
        <div class="page-header">
          <el-button
            icon="el-icon-arrow-left"
            @click="backToList"
          >
            返回列表
          </el-button>
          <h2 class="page-title">{{ pageTitle }}</h2>
          <div class="header-actions" v-if="currentView !== 'view'">
            <el-button @click="backToList">取消</el-button>
            <el-button type="primary" @click="handleSave">
              {{ currentView === 'create' ? '创建' : '保存' }}
            </el-button>
          </div>
          <div class="header-actions" v-else>
            <el-button type="primary" @click="switchToEdit">编辑</el-button>
          </div>
        </div>

        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
          :disabled="currentView === 'view'"
          class="competition-form"
        >
          <!-- 基本信息 -->
          <div class="form-section">
            <div class="section-title">
              <i class="el-icon-document"></i>
              基本信息
            </div>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="赛事名称" prop="competitionName">
                  <el-input
                    v-model="formData.competitionName"
                    placeholder="请输入赛事名称"
                    maxlength="100"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="比赛编码" prop="competitionCode">
                  <el-input
                    v-model="formData.competitionCode"
                    placeholder="例如:WS2025 (留空自动生成)"
                    maxlength="50"
                  >
                    <template #append>
                      <el-button
                        v-if="formData.competitionCode"
                        icon="el-icon-document-copy"
                        @click="copyToClipboard(formData.competitionCode, '比赛编码')"
                      >
                        复制
                      </el-button>
                    </template>
                  </el-input>
                  <div style="font-size: 12px; color: #909399; margin-top: 4px;">
                    💡 用于评委小程序登录，建议格式：项目简称+年份（如WS2025）
                  </div>
                </el-form-item>
              </el-col>
            </el-row>

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

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="比赛场馆" prop="venue">
                  <el-input
                    v-model="formData.venue"
                    placeholder="请输入比赛场馆"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="报名时间" prop="registrationTime">
                  <el-date-picker
                    v-model="formData.registrationTimeRange"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    style="width: 100%"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="比赛时间" prop="competitionTime">
                  <el-date-picker
                    v-model="formData.competitionTimeRange"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    style="width: 100%"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="赛事状态" prop="status">
                  <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                    <el-option label="未开始" :value="1" />
                    <el-option label="报名中" :value="2" />
                    <el-option label="进行中" :value="3" />
                    <el-option label="已结束" :value="4" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 信息发布 -->
          <div class="form-section">
            <div class="section-title">
              <i class="el-icon-reading"></i>
              信息发布
            </div>

            <el-form-item label="赛事简介" prop="introduction">
              <el-input
                v-model="formData.introduction"
                type="textarea"
                :rows="4"
                placeholder="请输入赛事简介"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="联系人" prop="contactPerson">
                  <el-input
                    v-model="formData.contactPerson"
                    placeholder="请输入联系人姓名"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系电话" prop="contactPhone">
                  <el-input
                    v-model="formData.contactPhone"
                    placeholder="请输入联系电话"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系邮箱" prop="contactEmail">
                  <el-input
                    v-model="formData.contactEmail"
                    placeholder="请输入联系邮箱"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 赛事规程 -->
          <div class="form-section">
            <div class="section-title">
              <i class="el-icon-document-checked"></i>
              赛事规程
            </div>

            <el-form-item label="比赛规则" prop="rules">
              <el-input
                v-model="formData.rules"
                type="textarea"
                :rows="4"
                placeholder="请输入比赛规则"
              />
            </el-form-item>

            <el-form-item label="参赛要求" prop="requirements">
              <el-input
                v-model="formData.requirements"
                type="textarea"
                :rows="4"
                placeholder="请输入参赛要求"
              />
            </el-form-item>

            <el-form-item label="奖项设置" prop="awards">
              <el-input
                v-model="formData.awards"
                type="textarea"
                :rows="4"
                placeholder="请输入奖项设置"
              />
            </el-form-item>
          </div>

          <!-- 附件管理 -->
          <div class="form-section">
            <div class="section-title">
              <i class="el-icon-folder-opened"></i>
              附件管理
            </div>

            <!-- 附件类型选项卡 -->
            <el-tabs v-model="activeAttachmentTab" type="card">
              <el-tab-pane
                v-for="tab in attachmentTabs"
                :key="tab.type"
                :label="tab.label"
                :name="tab.type"
              >
                <div class="attachment-section">
                  <!-- 上传按钮 -->
                  <div class="attachment-upload" v-if="currentView !== 'view'">
                    <el-button
                      type="primary"
                      icon="el-icon-upload"
                      size="small"
                      @click="handleOpenAttachmentUpload(tab.type)"
                    >
                      上传{{ tab.label }}附件
                    </el-button>
                    <span class="upload-tip">支持 PDF、Word、Excel、图片等格式，单个文件不超过 50MB</span>
                  </div>

                  <!-- 附件列表 -->
                  <el-table
                    :data="formData.attachments[tab.type] || []"
                    border
                    style="width: 100%; margin-top: 15px;"
                    v-if="(formData.attachments[tab.type] || []).length > 0"
                  >
                    <el-table-column
                      label="文件名"
                      min-width="200"
                      show-overflow-tooltip
                    >
                      <template #default="scope">
                        <div class="file-name-cell">
                          <i :class="getFileIcon(scope.row.fileType)" class="file-icon"></i>
                          <span>{{ scope.row.fileName }}</span>
                        </div>
                      </template>
                    </el-table-column>

                    <el-table-column
                      label="文件大小"
                      width="120"
                      align="center"
                    >
                      <template #default="scope">
                        {{ formatFileSize(scope.row.fileSize) }}
                      </template>
                    </el-table-column>

                    <el-table-column
                      label="上传时间"
                      width="180"
                      align="center"
                    >
                      <template #default="scope">
                        {{ scope.row.createTime || '-' }}
                      </template>
                    </el-table-column>

                    <el-table-column
                      label="排序"
                      width="100"
                      align="center"
                    >
                      <template #default="scope">
                        <el-input-number
                          v-if="currentView !== 'view'"
                          v-model="scope.row.orderNum"
                          :min="0"
                          :max="999"
                          size="small"
                          style="width: 80px"
                          controls-position="right"
                        />
                        <span v-else>{{ scope.row.orderNum }}</span>
                      </template>
                    </el-table-column>

                    <el-table-column
                      label="操作"
                      width="150"
                      align="center"
                      fixed="right"
                    >
                      <template #default="scope">
                        <el-button
                          type="primary"
                          link
                          size="small"
                          @click="handlePreviewAttachment(scope.row)"
                        >
                          预览
                        </el-button>
                        <el-button
                          v-if="currentView !== 'view'"
                          type="danger"
                          link
                          size="small"
                          @click="handleDeleteAttachment(tab.type, scope.$index)"
                        >
                          删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>

                  <!-- 空状态 -->
                  <div class="empty-attachment" v-else>
                    <i class="el-icon-folder-opened"></i>
                    <p>暂无{{ tab.label }}附件</p>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>

          <!-- 活动日程 -->
          <!-- <div class="form-section">
            <div class="section-title">
              <i class="el-icon-date"></i>
              活动日程
            </div>

            <el-form-item label="" class="button-right">
              <el-button
                v-if="currentView !== 'view'"
                type="primary"
                icon="el-icon-plus"
                size="small"
                @click="handleAddSchedule"
              >
                添加日程
              </el-button>
            </el-form-item>

            <el-table
              :data="formData.schedule"
              border
              style="width: 100%"
            >
              <el-table-column
                label="日期"
                width="160"
              >
                <template #default="scope">
                  <el-date-picker
                    v-if="currentView !== 'view'"
                    v-model="scope.row.scheduleDate"
                    type="date"
                    placeholder="选择日期"
                    size="small"
                    style="width: 100%"
                    value-format="YYYY-MM-DD"
                  />
                  <span v-else>{{ scope.row.scheduleDate }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="时间"
                width="140"
              >
                <template #default="scope">
                  <el-time-picker
                    v-if="currentView !== 'view'"
                    v-model="scope.row.scheduleTime"
                    placeholder="选择时间"
                    size="small"
                    style="width: 100%"
                    value-format="HH:mm:ss"
                  />
                  <span v-else>{{ scope.row.scheduleTime }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="活动项目"
                min-width="150"
              >
                <template #default="scope">
                  <el-input
                    v-if="currentView !== 'view'"
                    v-model="scope.row.eventName"
                    placeholder="请输入活动项目"
                    size="small"
                  />
                  <span v-else>{{ scope.row.eventName }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="地点"
                width="140"
              >
                <template #default="scope">
                  <el-input
                    v-if="currentView !== 'view'"
                    v-model="scope.row.venue"
                    placeholder="请输入地点"
                    size="small"
                  />
                  <span v-else>{{ scope.row.venue }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="描述"
                min-width="150"
              >
                <template #default="scope">
                  <el-input
                    v-if="currentView !== 'view'"
                    v-model="scope.row.description"
                    placeholder="请输入描述"
                    size="small"
                  />
                  <span v-else>{{ scope.row.description }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="排序"
                width="80"
                align="center"
              >
                <template #default="scope">
                  <el-input-number
                    v-if="currentView !== 'view'"
                    v-model="scope.row.sortOrder"
                    :min="0"
                    :max="999"
                    size="small"
                    style="width: 100%"
                    controls-position="right"
                  />
                  <span v-else>{{ scope.row.sortOrder }}</span>
                </template>
              </el-table-column>

              <el-table-column
                v-if="currentView !== 'view'"
                label="操作"
                width="80"
                align="center"
              >
                <template #default="scope">
                  <el-button
                    type="danger"
                    link
                    size="small"
                    icon="el-icon-delete"
                    @click="handleDeleteSchedule(scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div> -->

          <!-- 项目列表 -->
          <div class="form-section">
            <div class="section-title">
              <i class="el-icon-medal"></i>
              项目列表
            </div>

            <el-form-item label="" class="button-right">
              <el-button
                v-if="currentView !== 'view'"
                type="primary"
                icon="el-icon-plus"
                size="small"
                @click="handleAddProject"
              >
                添加项目
              </el-button>
            </el-form-item>

            <el-table
              :data="formData.projects"
              border
              style="width: 100%"
            >
              <el-table-column
                label="项目名称"
                min-width="150"
              >
                <template #default="scope">
                  <el-input
                    v-if="currentView !== 'view'"
                    v-model="scope.row.projectName"
                    placeholder="例如：太极拳"
                    size="small"
                  />
                  <span v-else>{{ scope.row.projectName }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="项目代码"
                width="120"
              >
                <template #default="scope">
                  <el-input
                    v-if="currentView !== 'view'"
                    v-model="scope.row.projectCode"
                    placeholder="例如：TJQ001"
                    size="small"
                  />
                  <span v-else>{{ scope.row.projectCode }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="组别"
                width="120"
              >
                <template #default="scope">
                  <el-input
                    v-if="currentView !== 'view'"
                    v-model="scope.row.category"
                    placeholder="例如：成年男子组"
                    size="small"
                  />
                  <span v-else>{{ scope.row.category }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="参赛人数限制"
                width="130"
                align="center"
              >
                <template #default="scope">
                  <el-input-number
                    v-if="currentView !== 'view'"
                    v-model="scope.row.maxParticipants"
                    :min="1"
                    :max="9999"
                    size="small"
                    style="width: 100%"
                  />
                  <span v-else>{{ scope.row.maxParticipants || '不限' }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="报名费用(元)"
                width="130"
                align="center"
              >
                <template #default="scope">
                  <el-input-number
                    v-if="currentView !== 'view'"
                    v-model="scope.row.price"
                    :min="0"
                    :precision="2"
                    :step="10"
                    size="small"
                    style="width: 100%"
                    placeholder="0.00"
                  />
                  <span v-else style="color: #f56c6c">¥{{ scope.row.price || 0 }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="项目说明"
                min-width="200"
              >
                <template #default="scope">
                  <el-input
                    v-if="currentView !== 'view'"
                    v-model="scope.row.description"
                    placeholder="请输入项目说明"
                    size="small"
                  />
                  <span v-else>{{ scope.row.description }}</span>
                </template>
              </el-table-column>

              <el-table-column
                v-if="currentView !== 'view'"
                label="操作"
                width="80"
                align="center"
              >
                <template #default="scope">
                  <el-button
                    type="danger"
                    link
                    size="small"
                    icon="el-icon-delete"
                    @click="handleDeleteProject(scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 场地配置 -->
          <div class="form-section">
            <div class="section-title">
              <i class="el-icon-office-building"></i>
              场地配置
            </div>

            <el-form-item label="" class="button-right">
              <el-button
                v-if="currentView !== 'view'"
                type="primary"
                icon="el-icon-plus"
                size="small"
                @click="handleAddVenue"
              >
                添加场地
              </el-button>
            </el-form-item>

            <el-table
              :data="formData.venues"
              border
              style="width: 100%"
            >
              <el-table-column
                label="场地名称"
                width="150"
              >
                <template #default="scope">
                  <el-input
                    v-if="currentView !== 'view'"
                    v-model="scope.row.venueName"
                    placeholder="例如：主比赛场A"
                    size="small"
                  />
                  <span v-else>{{ scope.row.venueName }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="场地编号"
                width="120"
              >
                <template #default="scope">
                  <el-input
                    v-if="currentView !== 'view'"
                    v-model="scope.row.venueCode"
                    placeholder="例如：A001"
                    size="small"
                  />
                  <span v-else>{{ scope.row.venueCode }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="场地类型"
                width="120"
              >
                <template #default="scope">
                  <el-select
                    v-if="currentView !== 'view'"
                    v-model="scope.row.venueType"
                    placeholder="请选择"
                    size="small"
                    style="width: 100%"
                  >
                    <el-option label="室内" value="indoor" />
                    <el-option label="室外" value="outdoor" />
                  </el-select>
                  <span v-else>{{ scope.row.venueType === 'indoor' ? '室内' : '室外' }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="容纳人数"
                width="120"
                align="center"
              >
                <template #default="scope">
                  <el-input-number
                    v-if="currentView !== 'view'"
                    v-model="scope.row.capacity"
                    :min="1"
                    :max="99999"
                    size="small"
                    style="width: 100%"
                  />
                  <span v-else>{{ scope.row.capacity }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="位置"
                min-width="150"
              >
                <template #default="scope">
                  <el-input
                    v-if="currentView !== 'view'"
                    v-model="scope.row.location"
                    placeholder="例如：体育馆1楼东侧"
                    size="small"
                  />
                  <span v-else>{{ scope.row.location }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="备注"
                min-width="200"
              >
                <template #default="scope">
                  <el-input
                    v-if="currentView !== 'view'"
                    v-model="scope.row.remark"
                    placeholder="请输入备注"
                    size="small"
                  />
                  <span v-else>{{ scope.row.remark }}</span>
                </template>
              </el-table-column>

              <el-table-column
                v-if="currentView !== 'view'"
                label="操作"
                width="80"
                align="center"
              >
                <template #default="scope">
                  <el-button
                    type="danger"
                    link
                    size="small"
                    icon="el-icon-delete"
                    @click="handleDeleteVenue(scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
      </el-card>
    </div>

    <!-- 附件上传对话框 -->
    <el-dialog
      title="上传附件"
      v-model="attachmentUploadDialogVisible"
      width="555px"
      append-to-body
      :close-on-click-modal="false"
    >
      <avue-form
        ref="attachmentUploadForm"
        :option="attachmentUploadOption"
        v-model="attachmentUploadForm"
        :upload-after="attachmentUploadAfter"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  getCompetitionList,
  getCompetitionDetail,
  submitCompetition,
  removeCompetition
} from '@/api/martial/competition'
import {
  getActivityScheduleList,
  submitActivitySchedule,
  removeActivitySchedule
} from '@/api/martial/activitySchedule'
import {
  submitProject,
  removeProject,
  getProjectsByCompetition
} from '@/api/martial/project'
import {
  submitVenue,
  removeVenue,
  getVenuesByCompetition
} from '@/api/martial/venue'
import {
  getAttachmentsByCompetition,
  submitAttachment,
  removeAttachment,
  batchSubmitAttachments,
  ATTACHMENT_TYPES,
  ATTACHMENT_TYPE_LABELS
} from '@/api/martial/attachment'

export default {
  name: 'CompetitionManagement',
  data() {
    return {
      currentView: 'list', // list, create, edit, view
      competitionId: null,
      loading: false,
      competitionList: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 附件相关数据
      activeAttachmentTab: 'info',
      attachmentTabs: [
        { type: 'info', label: '赛事发布' },
        { type: 'rules', label: '赛事规程' },
        { type: 'schedule', label: '活动日程' },
        { type: 'results', label: '成绩' },
        { type: 'medals', label: '奖牌榜' },
        { type: 'photos', label: '图片直播' }
      ],
      attachmentUploadDialogVisible: false,
      currentAttachmentType: '',
      attachmentUploadForm: {},
      attachmentUploadOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '附件上传',
            prop: 'attachmentFile',
            type: 'upload',
            drag: true,
            loadText: '文件上传中，请稍等',
            span: 24,
            accept: '.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.jpg,.jpeg,.png,.gif,.zip,.rar',
            tip: '支持 PDF、Word、Excel、PPT、图片、压缩包等格式，单个文件不超过 50MB',
            propsHttp: {
              res: 'data',
            },
            action: '/blade-resource/oss/endpoint/put-file'
          }
        ]
      },
      formData: {
        competitionName: '',
        competitionCode: '', // 比赛编码
        organizer: '',
        location: '',
        venue: '',
        registrationTime: '',
        registrationTimeRange: [],
        competitionTime: '',
        competitionTimeRange: [],
        status: 1,
        introduction: '',
        contactPerson: '',
        contactPhone: '',
        contactEmail: '',
        rules: '',
        requirements: '',
        awards: '',
        schedule: [],
        projects: [],
        venues: [],
        attachments: {
          info: [],
          rules: [],
          schedule: [],
          results: [],
          medals: [],
          photos: []
        }
      },
      formRules: {
        competitionName: [
          { required: true, message: '请输入赛事名称', trigger: 'blur' }
        ],
        organizer: [
          { required: true, message: '请输入主办单位', trigger: 'blur' }
        ],
        location: [
          { required: true, message: '请输入举办地点', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    pageTitle() {
      const titleMap = {
        create: '新建赛事',
        edit: '编辑赛事',
        view: '查看赛事'
      };
      return titleMap[this.currentView] || '赛事信息';
    }
  },
  watch: {
    '$route.query': {
      handler(query) {
        console.log('路由查询参数变化:', query);
        this.initPage();
      },
      immediate: true
    },
    competitionList: {
      handler(newVal) {
        console.log('competitionList 变化:', newVal);
        console.log('competitionList 长度:', newVal?.length);
      },
      deep: true
    },
    currentView: {
      handler(newVal) {
        console.log('currentView 变化:', newVal);
      }
    }
  },
  mounted() {
    console.log('组件已挂载 mounted');
    console.log('当前视图:', this.currentView);
    console.log('当前列表数据:', this.competitionList);
    // 不需要在这里调用 loadCompetitionList()，因为 watch '$route.query' 的 immediate: true 会在初始化时调用 initPage()
  },
  methods: {
    initPage() {
      console.log('======= initPage 开始 =======');
      const { mode, id } = this.$route.query;
      console.log('路由参数 - mode:', mode, 'id:', id);

      this.currentView = mode || 'list';
      // 不要使用 parseInt，直接使用字符串 ID，避免大整数精度丢失
      this.competitionId = id || null;

      console.log('设置后 - currentView:', this.currentView);
      console.log('设置后 - competitionId:', this.competitionId);

      if (this.currentView === 'list') {
        // 切换到列表视图时重新加载数据
        console.log('当前是列表视图，准备加载数据');
        this.loadCompetitionList();
      } else if (this.currentView !== 'list' && this.competitionId) {
        console.log('当前是编辑/查看视图，加载详情');
        this.loadCompetitionData();
      } else if (this.currentView === 'create') {
        console.log('当前是创建视图，重置表单');
        this.resetFormData();
      }
      console.log('======= initPage 结束 =======');
    },

    loadCompetitionList() {
      this.loading = true;
      getCompetitionList(this.pagination.current, this.pagination.size, {})
        .then(res => {
          console.log('赛事列表返回数据:', res);
          console.log('res.data:', res.data);
          console.log('res.data.data:', res.data?.data);
          console.log('res.data.data.records:', res.data?.data?.records);

          // 修正：实际数据在 res.data.data 中
          const responseData = res.data?.data;
          if (responseData && responseData.records) {
            try {
              this.competitionList = responseData.records.map((item, index) => {
                console.log(`正在格式化第 ${index + 1} 条数据:`, item);
                const formatted = this.formatBackendData(item);
                console.log(`格式化结果:`, formatted);
                return formatted;
              });
              this.pagination.total = responseData.total || 0;
              console.log('最终列表数据:', this.competitionList);
              console.log('列表长度:', this.competitionList.length);
              console.log('总数:', this.pagination.total);
            } catch (error) {
              console.error('格式化数据时出错:', error);
              this.$message.error('数据格式化失败');
            }
          } else {
            console.warn('返回数据结构不正确:', res);
          }
        })
        .catch(err => {
          console.error('加载赛事列表失败', err);
          this.$message.error('加载赛事列表失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },

    handlePageChange(current) {
      this.pagination.current = current;
      this.loadCompetitionList();
    },

    handleSizeChange(size) {
      this.pagination.size = size;
      this.pagination.current = 1;
      this.loadCompetitionList();
    },

    saveCompetitionList() {
      // 不再需要保存到 localStorage
    },

    loadCompetitionData() {
      if (!this.competitionId) return;

      this.loading = true;
      getCompetitionDetail(this.competitionId)
        .then(res => {
          console.log('赛事详情返回数据:', res);
          // 修正:实际数据在 res.data.data 中
          const detailData = res.data?.data;
          console.log('detailData:', detailData);
          if (detailData) {
            try {
              this.formData = this.formatBackendData(detailData);
              console.log('格式化后的表单数据:', this.formData);
              // 加载关联数据：活动日程、项目列表、场地配置、附件
              this.loadActivitySchedules();
              this.loadProjects();
              this.loadVenues();
              this.loadAttachments();
            } catch (error) {
              console.error('格式化数据时出错:', error);
              this.$message.error('数据格式化失败: ' + error.message);
            }
          } else {
            console.warn('未获取到详情数据');
            this.$message.warning('未获取到赛事详情');
          }
        })
        .catch(err => {
          console.error('加载赛事详情失败', err);
          this.$message.error('加载赛事详情失败: ' + (err.message || '未知错误'));
        })
        .finally(() => {
          this.loading = false;
        });
    },

    loadActivitySchedules() {
      if (!this.competitionId) {
        console.warn('loadActivitySchedules: competitionId 为空，跳过加载');
        return;
      }

      console.log('开始加载活动日程，competitionId:', this.competitionId);
      getActivityScheduleList(1, 100, { competitionId: this.competitionId })
        .then(res => {
          console.log('活动日程返回数据:', res);
          console.log('res.data:', res.data);
          console.log('res.data.data:', res.data?.data);
          const responseData = res.data?.data;
          if (responseData && responseData.records) {
            console.log('活动日程 records:', responseData.records);
            this.formData.schedule = responseData.records.map(item => ({
              id: item.id,
              scheduleDate: item.scheduleDate,
              scheduleTime: item.scheduleTime,
              eventName: item.eventName,
              venue: item.venue,
              description: item.description,
              sortOrder: item.sortOrder
            }));
            console.log('✅ 加载的活动日程:', this.formData.schedule);
            console.log('✅ 活动日程数量:', this.formData.schedule.length);
          } else {
            console.log('⚠️ 活动日程数据为空或格式不正确');
            this.formData.schedule = [];
          }
        })
        .catch(err => {
          console.error('❌ 加载活动日程失败:', err);
          this.formData.schedule = [];
          // 不显示错误消息，因为可能是新建赛事还没有日程
        });
    },

    loadProjects() {
      if (!this.competitionId) {
        console.warn('loadProjects: competitionId 为空，跳过加载');
        return;
      }

      console.log('开始加载项目列表，competitionId:', this.competitionId);
      getProjectsByCompetition(this.competitionId)
        .then(res => {
          console.log('项目列表返回数据:', res);
          console.log('res.data:', res.data);
          console.log('res.data.data:', res.data?.data);
          const responseData = res.data?.data;

          let projectList = [];
          if (responseData) {
            if (Array.isArray(responseData)) {
              projectList = responseData;
              console.log('项目数据格式：直接数组');
            } else if (responseData.records && Array.isArray(responseData.records)) {
              projectList = responseData.records;
              console.log('项目数据格式：分页对象');
            }
          }

          console.log('解析出的项目列表:', projectList);
          console.log('项目列表长度:', projectList.length);

          if (projectList.length > 0) {
            this.formData.projects = projectList.map(item => ({
              id: item.id,
              projectName: item.projectName,
              projectCode: item.projectCode,
              category: item.category,
              type: item.type,
              minParticipants: item.minParticipants,
              maxParticipants: item.maxParticipants,
              estimatedDuration: item.estimatedDuration,
              price: item.price,
              description: item.description
            }));
            console.log('✅ 加载的项目列表:', this.formData.projects);
            console.log('✅ 项目数量:', this.formData.projects.length);
          } else {
            console.log('⚠️ 项目列表为空');
            this.formData.projects = [];
          }
        })
        .catch(err => {
          console.error('❌ 加载项目列表失败:', err);
          this.formData.projects = [];
          // 不显示错误消息，因为可能是新建赛事还没有项目
        });
    },

    loadVenues() {
      if (!this.competitionId) {
        console.warn('loadVenues: competitionId 为空，跳过加载');
        return;
      }

      console.log('开始加载场地列表，competitionId:', this.competitionId);
      getVenuesByCompetition(this.competitionId)
        .then(res => {
          console.log('场地列表返回数据:', res);
          console.log('res.data:', res.data);
          console.log('res.data.data:', res.data?.data);
          const responseData = res.data?.data;

          let venueList = [];
          if (responseData) {
            if (Array.isArray(responseData)) {
              venueList = responseData;
              console.log('场地数据格式：直接数组');
            } else if (responseData.records && Array.isArray(responseData.records)) {
              venueList = responseData.records;
              console.log('场地数据格式：分页对象');
            }
          }

          console.log('解析出的场地列表:', venueList);
          console.log('场地列表长度:', venueList.length);

          if (venueList.length > 0) {
            this.formData.venues = venueList.map(item => ({
              id: item.id,
              venueName: item.venueName,
              venueCode: item.venueCode,
              capacity: item.capacity,
              location: item.location,
              remark: item.facilities || ''
            }));
            console.log('✅ 加载的场地列表:', this.formData.venues);
            console.log('✅ 场地数量:', this.formData.venues.length);
          } else {
            console.log('⚠️ 场地列表为空');
            this.formData.venues = [];
          }
        })
        .catch(err => {
          console.error('❌ 加载场地列表失败:', err);
          this.formData.venues = [];
          // 不显示错误消息，因为可能是新建赛事还没有场地
        });
    },

    // 加载附件列表
    loadAttachments() {
      if (!this.competitionId) {
        console.warn('loadAttachments: competitionId 为空，跳过加载');
        return;
      }

      console.log('开始加载附件列表，competitionId:', this.competitionId);
      getAttachmentsByCompetition(this.competitionId)
        .then(res => {
          console.log('附件列表返回数据:', res);
          const responseData = res.data?.data;

          // 初始化附件对象
          const attachments = {
            info: [],
            rules: [],
            schedule: [],
            results: [],
            medals: [],
            photos: []
          };

          if (responseData && Array.isArray(responseData)) {
            // 按类型分组
            responseData.forEach(item => {
              const type = item.attachmentType;
              if (attachments[type]) {
                attachments[type].push({
                  id: item.id,
                  fileName: item.fileName,
                  fileUrl: item.fileUrl,
                  fileSize: item.fileSize,
                  fileType: item.fileType,
                  orderNum: item.orderNum || 0,
                  createTime: item.createTime
                });
              }
            });
            console.log('✅ 加载的附件列表:', attachments);
          } else {
            console.log('⚠️ 附件列表为空');
          }

          this.formData.attachments = attachments;
        })
        .catch(err => {
          console.error('❌ 加载附件列表失败:', err);
          // 不显示错误消息，因为可能是新建赛事还没有附件
        });
    },

    // 打开附件上传对话框
    handleOpenAttachmentUpload(type) {
      this.currentAttachmentType = type;
      this.attachmentUploadForm = {};
      this.attachmentUploadDialogVisible = true;
    },

    // 附件上传成功回调
    attachmentUploadAfter(res, done, loading, column) {
      console.log('附件上传响应:', res);

      if (res && (res.link || res.url)) {
        const fileUrl = res.link || res.url;
        const fileName = res.originalName || res.name || this.getFileNameFromUrl(fileUrl);
        const fileType = this.getFileExtension(fileName);
        const fileSize = res.size || 0;

        // 添加到对应类型的附件列表
        if (!this.formData.attachments[this.currentAttachmentType]) {
          this.formData.attachments[this.currentAttachmentType] = [];
        }

        this.formData.attachments[this.currentAttachmentType].push({
          fileName: fileName,
          fileUrl: fileUrl,
          fileSize: fileSize,
          fileType: fileType,
          orderNum: this.formData.attachments[this.currentAttachmentType].length,
          isNew: true // 标记为新上传的附件
        });

        this.$message.success('附件上传成功');
        this.attachmentUploadDialogVisible = false;
      } else {
        this.$message.error('上传失败，未获取到文件地址');
      }
      done();
    },

    // 预览附件
    handlePreviewAttachment(attachment) {
      if (!attachment.fileUrl) {
        this.$message.warning('文件地址不存在');
        return;
      }
      window.open(attachment.fileUrl, '_blank');
    },

    // 删除附件
    handleDeleteAttachment(type, index) {
      this.$confirm('确定要删除该附件吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const attachment = this.formData.attachments[type][index];

        // 如果是已保存的附件，需要调用后端删除
        if (attachment.id) {
          removeAttachment(attachment.id.toString())
            .then(() => {
              this.formData.attachments[type].splice(index, 1);
              this.$message.success('删除成功');
            })
            .catch(err => {
              console.error('删除附件失败:', err);
              this.$message.error('删除失败');
            });
        } else {
          // 新上传的附件直接从列表中移除
          this.formData.attachments[type].splice(index, 1);
          this.$message.success('删除成功');
        }
      }).catch(() => {});
    },

    // 获取文件图标
    getFileIcon(fileType) {
      const iconMap = {
        'pdf': 'el-icon-document',
        'doc': 'el-icon-document',
        'docx': 'el-icon-document',
        'xls': 'el-icon-document',
        'xlsx': 'el-icon-document',
        'ppt': 'el-icon-document',
        'pptx': 'el-icon-document',
        'jpg': 'el-icon-picture',
        'jpeg': 'el-icon-picture',
        'png': 'el-icon-picture',
        'gif': 'el-icon-picture',
        'zip': 'el-icon-folder',
        'rar': 'el-icon-folder'
      };
      return iconMap[fileType?.toLowerCase()] || 'el-icon-document';
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (!bytes || bytes === 0) return '0 B';
      if (typeof bytes === 'string') return bytes;

      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return (bytes / Math.pow(k, i)).toFixed(1) + ' ' + sizes[i];
    },

    // 从URL获取文件名
    getFileNameFromUrl(url) {
      if (!url) return 'unknown';
      const parts = url.split('/');
      return parts[parts.length - 1] || 'unknown';
    },

    // 获取文件扩展名
    getFileExtension(fileName) {
      if (!fileName) return '';
      const parts = fileName.split('.');
      return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : '';
    },

    // 保存附件
    async saveAttachments(competitionId) {
      const allAttachments = [];

      // 收集所有需要保存的附件
      for (const type of Object.keys(this.formData.attachments)) {
        const attachments = this.formData.attachments[type] || [];
        for (const attachment of attachments) {
          // 只保存新上传的附件或已修改的附件
          if (attachment.isNew || attachment.isModified) {
            allAttachments.push({
              id: attachment.id || null,
              competitionId: competitionId,
              attachmentType: type,
              fileName: attachment.fileName,
              fileUrl: attachment.fileUrl,
              fileSize: attachment.fileSize,
              fileType: attachment.fileType,
              orderNum: attachment.orderNum || 0,
              status: 1
            });
          }
        }
      }

      if (allAttachments.length === 0) {
        return Promise.resolve();
      }

      console.log('准备保存的附件:', allAttachments);
      return batchSubmitAttachments(allAttachments);
    },

    getStatusText(status) {
      const statusMap = {
        1: '未开始',
        2: '报名中',
        3: '进行中',
        4: '已结束'
      };
      return statusMap[status] || '未知';
    },

    getStatusType(status) {
      const typeMap = {
        1: 'info',
        2: 'success',
        3: 'warning',
        4: 'danger'
      };
      return typeMap[status] || '';
    },

    handleCreate() {
      this.$router.push({
        path: '/martial/competition/list',
        query: { mode: 'create' }
      });
    },

    handleView(row) {
      console.log(row)
      this.$router.push({
        path: '/martial/competition/list',
        query: { mode: 'view', id: row.id }
      });
    },

    handleEdit(row) {
      this.$router.push({
        path: '/martial/competition/list',
        query: { mode: 'edit', id: row.id }
      });
    },

    switchToEdit() {
      this.$router.push({
        path: '/martial/competition/list',
        query: { mode: 'edit', id: this.competitionId }
      });
    },

    handleDelete(row) {
      this.$confirm('确定要删除该赛事吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        removeCompetition(row.id.toString())
          .then(res => {
            this.$message.success('删除成功');
            this.loadCompetitionList();
          })
          .catch(err => {
            console.error('删除失败', err);
            this.$message.error('删除失败');
          })
          .finally(() => {
            this.loading = false;
          });
      }).catch(() => {});
    },

    handleAddSchedule() {
      this.formData.schedule.push({
        scheduleDate: '',
        scheduleTime: '',
        eventName: '',
        venue: '',
        description: '',
        sortOrder: 0
      });
    },

    handleDeleteSchedule(index) {
      this.formData.schedule.splice(index, 1);
    },

    // 项目列表管理
    handleAddProject() {
      this.formData.projects.push({
        projectName: '',
        projectCode: '',
        category: '',
        maxParticipants: null,
        price: 0,
        description: ''
      });
    },

    handleDeleteProject(index) {
      this.formData.projects.splice(index, 1);
    },

    // 场地配置管理
    handleAddVenue() {
      this.formData.venues.push({
        venueName: '',
        venueCode: '',
        venueType: 'indoor',
        capacity: null,
        location: '',
        remark: ''
      });
    },

    handleDeleteVenue(index) {
      this.formData.venues.splice(index, 1);
    },

    handleSave() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.loading = true;
          const submitData = this.prepareSubmitData(this.formData);

          console.log('提交的数据:', submitData);

          // 如果是编辑模式，需要传入 id
          if (this.currentView === 'edit' && this.competitionId) {
            submitData.id = this.competitionId;
          }

          submitCompetition(submitData)
            .then(res => {
              console.log('保存成功返回:', res);
              const savedCompetitionId = this.currentView === 'edit'
                ? this.competitionId
                : res.data?.data?.id || res.data?.data;

              console.log('赛事ID:', savedCompetitionId);

              // 依次保存：活动日程 → 项目列表 → 场地配置
              const savePromises = [];

              // 1. 保存活动日程
              if (this.formData.schedule && this.formData.schedule.length > 0) {
                savePromises.push(this.saveActivitySchedules(savedCompetitionId));
              }

              // 2. 保存项目列表
              if (this.formData.projects && this.formData.projects.length > 0) {
                savePromises.push(this.saveProjects(savedCompetitionId));
              }

              // 3. 保存场地配置
              if (this.formData.venues && this.formData.venues.length > 0) {
                savePromises.push(this.saveVenues(savedCompetitionId));
              }

              // 4. 保存附件
              savePromises.push(this.saveAttachments(savedCompetitionId));

              // 等待所有保存操作完成
              if (savePromises.length > 0) {
                Promise.all(savePromises)
                  .then(() => {
                    this.$message.success(this.currentView === 'create' ? '创建成功' : '保存成功');
                    this.backToList();
                  })
                  .catch(err => {
                    console.error('保存关联数据失败', err);
                    this.$message.warning('赛事保存成功，但部分关联数据保存失败');
                    this.backToList();
                  });
              } else {
                this.$message.success(this.currentView === 'create' ? '创建成功' : '保存成功');
                this.backToList();
              }
            })
            .catch(err => {
              console.error('保存失败', err);
              this.$message.error(this.currentView === 'create' ? '创建失败' : '保存失败');
            })
            .finally(() => {
              this.loading = false;
            });
        } else {
          this.$message.error('请完善必填信息');
        }
      });
    },

    async saveActivitySchedules(competitionId) {
      const schedules = this.formData.schedule.filter(item =>
        item.scheduleDate && item.scheduleTime && item.eventName
      );

      if (schedules.length === 0) {
        return Promise.resolve();
      }

      console.log('准备保存的活动日程:', schedules);
      console.log('竞赛ID（原始）:', competitionId);

      // 如果是对象则取其 id 字段，否则直接使用（保持字符串格式，避免精度丢失）
      let finalCompetitionId = competitionId;
      if (typeof competitionId === 'object' && competitionId !== null) {
        finalCompetitionId = competitionId.id || competitionId.competitionId;
      }

      console.log('竞赛ID（处理后）:', finalCompetitionId);

      const promises = schedules.map(schedule => {
        const scheduleData = {
          competitionId: finalCompetitionId,
          scheduleDate: schedule.scheduleDate,
          scheduleTime: schedule.scheduleTime,
          eventName: schedule.eventName,
          venue: schedule.venue || '',
          description: schedule.description || '',
          sortOrder: schedule.sortOrder || 0
        };

        // 如果有 id，说明是编辑已有的日程
        if (schedule.id) {
          scheduleData.id = schedule.id;
        }

        console.log('提交活动日程:', scheduleData);
        return submitActivitySchedule(scheduleData);
      });

      return Promise.all(promises);
    },

    async saveProjects(competitionId) {
      const projects = this.formData.projects.filter(item =>
        item.projectName && item.projectCode
      );

      if (projects.length === 0) {
        return Promise.resolve();
      }

      console.log('准备保存的项目列表:', projects);

      // 如果是对象则取其 id 字段，否则直接使用（保持字符串格式，避免精度丢失）
      let finalCompetitionId = competitionId;
      if (typeof competitionId === 'object' && competitionId !== null) {
        finalCompetitionId = competitionId.id || competitionId.competitionId;
      }

      console.log('保存项目的竞赛ID:', finalCompetitionId);

      const promises = projects.map(project => {
        const projectData = {
          competitionId: finalCompetitionId,
          projectName: project.projectName,
          projectCode: project.projectCode,
          category: project.category || '',
          type: project.type || 1, // 默认个人项目
          minParticipants: project.minParticipants || 1,
          maxParticipants: project.maxParticipants || 1,
          estimatedDuration: project.estimatedDuration || 5,
          price: project.price || 0,
          description: project.description || ''
        };

        // 如果有 id，说明是编辑已有的项目
        if (project.id) {
          projectData.id = project.id;
        }

        console.log('提交项目:', projectData);
        return submitProject(projectData);
      });

      return Promise.all(promises);
    },

    async saveVenues(competitionId) {
      const venues = this.formData.venues.filter(item =>
        item.venueName && item.venueCode
      );

      if (venues.length === 0) {
        return Promise.resolve();
      }

      console.log('准备保存的场地配置:', venues);

      // 如果是对象则取其 id 字段，否则直接使用（保持字符串格式，避免精度丢失）
      let finalCompetitionId = competitionId;
      if (typeof competitionId === 'object' && competitionId !== null) {
        finalCompetitionId = competitionId.id || competitionId.competitionId;
      }

      console.log('保存场地的竞赛ID:', finalCompetitionId);

      const promises = venues.map(venue => {
        const venueData = {
          competitionId: finalCompetitionId,
          venueName: venue.venueName,
          venueCode: venue.venueCode,
          capacity: venue.capacity || 100,
          location: venue.location || '',
          facilities: venue.remark || ''
        };

        // 如果有 id，说明是编辑已有的场地
        if (venue.id) {
          venueData.id = venue.id;
        }

        console.log('提交场地:', venueData);
        return submitVenue(venueData);
      });

      return Promise.all(promises);
    },

    backToList() {
      this.$router.push({
        path: '/martial/competition/list'
      });
      // 路由跳转后，在 initPage 中会自动加载列表
    },

    resetFormData() {
      this.formData = {
        competitionName: '',
        competitionCode: '', // 比赛编码
        organizer: '',
        location: '',
        venue: '',
        registrationTime: '',
        registrationTimeRange: [],
        competitionTime: '',
        competitionTimeRange: [],
        status: 1,
        introduction: '',
        contactPerson: '',
        contactPhone: '',
        contactEmail: '',
        rules: '',
        requirements: '',
        awards: '',
        schedule: [],
        projects: [],
        venues: [],
        attachments: {
          info: [],
          rules: [],
          schedule: [],
          results: [],
          medals: [],
          photos: []
        }
      };
    },

    // 时间字段转换：前端显示格式 <-> 后端存储格式
    formatTimeRange(startTime, endTime) {
      // 处理空字符串和 null
      if (!startTime || startTime === '' || !endTime || endTime === '') return '';
      return `${startTime} 至 ${endTime}`;
    },

    parseTimeRange(timeRange) {
      if (!timeRange) return { start: '', end: '' };
      const parts = timeRange.split(' 至 ');
      return {
        start: parts[0] || '',
        end: parts[1] || ''
      };
    },

    // 准备提交数据：将前端格式转换为后端格式
    prepareSubmitData(formData) {
      // 从日期范围选择器获取开始和结束时间
      let registrationStartTime = '';
      let registrationEndTime = '';
      let competitionStartTime = '';
      let competitionEndTime = '';

      if (formData.registrationTimeRange && formData.registrationTimeRange.length === 2) {
        registrationStartTime = formData.registrationTimeRange[0];
        registrationEndTime = formData.registrationTimeRange[1];
      }

      if (formData.competitionTimeRange && formData.competitionTimeRange.length === 2) {
        competitionStartTime = formData.competitionTimeRange[0];
        competitionEndTime = formData.competitionTimeRange[1];
      }

      // 准备提交数据
      const submitData = {
        competitionName: formData.competitionName,
        competitionCode: formData.competitionCode || this.generateCompetitionCode(), // 自动生成编码
        organizer: formData.organizer,
        location: formData.location,
        venue: formData.venue,
        registrationStartTime,
        registrationEndTime,
        competitionStartTime,
        competitionEndTime,
        introduction: formData.introduction,
        contactPerson: formData.contactPerson,
        contactPhone: formData.contactPhone,
        contactEmail: formData.contactEmail,
        rules: formData.rules,
        requirements: formData.requirements,
        awards: formData.awards,
        posterImages: formData.posterImages || '[]',
        regulationFiles: formData.regulationFiles || '[]'
      };

      return submitData;
    },

    // 生成赛事编码
    generateCompetitionCode() {
      // 格式: WS + 年月日 + 4位随机数，例如: WS20251203A8F2
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const random = Math.random().toString(36).substring(2, 6).toUpperCase();
      return `WS${year}${month}${day}${random}`;
    },

    // 格式化后端数据：将后端格式转换为前端格式
    formatBackendData(data) {
      console.log('formatBackendData 输入数据:', data);

      // 构建时间范围数组
      const registrationTimeRange = [];
      if (data.registrationStartTime && data.registrationStartTime !== '' && data.registrationStartTime !== null) {
        registrationTimeRange.push(data.registrationStartTime);
      }
      if (data.registrationEndTime && data.registrationEndTime !== '' && data.registrationEndTime !== null) {
        registrationTimeRange.push(data.registrationEndTime);
      }

      const competitionTimeRange = [];
      if (data.competitionStartTime && data.competitionStartTime !== '' && data.competitionStartTime !== null) {
        competitionTimeRange.push(data.competitionStartTime);
      }
      if (data.competitionEndTime && data.competitionEndTime !== '' && data.competitionEndTime !== null) {
        competitionTimeRange.push(data.competitionEndTime);
      }

      console.log('registrationTimeRange:', registrationTimeRange);
      console.log('competitionTimeRange:', competitionTimeRange);

      const formatted = {
        ...data,
        registrationTime: this.formatTimeRange(data.registrationStartTime, data.registrationEndTime),
        registrationTimeRange: registrationTimeRange.length === 2 ? registrationTimeRange : [],
        competitionTime: this.formatTimeRange(data.competitionStartTime, data.competitionEndTime),
        competitionTimeRange: competitionTimeRange.length === 2 ? competitionTimeRange : [],
        status: this.calculateStatus(data), // 根据时间计算状态
        schedule: data.schedule || [], // 活动日程需要单独管理，暂时为空
        projects: data.projects || [], // 项目列表
        venues: data.venues || [] // 场地配置
      };

      console.log('formatBackendData 输出数据:', formatted);
      return formatted;
    },

    // 根据时间计算赛事状态
    calculateStatus(data) {
      const now = new Date();

      // 处理空字符串，转换为 null
      const regStart = data.registrationStartTime && data.registrationStartTime !== ''
        ? new Date(data.registrationStartTime) : null;
      const regEnd = data.registrationEndTime && data.registrationEndTime !== ''
        ? new Date(data.registrationEndTime) : null;
      const compStart = data.competitionStartTime && data.competitionStartTime !== ''
        ? new Date(data.competitionStartTime) : null;
      const compEnd = data.competitionEndTime && data.competitionEndTime !== ''
        ? new Date(data.competitionEndTime) : null;

      // 已结束
      if (compEnd && now > compEnd) {
        return 4;
      }
      // 进行中
      if (compStart && now >= compStart) {
        return 3;
      }
      // 报名中
      if (regStart && regEnd && now >= regStart && now <= regEnd) {
        return 2;
      }
      // 未开始（默认状态）
      return 1;
    },

    // 复制到剪贴板
    copyToClipboard(text, label) {
      if (!text) {
        this.$message.warning(`${label}为空`);
        return;
      }

      // 使用现代API复制
      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text).then(() => {
          this.$message.success(`${label}已复制: ${text}`);
        }).catch(() => {
          this.fallbackCopyToClipboard(text, label);
        });
      } else {
        this.fallbackCopyToClipboard(text, label);
      }
    },

    // 降级复制方法(兼容旧浏览器)
    fallbackCopyToClipboard(text, label) {
      const textArea = document.createElement('textarea');
      textArea.value = text;
      textArea.style.position = 'fixed';
      textArea.style.top = '-9999px';
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();

      try {
        document.execCommand('copy');
        this.$message.success(`${label}已复制: ${text}`);
      } catch (err) {
        this.$message.error('复制失败，请手动复制');
      }

      document.body.removeChild(textArea);
    }
  }
};
</script>

<style lang="scss" scoped>
.competition-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  min-height: calc(100vh - 120px);
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 2px solid #f0f0f0;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.data-table {
  :deep(.el-table__header) {
    th {
      background-color: #fafafa;
      color: #333;
      font-weight: 600;
    }
  }

  :deep(.el-button--text) {
    padding: 0 8px;
  }
}

.page-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #f0f0f0;

  .page-title {
    flex: 1;
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    color: #333;
  }

  .header-actions {
    display: flex;
    gap: 10px;
  }
}

.competition-form {
  max-width: 1200px;
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 600;
  color: #333;

  i {
    color: #dc2626;
    font-size: 18px;
  }
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

.button-right {
  :deep(.el-form-item__content) {
    justify-content: flex-end;
  }
}

:deep(.el-table) {
  .el-input {
    width: 100%;
  }
}

// 附件管理样式
.attachment-section {
  padding: 10px 0;
}

.attachment-upload {
  display: flex;
  align-items: center;
  gap: 15px;

  .upload-tip {
    font-size: 12px;
    color: #909399;
  }
}

.file-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;

  .file-icon {
    font-size: 18px;
    color: #409eff;
  }
}

.empty-attachment {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #909399;

  i {
    font-size: 48px;
    margin-bottom: 10px;
    opacity: 0.5;
  }

  p {
    margin: 0;
    font-size: 14px;
  }
}

:deep(.el-tabs__content) {
  padding: 10px 0;
}
</style>
