<template>
  <div class="game-event-athlete">
    <el-card shadow="never">
      <template #header>
        <div class="page-header">
          <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
          <span class="page-title">参赛者信息</span>
        </div>
      </template>

      <el-form ref="athleteFormRef" :model="athleteForm" :rules="athleteRules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="赛事" prop="eventName">
              <el-input v-model="athleteForm.eventName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="athleteForm.unit" placeholder="输入单位" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="athleteForm.name" placeholder="输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="编号" prop="athleteCode">
              <el-input v-model="athleteForm.athleteCode" placeholder="输入号码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="athleteForm.age" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="athleteForm.gender">
                <el-radio value="0">男</el-radio>
                <el-radio value="1">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="赛事项目" prop="projectValue">
              <el-transfer
                v-model="athleteForm.projectValue"
                :data="allProjects"
                :titles="['可选项目', '已选项目']"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup name="GameEventAthlete" lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { listGameEventProject } from '@/api/system/gameEventProject';
import { addGameAthlete } from '@/api/system/gameAthlete';
import { GameAthleteForm } from '@/api/system/gameAthlete/types';

const router = useRouter();
const route = useRoute();

const athleteFormRef = ref<any>(null);

const athleteForm = reactive({
  eventId: route.params.eventId as string,
  eventName: '',
  name: '',
  athleteCode: '',
  unit: '',
  age: 0,
  gender: '',
  projectValue: [] as string[]  // 确保初始化为数组
});

const athleteRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  athleteCode: [
    { required: true, message: '请输入号码', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' }
  ]
};

const allProjects = ref<{ key: string; label: string }[]>([]);

onMounted(async () => {
  const eventName = route.params.eventName as string;
  athleteForm.eventName = eventName;

  // 加载赛事项目数据
  await loadProjects();
});

const loadProjects = async () => {
  // console.log(route.params.eventId);
  const res = await listGameEventProject({ 
    eventId: route.params.eventId as string,
    pageNum: 1,
    pageSize: 100
  });
  allProjects.value = res.rows.map(item => ({
    key: String(item.projectId),
    label: `${item.projectName}`
  }));
};

const goBack = () => {
  router.go(-1);
};

const submitForm = () => {
  athleteFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 准备提交的数据
      let projectValue = athleteForm.projectValue;
      // if (!Array.isArray(projectValue)) {  // 检查 projectValue 是否为数组
      //   projectValue = [];
      // }
      const submitData: GameAthleteForm = {
        eventId: route.params.eventId as string,
        name: athleteForm.name,
        unit: athleteForm.unit,
        athleteCode: athleteForm.athleteCode,
        age: athleteForm.age,
        gender: athleteForm.gender,
        projectValue: `${projectValue.join(',')}`,  // 安全地进行 join 操作
      };
      console.log(athleteForm.projectValue);
      try {
        // 保存数据到game_athlete表
        await addGameAthlete(submitData);
        ElMessage.success('提交成功');
        goBack();
      } catch (error) {
        ElMessage.error('提交失败');
        console.error('提交失败:', error);
      }
    }
  });
};
</script>

<style scoped lang="scss">
.game-event-athlete {
  .page-header {
    display: flex;
    align-items: center;
    .page-title {
      margin-left: 10px;
      font-size: 16px;
    }
  }
}
</style>