<template>
  <div class="competition-create-container">
    <el-card shadow="hover">
      <div class="page-header">
        <el-button icon="el-icon-back" size="small" @click="goBack">返回</el-button>
        <h2 class="page-title">新建赛事</h2>
      </div>

      <el-steps :active="currentStep" align-center class="steps-container" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="信息发布"></el-step>
        <el-step title="赛事规程"></el-step>
        <el-step title="活动日程"></el-step>
      </el-steps>

      <el-form ref="competitionForm" :model="formData" :rules="rules" label-width="120px" class="form-container">
        <!-- Step 1: 基本信息 -->
        <div v-show="currentStep === 0" class="form-step">
          <h3 class="step-title">赛事基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="赛事名称" prop="competitionName">
                <el-input v-model="formData.competitionName" placeholder="请输入赛事名称" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="主办单位" prop="organizer">
                <el-input v-model="formData.organizer" placeholder="请输入主办单位" clearable></el-input>
              </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="例如：四川省 成都市" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="详细地点" prop="venue">
                <el-input v-model="formData.venue" placeholder="请输入详细地点" clearable></el-input>
              </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.registrationTime"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="比赛时间" prop="competitionTime">
                <el-date-picker
                  v-model="formData.competitionTime"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- Step 2: 信息发布 -->
        <div v-show="currentStep === 1" class="form-step">
          <h3 class="step-title">信息发布</h3>

          <el-form-item label="赛事简介" prop="introduction">
            <el-input
              v-model="formData.introduction"
              type="textarea"
              :rows="8"
              placeholder="请输入赛事简介，支持详细描述赛事背景、特色等信息"
            ></el-input>
          </el-form-item>

          <el-form-item label="宣传图片" prop="posterImages">
            <el-upload
              class="upload-demo"
              action="#"
              :auto-upload="false"
              :on-change="handlePosterChange"
              :on-remove="handlePosterRemove"
              :file-list="posterFileList"
              list-type="picture-card"
              accept="image/*"
            >
              <i class="el-icon-plus"></i>
              <div slot="tip" class="el-upload__tip">建议上传jpg/png文件，且不超过2MB</div>
            </el-upload>
          </el-form-item>

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

        <!-- Step 3: 赛事规程 -->
        <div v-show="currentStep === 2" class="form-step">
          <h3 class="step-title">赛事规程</h3>

          <el-form-item label="竞赛规则" prop="rules">
            <el-input
              v-model="formData.rules"
              type="textarea"
              :rows="6"
              placeholder="请输入竞赛规则，包括比赛项目、评分标准等"
            ></el-input>
          </el-form-item>

          <el-form-item label="参赛要求" prop="requirements">
            <el-input
              v-model="formData.requirements"
              type="textarea"
              :rows="4"
              placeholder="请输入参赛要求，如年龄限制、资格要求等"
            ></el-input>
          </el-form-item>

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

          <el-form-item label="规程文件" prop="regulationFiles">
            <el-upload
              class="upload-demo"
              action="#"
              :auto-upload="false"
              :on-change="handleRegulationChange"
              :on-remove="handleRegulationRemove"
              :file-list="regulationFileList"
              accept=".pdf,.doc,.docx"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">支持上传PDF、Word文件，单个文件不超过10MB</div>
            </el-upload>
          </el-form-item>
        </div>

        <!-- Step 4: 活动日程 -->
        <div v-show="currentStep === 3" class="form-step">
          <h3 class="step-title">活动日程</h3>

          <div class="schedule-header">
            <el-button type="primary" size="small" icon="el-icon-plus" @click="addScheduleItem">添加日程</el-button>
          </div>

          <el-table :data="formData.schedule" border stripe size="small" class="schedule-table">
            <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
            <el-table-column label="日期时间" min-width="200">
              <template #default="scope">
                <el-date-picker
                  v-model="scope.row.date"
                  type="datetime"
                  placeholder="选择日期时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  size="small"
                  style="width: 100%"
                ></el-date-picker>
              </template>
            </el-table-column>
            <el-table-column label="活动项目" min-width="150">
              <template #default="scope">
                <el-input v-model="scope.row.eventName" placeholder="请输入活动项目" size="small"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="地点" min-width="150">
              <template #default="scope">
                <el-input v-model="scope.row.venue" placeholder="请输入地点" size="small"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="备注" min-width="150">
              <template #default="scope">
                <el-input v-model="scope.row.remark" placeholder="请输入备注" size="small"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center" fixed="right">
              <template #default="scope">
                <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteScheduleItem(scope.$index)" circle></el-button>
              </template>
            </el-table-column>
          </el-table>

          <div v-if="formData.schedule.length === 0" class="empty-schedule">
            <i class="el-icon-calendar"></i>
            <p>暂无日程安排，点击上方"添加日程"按钮开始添加</p>
          </div>
        </div>
      </el-form>

      <!-- 底部操作按钮 -->
      <div class="form-footer">
        <el-button v-if="currentStep > 0" @click="prevStep">上一步</el-button>
        <el-button v-if="currentStep < 3" type="primary" @click="nextStep">下一步</el-button>
        <el-button v-if="currentStep === 3" type="success" :loading="submitLoading" @click="handleSubmit">提交</el-button>
        <el-button @click="goBack">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { addCompetition } from '@/api/martial/competition'

