<template>
  <div class="competition-create">
    <div class="page-header">
      <el-button
        icon="el-icon-arrow-left"
        @click="handleBack"
      >
        返回列表
      </el-button>
      <h2 class="page-title">{{ pageTitle }}</h2>
      <div class="header-actions" v-if="mode !== 'view'">
        <el-button @click="handleBack">取消</el-button>
        <el-button type="primary" @click="handleSave">
          {{ mode === '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="mode === '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="mode !== '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="mode !== '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="mode !== '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="mode !== '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="mode !== '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="mode !== '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>
</template>

<script>
export default {
  name: 'CompetitionCreate',
  data() {
    return {
      mode: 'create', // create, edit, view
      competitionId: 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: {
    pageTitle() {
      const titleMap = {
        create: '新建赛事',
        edit: '编辑赛事',
        view: '查看赛事'
      };
      return titleMap[this.mode] || '赛事信息';
    }
  },
  created() {
    this.initPage();
  },
  methods: {
    initPage() {
      const { mode, id } = this.$route.query;
      this.mode = mode || 'create';
      this.competitionId = id ? parseInt(id) : null;

      if (this.mode !== 'create' && this.competitionId) {
        this.loadCompetitionData();
      }
    },

    loadCompetitionData() {
      // 从 localStorage 加载数据
      const savedData = localStorage.getItem('competitionList');
      if (savedData) {
        try {
          const list = JSON.parse(savedData);
          const competition = list.find(item => item.id === this.competitionId);
          if (competition) {
            this.formData = { ...competition };
          }
        } catch (e) {
          console.error('加载数据失败', e);
          this.$message.error('加载数据失败');
        }
      }
    },

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

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

    handleSave() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const savedData = localStorage.getItem('competitionList');
          let list = savedData ? JSON.parse(savedData) : [];

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

          localStorage.setItem('competitionList', JSON.stringify(list));

          // 返回列表页
          setTimeout(() => {
            this.handleBack();
          }, 500);
        } else {
          this.$message.error('请完善必填信息');
        }
      });
    },

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

    handleBack() {
      this.$router.push('/martial/competition/list');
    }
  }
};
</script>

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

.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: 40px;
  padding: 24px;
  background: #fafafa;
  border-radius: 8px;

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

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

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

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

:deep(.el-table) {
  .el-input {
    width: 100%;
  }
}
</style>
