<template>
  <div class="participant-manage">
    <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="participant-form"
    >
      <!-- 基本信息 -->
      <div class="form-section">
        <div class="section-title">
          <i class="el-icon-user"></i>
          基本信息
        </div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="选手姓名" prop="playerName">
              <el-input
                v-model="formData.playerName"
                placeholder="请输入选手姓名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="formData.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年龄" prop="age">
              <el-input-number
                v-model="formData.age"
                :min="6"
                :max="100"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input
                v-model="formData.idCard"
                placeholder="请输入身份证号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input
                v-model="formData.contactPhone"
                placeholder="请输入联系电话"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="所属单位" prop="organization">
          <el-input
            v-model="formData.organization"
            placeholder="请输入所属单位"
          />
        </el-form-item>
      </div>

      <!-- 赛事信息 -->
      <div class="form-section">
        <div class="section-title">
          <i class="el-icon-trophy"></i>
          赛事信息
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属赛事" prop="competitionId">
              <el-select
                v-model="formData.competitionId"
                placeholder="请选择赛事"
                style="width: 100%"
                @change="handleCompetitionChange"
              >
                <el-option
                  v-for="item in competitionOptions"
                  :key="item.id"
                  :label="item.competitionName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="参赛项目" prop="projectName">
              <el-input
                v-model="formData.projectName"
                placeholder="请输入参赛项目"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="组别" prop="category">
              <el-input
                v-model="formData.category"
                placeholder="例如：成年男子组"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出场顺序" prop="orderNum">
              <el-input-number
                v-model="formData.orderNum"
                :min="1"
                :max="9999"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 其他信息 -->
      <div class="form-section">
        <div class="section-title">
          <i class="el-icon-document"></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-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'ParticipantManage',
  data() {
    return {
      mode: 'create', // create, edit, view
      participantId: null,
      competitionOptions: [],
      formData: {
        competitionId: null,
        competitionName: '',
        playerName: '',
        gender: 1,
        age: null,
        contactPhone: '',
        organization: '',
        idCard: '',
        projectName: '',
        category: '',
        orderNum: 1,
        introduction: '',
        remark: '',
        attachments: []
      },
      formRules: {
        playerName: [
          { required: true, message: '请输入选手姓名', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        competitionId: [
          { required: true, message: '请选择赛事', trigger: 'change' }
        ],
        projectName: [
          { 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.participantId = id ? parseInt(id) : null;

      // 加载赛事选项
      this.loadCompetitionOptions();

      if (this.mode !== 'create' && this.participantId) {
        this.loadParticipantData();
      }
    },

    loadCompetitionOptions() {
      const savedData = localStorage.getItem('competitionList');
      if (savedData) {
        try {
          this.competitionOptions = JSON.parse(savedData);
        } catch (e) {
          console.error('加载赛事数据失败', e);
        }
      }
    },

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

    handleCompetitionChange(competitionId) {
      const competition = this.competitionOptions.find(item => item.id === competitionId);
      if (competition) {
        this.formData.competitionName = competition.competitionName;
      }
    },

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

          // 确保有赛事名称
          if (!this.formData.competitionName) {
            const competition = this.competitionOptions.find(item => item.id === this.formData.competitionId);
            if (competition) {
              this.formData.competitionName = competition.competitionName;
            }
          }

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

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

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

    switchToEdit() {
      this.$router.push({
        path: '/martial/participant/manage',
        query: { mode: 'edit', id: this.participantId }
      });
    },

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

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

.participant-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;
}
</style>