export default {
  name: 'CompetitionCreate',
  data() {
    return {
      currentStep: 0,
      submitLoading: false,
      posterFileList: [],
      regulationFileList: [],
      formData: {
        // 基本信息
        competitionName: '',
        organizer: '',
        location: '',
        venue: '',
        registrationTime: [],
        competitionTime: [],

        // 信息发布
        introduction: '',
        posterImages: [],
        contactPerson: '',
        contactPhone: '',
        contactEmail: '',

        // 赛事规程
        rules: '',
        requirements: '',
        awards: '',
        regulationFiles: [],

        // 活动日程
        schedule: []
      },
      rules: {
        competitionName: [
          { required: true, message: '请输入赛事名称', trigger: 'blur' }
        ],
        organizer: [
          { required: true, message: '请输入主办单位', trigger: 'blur' }
        ],
        location: [
          { required: true, message: '请输入地区', trigger: 'blur' }
        ],
        venue: [
          { required: true, message: '请输入详细地点', trigger: 'blur' }
        ],
        registrationTime: [
          { required: true, message: '请选择报名时间', trigger: 'change' }
        ],
        competitionTime: [
          { required: true, message: '请选择比赛时间', trigger: 'change' }
        ],
        contactPhone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        contactEmail: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 上一步
    prevStep() {
      if (this.currentStep > 0) {
        this.currentStep--
      }
    },

    // 下一步
    nextStep() {
      // 验证当前步骤的表单
      this.$refs.competitionForm.validateField(this.getStepFields(this.currentStep), (valid) => {
        if (!valid) {
          this.currentStep++
        }
      })
    },

    // 获取每个步骤需要验证的字段
    getStepFields(step) {
      const fieldsMap = {
        0: ['competitionName', 'organizer', 'location', 'venue', 'registrationTime', 'competitionTime'],
        1: ['contactPhone', 'contactEmail'],
        2: [],
        3: []
      }
      return fieldsMap[step] || []
    },

    // 返回
    goBack() {
      this.$router.go(-1)
    },

    // 添加日程项
    addScheduleItem() {
      this.formData.schedule.push({
        date: '',
        eventName: '',
        venue: '',
        remark: ''
      })
    },

    // 删除日程项
    deleteScheduleItem(index) {
      this.$confirm('确定删除该日程吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formData.schedule.splice(index, 1)
        this.$message.success('删除成功')
      }).catch(() => {})
    },

    // 处理宣传图片上传
    handlePosterChange(file, fileList) {
      this.posterFileList = fileList
      this.formData.posterImages = fileList.map(f => f.raw || f)
    },

    // 处理宣传图片删除
    handlePosterRemove(file, fileList) {
      this.posterFileList = fileList
      this.formData.posterImages = fileList.map(f => f.raw || f)
    },

    // 处理规程文件上传
    handleRegulationChange(file, fileList) {
      this.regulationFileList = fileList
      this.formData.regulationFiles = fileList.map(f => f.raw || f)
    },

    // 处理规程文件删除
    handleRegulationRemove(file, fileList) {
      this.regulationFileList = fileList
      this.formData.regulationFiles = fileList.map(f => f.raw || f)
    },

    // 提交表单
    handleSubmit() {
      this.$refs.competitionForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true

          // 构建提交数据
          const submitData = {
            ...this.formData,
            registrationStartTime: this.formData.registrationTime[0],
            registrationEndTime: this.formData.registrationTime[1],
            competitionStartTime: this.formData.competitionTime[0],
            competitionEndTime: this.formData.competitionTime[1]
          }

          // 删除临时字段
          delete submitData.registrationTime
          delete submitData.competitionTime

          // 调用API
          addCompetition(submitData).then(res => {
            this.$message.success('赛事创建成功')
            this.$router.push('/martial/order/list')
          }).catch(err => {
            this.$message.error(err.message || '创建失败')
          }).finally(() => {
            this.submitLoading = false
          })
        } else {
          this.$message.warning('请完善必填信息')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.competition-create-container {
  min-height: 100%;
  padding: 15px;

  .page-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    gap: 10px;

    .page-title {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #2c3e50;
    }
  }

  .steps-container {
    margin-bottom: 30px;
    padding: 20px 0;
  }

  .form-container {
    min-height: 400px;
    padding: 20px;
    background: #f5f7fa;
    border-radius: 4px;

    .form-step {
      .step-title {
        margin-bottom: 20px;
        padding-left: 12px;
        font-size: 16px;
        font-weight: 600;
        color: #409eff;
        border-left: 4px solid #409eff;
      }
    }
  }

  .upload-demo {
    width: 100%;
  }

  .schedule-header {
    margin-bottom: 15px;
  }

  .schedule-table {
    margin-top: 15px;
  }

  .empty-schedule {
    padding: 60px 0;
    text-align: center;
    color: #909399;

    i {
      font-size: 64px;
      margin-bottom: 15px;
      opacity: 0.3;
    }

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

  .form-footer {
    margin-top: 30px;
    padding-top: 20px;
    text-align: center;
    border-top: 1px solid #dcdfe6;

    .el-button {
      min-width: 100px;
    }
  }
}
</style>
