<template>
  <div class="competition-list">
    <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"
    >
      <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="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-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="900px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
      top="5vh"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        :disabled="dialogMode === '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="organizer">
                <el-input
                  v-model="formData.organizer"
                  placeholder="请输入主办单位"
                />
              </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="formData.location"
                  placeholder="请输入举办地点"
                />
              </el-form-item>
            </el-col>
            <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-input
                  v-model="formData.registrationTime"
                  placeholder="例如：2025-01-01 至 2025-02-28"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="比赛时间" prop="competitionTime">
                <el-input
                  v-model="formData.competitionTime"
                  placeholder="例如：2025-03-15 至 2025-03-20"
                />
              </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-date"></i>
            活动日程
          </div>

          <el-form-item label="">
            <el-button
              v-if="dialogMode !== '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="150"
            >
              <template #default="scope">
                <el-input
                  v-if="dialogMode !== 'view'"
                  v-model="scope.row.date"
                  placeholder="2025-03-15"
                  size="small"
                />
                <span v-else>{{ scope.row.date }}</span>
              </template>
            </el-table-column>

            <el-table-column
              label="时间"
              width="150"
            >
              <template #default="scope">
                <el-input
                  v-if="dialogMode !== 'view'"
                  v-model="scope.row.time"
                  placeholder="09:00-12:00"
                  size="small"
                />
                <span v-else>{{ scope.row.time }}</span>
              </template>
            </el-table-column>

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

            <el-table-column
              label="比赛场馆"
              width="150"
            >
              <template #default="scope">
                <el-input
                  v-if="dialogMode !== 'view'"
                  v-model="scope.row.venue"
                  placeholder="请输入场馆"
                  size="small"
                />
                <span v-else>{{ scope.row.venue }}</span>
              </template>
            </el-table-column>

            <el-table-column
              v-if="dialogMode !== '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> -->
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          v-if="dialogMode !== 'view'"
          type="primary"
          :loading="submitLoading"
          @click="handleSubmit"
        >
          确定
        </el-button>
        <el-button
          v-else
          type="primary"
          @click="switchToEdit"
        >
          编辑
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'CompetitionList',
  data() {
    return {
      competitionList: [
      ],
      dialogVisible: false,
      dialogMode: 'create', // create, edit, view
      submitLoading: false,
      currentCompetitionId: null,
      formData: {
        competitionName: '',
        organizer: '',
        location: '',
        venue: '',
        registrationTime: '',
        competitionTime: '',
        status: 1,
        introduction: '',
        contactPerson: '',
        contactPhone: '',
        contactEmail: '',
        rules: '',
        requirements: '',
        awards: '',
        schedule: []
      },
      formRules: {
        competitionName: [
          { required: true, message: '请输入赛事名称', trigger: 'blur' }
        ],
        organizer: [
          { required: true, message: '请输入主办单位', trigger: 'blur' }
        ],
        location: [
          { required: true, message: '请输入举办地点', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    dialogTitle() {
      const titleMap = {
        create: '新建赛事',
        edit: '编辑赛事',
        view: '查看赛事'
      };
      return titleMap[this.dialogMode] || '赛事信息';
    }
  },
  mounted() {
    this.loadCompetitionList();
  },
  methods: {
    loadCompetitionList() {
      // 从 localStorage 加载数据
      const savedData = localStorage.getItem('competitionList');
      if (savedData) {
        try {
          this.competitionList = JSON.parse(savedData);
        } catch (e) {
          console.error('加载数据失败', e);
        }
      } else {
        // 首次加载，保存默认数据
        this.saveCompetitionList();
      }
    },

    saveCompetitionList() {
      localStorage.setItem('competitionList', JSON.stringify(this.competitionList));
    },

    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.dialogMode = 'create';
      this.currentCompetitionId = null;
      this.resetFormData();
      this.dialogVisible = true;
    },

    handleView(row) {
      this.dialogMode = 'view';
      this.currentCompetitionId = row.id;
      this.formData = { ...row };
      this.dialogVisible = true;
    },

    handleEdit(row) {
      this.dialogMode = 'edit';
      this.currentCompetitionId = row.id;
      this.formData = { ...row };
      this.dialogVisible = true;
    },

    switchToEdit() {
      this.dialogMode = 'edit';
    },

    handleDelete(row) {
      this.$confirm('确定要删除该赛事吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.competitionList.findIndex(item => item.id === row.id);
        if (index !== -1) {
          this.competitionList.splice(index, 1);
          this.saveCompetitionList();
          this.$message.success('删除成功');
        }
      }).catch(() => {});
    },

    handleAddSchedule() {
      this.formData.schedule.push({
        date: '',
        time: '',
        event: '',
        venue: ''
      });
    },

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

    handleSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.submitLoading = true;

          setTimeout(() => {
            if (this.dialogMode === 'create') {
              // 新建
              const newId = this.competitionList.length > 0
                ? Math.max(...this.competitionList.map(item => item.id)) + 1
                : 1;
              const newCompetition = {
                ...this.formData,
                id: newId,
                posterImages: [],
                regulationFiles: []
              };
              this.competitionList.push(newCompetition);
              this.$message.success('创建成功');
            } else if (this.dialogMode === 'edit') {
              // 编辑
              const index = this.competitionList.findIndex(item => item.id === this.currentCompetitionId);
              if (index !== -1) {
                this.competitionList[index] = {
                  ...this.competitionList[index],
                  ...this.formData
                };
                this.$message.success('保存成功');
              }
            }

            this.saveCompetitionList();
            this.dialogVisible = false;
            this.submitLoading = false;
          }, 500);
        } else {
          this.$message.error('请完善必填信息');
        }
      });
    },

    handleDialogClose() {
      this.$refs.formRef.resetFields();
      this.resetFormData();
    },

    resetFormData() {
      this.formData = {
        competitionName: '',
        organizer: '',
        location: '',
        venue: '',
        registrationTime: '',
        competitionTime: '',
        status: 1,
        introduction: '',
        contactPerson: '',
        contactPhone: '',
        contactEmail: '',
        rules: '',
        requirements: '',
        awards: '',
        schedule: []
      };
    }
  }
};
</script>

<style lang="scss" scoped>
.competition-list {
  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;
  }
}

.competition-form {
  max-height: 60vh;
  overflow-y: auto;
}

.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;
}

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

.dialog-footer {
  text-align: right;
}
</style>
