<template>
  <div class="participant-list">
    <div class="list-header">
      <h2 class="page-title">参赛选手管理</h2>
      <el-button type="primary" icon="el-icon-plus" @click="handleCreate">
        添加选手
      </el-button>
    </div>

    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item>
        <el-input
          v-model="searchForm.keyword"
          placeholder="搜索选手姓名"
          clearable
          size="small"
          style="width: 240px"
        >
          <template #prefix>
            <i class="el-input__icon el-icon-search"></i>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchForm.competitionId" placeholder="选择赛事" clearable size="small" style="width: 200px">
          <el-option label="全部赛事" :value="null" />
          <el-option
            v-for="item in allCompetitionOptions"
            :key="item.id"
            :label="item.competitionName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleSearch">查询</el-button>
        <el-button size="small" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="displayList"
      border
      stripe
      style="width: 100%"
      class="data-table"
    >
      <el-table-column
        type="index"
        label="序号"
        width="60"
        align="center"
      />

      <el-table-column
        prop="playerName"
        label="选手姓名"
        width="120"
      />

      <el-table-column
        prop="competitionName"
        label="所属赛事"
        min-width="180"
        show-overflow-tooltip
      />

      <el-table-column
        prop="projectName"
        label="参赛项目"
        width="120"
      />

      <el-table-column
        prop="category"
        label="组别"
        width="100"
      />

      <el-table-column
        label="性别"
        width="80"
        align="center"
      >
        <template #default="scope">
          <el-tag :type="scope.row.gender === 1 ? 'primary' : 'danger'" size="small">
            {{ scope.row.gender === 1 ? '男' : '女' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="age"
        label="年龄"
        width="80"
        align="center"
      />

      <el-table-column
        prop="organization"
        label="所属单位"
        min-width="150"
        show-overflow-tooltip
      />

      <el-table-column
        prop="contactPhone"
        label="联系电话"
        width="120"
      />

      <el-table-column
        prop="orderNum"
        label="出场顺序"
        width="100"
        align="center"
      />

      <el-table-column
        label="操作"
        width="180"
        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-pagination
      v-if="pagination.total > 0"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
      :current-page="pagination.current"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pagination.size"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper"
      style="margin-top: 20px; text-align: right"
    />

    <!-- 新增/编辑/查看弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
      top="5vh"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        :disabled="dialogMode === '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="projectId">
                <el-select
                  v-model="formData.projectId"
                  placeholder="请选择参赛项目"
                  style="width: 100%"
                  @change="handleProjectChange"
                >
                  <el-option
                    v-for="item in projectOptions"
                    :key="item.id"
                    :label="item.projectName"
                    :value="item.id"
                  />
                </el-select>
              </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>

      <template #footer>
        <div 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>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getCompetitionList } from '@/api/martial/competition'
import { getInfoPublishList } from '@/api/martial/infoPublish'
import { getProjectsByCompetition } from '@/api/martial/project'
import {
  getParticipantList,
  getParticipantDetail,
  addParticipant,
  updateParticipant,
  removeParticipant
} from '@/api/martial/participant'

export default {
  name: 'ParticipantList',
  data() {
    return {
      loading: false,
      searchForm: {
        keyword: '',
        competitionId: null
      },
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      competitionOptions: [], // 可报名的赛事列表
      allCompetitionOptions: [], // 所有赛事列表（用于搜索过滤）
      projectOptions: [], // 项目列表
      participantList: [],
      dialogVisible: false,
      dialogMode: 'create', // create, edit, view
      submitLoading: false,
      currentParticipantId: null,
      formData: {
        competitionId: null,
        competitionName: '',
        playerName: '',
        gender: 1,
        age: null,
        contactPhone: '',
        organization: '',
        idCard: '',
        projectId: null,
        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' }
        ],
        projectId: [
          { required: true, message: '请选择参赛项目', trigger: 'change' }
        ]
      }
    };
  },
  computed: {
    dialogTitle() {
      const titleMap = {
        create: '添加参赛选手',
        edit: '编辑参赛选手',
        view: '查看参赛选手'
      };
      return titleMap[this.dialogMode] || '参赛选手信息';
    },
    displayList() {
      return this.participantList;
    }
  },
  mounted() {
    this.loadAvailableCompetitions();
    this.loadAllCompetitions();
  },
  methods: {
    // 加载可报名的赛事（从已发布的信息中获取）
    loadAvailableCompetitions() {
      // 获取已发布的赛事信息（publishStatus = 1 表示已发布）
      getInfoPublishList(1, 100, { publishStatus: 1 })
        .then(res => {
          console.log('已发布信息列表返回数据:', res);
          const responseData = res.data?.data;
          if (responseData && responseData.records) {
            const now = new Date();

            // 从已发布的信息中提取赛事ID
            const publishedCompetitionIds = new Set(
              responseData.records
                .filter(item => item.competitionId)
                .map(item => item.competitionId)
            );

            console.log('已发布的赛事ID列表:', Array.from(publishedCompetitionIds));

            // 如果有已发布的赛事，加载这些赛事的详细信息
            if (publishedCompetitionIds.size > 0) {
              this.loadPublishedCompetitions(Array.from(publishedCompetitionIds));
            } else {
              this.$message.warning('当前没有已发布的赛事');
              this.competitionOptions = [];
            }
          }
        })
        .catch(err => {
          console.error('加载已发布信息列表失败', err);
          this.$message.error('加载已发布信息列表失败');
        });
    },

    // 加载已发布的赛事详细信息，并过滤出可报名的赛事
    loadPublishedCompetitions(competitionIds) {
      getCompetitionList(1, 100, {})
        .then(res => {
          console.log('赛事列表返回数据:', res);
          const responseData = res.data?.data;
          if (responseData && responseData.records) {
            const now = new Date();

            // 筛选出已发布且可以报名的赛事
            this.competitionOptions = responseData.records
              .filter(item => {
                // 必须是已发布的赛事
                if (!competitionIds.includes(item.id)) {
                  return false;
                }

                // 检查报名开始时间和结束时间
                if (!item.registrationStartTime || !item.registrationEndTime) {
                  return false;
                }

                const regStart = new Date(item.registrationStartTime);
                const regEnd = new Date(item.registrationEndTime);

                // 当前时间在报名时间段内
                return now >= regStart && now <= regEnd;
              })
              .map(item => ({
                id: item.id,
                competitionName: item.competitionName,
                registrationStartTime: item.registrationStartTime,
                registrationEndTime: item.registrationEndTime
              }));

            console.log('可报名的已发布赛事列表:', this.competitionOptions);

            if (this.competitionOptions.length === 0) {
              this.$message.warning('当前没有可以报名的赛事');
            }
          }
        })
        .catch(err => {
          console.error('加载赛事列表失败', err);
          this.$message.error('加载赛事列表失败');
        });
    },

    // 加载所有赛事（用于搜索过滤）
    loadAllCompetitions() {
      getCompetitionList(1, 100, {})
        .then(res => {
          const responseData = res.data?.data;
          if (responseData && responseData.records) {
            this.allCompetitionOptions = responseData.records.map(item => ({
              id: item.id,
              competitionName: item.competitionName
            }));
          }
        })
        .catch(err => {
          console.error('加载所有赛事失败', err);
        });
    },

    // 编辑时加载所有赛事到下拉框
    loadAllCompetitionsForEdit() {
      return getCompetitionList(1, 100, {})
        .then(res => {
          const responseData = res.data?.data;
          if (responseData && responseData.records) {
            // 编辑模式下，competitionOptions 应该包含所有赛事
            this.competitionOptions = responseData.records.map(item => ({
              id: item.id,
              competitionName: item.competitionName,
              registrationStartTime: item.registrationStartTime,
              registrationEndTime: item.registrationEndTime
            }));
            console.log('编辑模式 - 所有赛事列表:', this.competitionOptions);
          }
        })
        .catch(err => {
          console.error('加载所有赛事失败', err);
          this.$message.error('加载所有赛事失败');
          throw err;
        });
    },

    loadParticipantList() {
      this.loading = true;
      const params = {};

      if (this.searchForm.keyword) {
        params.playerName = this.searchForm.keyword;
      }

      if (this.searchForm.competitionId) {
        params.competitionId = this.searchForm.competitionId;
      }

      getParticipantList(null, this.pagination.current, this.pagination.size, params)
        .then(res => {
          console.log('参赛人员列表返回数据:', res);
          const responseData = res.data?.data;
          if (responseData && responseData.records) {
            this.participantList = responseData.records;
            this.pagination.total = responseData.total || 0;
          }
        })
        .catch(err => {
          console.error('加载参赛人员列表失败', err);
          this.$message.error('加载参赛人员列表失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },

    handlePageChange(current) {
      this.pagination.current = current;
      this.loadParticipantList();
    },

    handleSizeChange(size) {
      this.pagination.size = size;
      this.pagination.current = 1;
      this.loadParticipantList();
    },

    handleSearch() {
      this.pagination.current = 1;
      this.loadParticipantList();
    },

    handleReset() {
      this.searchForm = {
        keyword: '',
        competitionId: null
      };
      this.pagination.current = 1;
      this.loadParticipantList();
    },

    handleCreate() {
      this.dialogMode = 'create';
      this.currentParticipantId = null;
      this.resetFormData();
      // 新建模式：重新加载可报名的赛事
      this.loadAvailableCompetitions();
      this.dialogVisible = true;
    },

    handleView(row) {
      this.dialogMode = 'view';
      this.currentParticipantId = row.id;
      this.loading = true;

      // 先加载所有赛事
      this.loadAllCompetitionsForEdit().then(() => {
        // 赛事加载完成后，再加载参赛人员详情
        return getParticipantDetail(row.id);
      }).then(res => {
        const detailData = res.data?.data;
        console.log('查看模式 - 参赛人员详情数据:', detailData);

        if (detailData) {
          // 确保 ID 字段是数字类型
          this.formData = {
            ...detailData,
            competitionId: detailData.competitionId ? Number(detailData.competitionId) : null,
            projectId: detailData.projectId ? Number(detailData.projectId) : null,
            gender: detailData.gender ? Number(detailData.gender) : 1,
            age: detailData.age ? Number(detailData.age) : null,
            orderNum: detailData.orderNum ? Number(detailData.orderNum) : 1
          };

          // 加载该赛事的项目列表（即使是查看模式也需要显示项目名称）
          if (this.formData.competitionId) {
            return this.loadProjectsByCompetition(this.formData.competitionId);
          }
        }
      }).then(() => {
        this.dialogVisible = true;
        this.loading = false;
      }).catch(err => {
        console.error('加载失败', err);
        this.$message.error('加载参赛人员详情失败');
        this.loading = false;
      });
    },

    handleEdit(row) {
      this.dialogMode = 'edit';
      this.currentParticipantId = row.id;
      this.loading = true;

      // 先加载所有赛事
      this.loadAllCompetitionsForEdit().then(() => {
        // 赛事加载完成后，再加载参赛人员详情
        return getParticipantDetail(row.id);
      }).then(res => {
        const detailData = res.data?.data;
        console.log('参赛人员详情数据:', detailData);

        if (detailData) {
          // 确保 ID 字段是数字类型
          this.formData = {
            ...detailData,
            competitionId: detailData.competitionId ? Number(detailData.competitionId) : null,
            projectId: detailData.projectId ? Number(detailData.projectId) : null,
            gender: detailData.gender ? Number(detailData.gender) : 1,
            age: detailData.age ? Number(detailData.age) : null,
            orderNum: detailData.orderNum ? Number(detailData.orderNum) : 1
          };
          console.log('转换后的 formData.competitionId:', this.formData.competitionId);
          console.log('转换后的 formData.projectId:', this.formData.projectId);

          // 加载该赛事的项目列表
          if (this.formData.competitionId) {
            return this.loadProjectsByCompetition(this.formData.competitionId);
          }
        }
      }).then(() => {
        console.log('当前 competitionOptions:', this.competitionOptions);
        console.log('当前 projectOptions:', this.projectOptions);
        this.dialogVisible = true;
        this.loading = false;
      }).catch(err => {
        console.error('加载失败', err);
        this.$message.error('加载参赛人员详情失败');
        this.loading = false;
      });
    },

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

    handleDelete(row) {
      this.$confirm('确定要删除该选手吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        removeParticipant(row.id.toString())
          .then(res => {
            this.$message.success('删除成功');
            this.loadParticipantList();
          })
          .catch(err => {
            console.error('删除失败', err);
            this.$message.error('删除失败');
          })
          .finally(() => {
            this.loading = false;
          });
      }).catch(() => {});
    },

    handleCompetitionChange(competitionId) {
      const competition = this.competitionOptions.find(item => item.id === competitionId);
      if (competition) {
        this.formData.competitionName = competition.competitionName;
      }
      // 加载该赛事的项目列表
      this.loadProjectsByCompetition(competitionId);
      // 清空已选项目
      this.formData.projectId = null;
    },

    handleProjectChange(projectId) {
      const project = this.projectOptions.find(item => item.id === projectId);
      if (project) {
        // 自动填充组别信息
        if (project.category && !this.formData.category) {
          this.formData.category = project.category;
        }
      }
    },

    loadProjectsByCompetition(competitionId) {
      if (!competitionId) {
        this.projectOptions = [];
        return Promise.resolve();
      }

      return getProjectsByCompetition(competitionId)
        .then(res => {
          console.log('项目列表返回数据:', res);
          const responseData = res.data?.data;
          if (responseData && responseData.records) {
            this.projectOptions = responseData.records.map(item => ({
              id: item.id,
              projectName: item.projectName,
              projectCode: item.projectCode,
              category: item.category
            }));
            console.log('可选项目列表:', this.projectOptions);
          }
        })
        .catch(err => {
          console.error('加载项目列表失败', err);
          this.$message.error('加载项目列表失败');
          throw err;
        });
    },

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

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

          const submitData = { ...this.formData };

          if (this.dialogMode === 'create') {
            // 新建
            addParticipant(submitData)
              .then(res => {
                this.$message.success('添加成功');
                this.dialogVisible = false;
                this.loadParticipantList();
              })
              .catch(err => {
                console.error('添加失败', err);
                this.$message.error('添加失败');
              })
              .finally(() => {
                this.submitLoading = false;
              });
          } else if (this.dialogMode === 'edit') {
            // 编辑
            submitData.id = this.currentParticipantId;
            updateParticipant(submitData)
              .then(res => {
                this.$message.success('保存成功');
                this.dialogVisible = false;
                this.loadParticipantList();
              })
              .catch(err => {
                console.error('保存失败', err);
                this.$message.error('保存失败');
              })
              .finally(() => {
                this.submitLoading = false;
              });
          }
        } else {
          this.$message.error('请完善必填信息');
        }
      });
    },

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

    resetFormData() {
      this.formData = {
        competitionId: null,
        competitionName: '',
        playerName: '',
        gender: 1,
        age: null,
        contactPhone: '',
        organization: '',
        idCard: '',
        projectId: null,
        category: '',
        orderNum: 1,
        introduction: '',
        remark: '',
        attachments: []
      };
    }
  }
};
</script>

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

.search-form {
  margin-bottom: 20px;
}

.data-table {
  :deep(.el-table__header) {
    th {
      background-color: #fafafa;
      color: #333;
      font-weight: 600;
    }
  }

  :deep(.el-button--text) {
    padding: 0 8px;
  }
}

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

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