<template>
  <view class="my-registration-page">
    <!-- Tab切换 -->
    <custom-tabs :tabs="tabs" :current="currentTab" @change="handleTabChange"></custom-tabs>

    <!-- 赛事列表 -->
    <view class="event-list">
      <view
        class="event-item"
        v-for="(item, index) in filteredList"
        :key="index"
        @click="goToEventDetail(item)"
      >
        <view class="status-tag" :class="getStatusClass(item.status)">
          <text>{{ getStatusText(item.status) }}</text>
        </view>

        <view class="event-title">{{ item.title }}</view>

        <view class="event-info">
          <text class="label">地点：</text>
          <text class="value location-text">{{ item.location || "暂无" }}</text>
        </view>

        <view class="event-info">
          <text class="label">比赛时间：</text>
          <text class="value">{{ item.matchTime || "暂无" }}</text>
        </view>

        <view class="event-info">
          <text class="label">报名项目：</text>
          <text class="value">{{ item.projects || "暂无" }}</text>
        </view>

        <view class="event-info">
          <text class="label">联系人：</text>
          <text class="value">{{ item.contact || "暂无" }}</text>
        </view>

        <view class="event-info">
          <text class="label">参赛选手：</text>
          <text class="value participants">{{ item.participants }}</text>
        </view>

        <view class="event-footer">
          <view class="register-note" v-if="item.status === 'ongoing'">
            <text>点击后进入【赛事详情】页面</text>
          </view>
          <view class="view-cert-btn" @click.stop="handleViewCert(item)">
            <text>查看证件</text>
            <text class="arrow">›</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="filteredList.length === 0">
      <text class="empty-text">暂无报名记录</text>
    </view>

    <!-- 证件弹窗 -->
    <view class="cert-modal" v-if="showCertModal" @click="closeCertModal">
      <view class="cert-modal-content" @click.stop>
        <view class="cert-modal-header">
          <text class="cert-modal-title">参赛选手证件</text>
          <text class="cert-close-icon" @click="closeCertModal">✕</text>
        </view>
        <scroll-view class="cert-modal-body" scroll-y>
          <view class="cert-athlete-item" v-for="(athlete, index) in certAthleteList" :key="index">
            <view class="cert-athlete-name">{{ athlete.playerName }}</view>
            <view class="cert-athlete-info">性别：{{ athlete.gender === 1 ? '男' : '女' }}</view>
            <view class="cert-athlete-info">身份证：{{ athlete.idCard || '暂无' }}</view>
          </view>
          <view class="cert-empty" v-if="certAthleteList.length === 0">
            <text>暂无选手信息</text>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
import CustomTabs from '../../components/custom-tabs/custom-tabs.vue';
import registrationAPI from '@/api/registration.js'
import competitionAPI from '@/api/competition.js'

export default {
  components: {
    CustomTabs
  },
  data() {
    return {
      tabs: ['全部', '待开始', '进行中', '已结束'],
      currentTab: 0,
      eventList: [],
      // 分页参数
      pageParams: {
        current: 1,
        size: 20
      },
      hasMore: true,
      showCertModal: false,
      certAthleteList: []
    };
  },
  onLoad() {
    this.loadRegistrationList()
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.pageParams.current = 1
    this.loadRegistrationList(true)
  },
  // 上拉加载更多
  onReachBottom() {
    if (this.hasMore) {
      this.pageParams.current++
      this.loadRegistrationList(false, true)
    }
  },
  computed: {
    filteredList() {
      if (this.currentTab === 0) {
        return this.eventList;
      }
      const statusMap = {
        1: 'pending',
        2: 'ongoing',
        3: 'finished'
      };
      return this.eventList.filter(item => item.status === statusMap[this.currentTab]);
    }
  },
  methods: {
    /**
     * 加载我的报名列表
     * @param {Boolean} refresh 是否刷新（重置列表）
     * @param {Boolean} loadMore 是否加载更多（追加列表）
     */
    async loadRegistrationList(refresh = false, loadMore = false) {
      try {
        const params = {
          current: this.pageParams.current,
          size: this.pageParams.size
        }

        // 添加状态筛选
        if (this.currentTab > 0) {
          params.status = this.currentTab
        }

        const res = await registrationAPI.getRegistrationList(params)

        console.log('=== 我的报名列表 ===', res)

        let list = []
        let total = 0

        // 处理分页数据
        if (res.records) {
          list = res.records
          total = res.total || 0
        } else if (Array.isArray(res)) {
          list = res
          total = res.length
        }

        // 优化：先收集所有不重复的赛事ID，批量获取赛事信息（使用缓存）
        const competitionIds = [...new Set(list.map(item => item.competitionId).filter(Boolean))]
        const competitionMap = await this.batchGetCompetitionInfo(competitionIds)

        // 映射数据（不再单独请求赛事详情）
        const mappedList = list.map(item => this.mapRegistrationItem(item, competitionMap))

        // 刷新或加载更多
        if (refresh || !loadMore) {
          this.eventList = mappedList
        } else {
          this.eventList = [...this.eventList, ...mappedList]
        }

        // 判断是否还有更多数据
        this.hasMore = this.eventList.length < total

        // 停止下拉刷新
        if (refresh) {
          uni.stopPullDownRefresh()
        }
      } catch (err) {
        console.error('加载报名列表失败:', err)
        uni.stopPullDownRefresh()
      }
    },

    /**
     * 批量获取赛事信息（带缓存，避免重复请求）
     * @param {Array} competitionIds 赛事ID数组
     * @returns {Promise<Object>} 赛事信息Map {id: info}
     */
    async batchGetCompetitionInfo(competitionIds) {
      const competitionMap = {}

      // 初始化缓存
      if (!this.competitionCache) {
        this.competitionCache = {}
      }

      // 过滤出未缓存的赛事ID
      const uncachedIds = competitionIds.filter(id => !this.competitionCache[id])

      // 只请求未缓存的赛事（去重后通常只有1-2个）
      if (uncachedIds.length > 0) {
        console.log('需要请求的赛事ID（去重后）:', uncachedIds)

        // 并行请求所有未缓存的赛事详情
        const promises = uncachedIds.map(async (id) => {
          try {
            const info = await competitionAPI.getCompetitionDetail(id)
            this.competitionCache[id] = info
          } catch (err) {
            console.error('获取赛事详情失败:', id, err)
            this.competitionCache[id] = null
          }
        })

        await Promise.all(promises)
      }

      // 从缓存中获取所有赛事信息
      competitionIds.forEach(id => {
        competitionMap[id] = this.competitionCache[id] || null
      })

      return competitionMap
    },

    /**
     * 映射单条报名记录（使用已缓存的赛事信息）
     * @param {Object} item 订单信息
     * @param {Object} competitionMap 赛事信息Map
     * @returns {Object} 映射后的数据
     */
    mapRegistrationItem(item, competitionMap) {
      const competitionInfo = competitionMap[item.competitionId] || {}

      return {
        id: item.id,
        competitionId: item.competitionId,
        status: this.getStatus(item.status),
        title: competitionInfo.competitionName || competitionInfo.name || item.competitionName || '未知赛事',
        location: competitionInfo.location || competitionInfo.address || item.location || '',
        matchTime: this.formatTimeRange(
          competitionInfo.competitionStartTime || competitionInfo.startTime,
          competitionInfo.competitionEndTime || competitionInfo.endTime
        ) || '',
        projects: item.projectNames || this.formatProjects(item.projects) || '',
        contact: item.contactPhone || item.contactPerson || '',
        participants: item.athleteNames || `${item.totalParticipants || 0}人`,
        athleteList: item.athleteList || []
      }
    },

    /**
     * 格式化时间范围
     */
    formatTimeRange(startTime, endTime) {
      if (!startTime || !endTime) return ''

      const formatDate = (dateStr) => {
        if (!dateStr) return ''
        const date = new Date(dateStr)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        return `${year}.${month}.${day}`
      }

      return `${formatDate(startTime)}-${formatDate(endTime)}`
    },

    /**
     * 获取报名状态
     */
    getStatus(status) {
      // 1: 待开始, 2: 进行中, 3: 已结束
      const statusMap = {
        1: 'pending',
        2: 'ongoing',
        3: 'finished',
        'pending': 'pending',
        'ongoing': 'ongoing',
        'finished': 'finished'
      }
      return statusMap[status] || 'pending'
    },

    /**
     * 格式化报名项目
     */
    formatProjects(projects) {
      if (!projects) return ''
      if (Array.isArray(projects)) {
        return projects.map(p => p.name || p.projectName).join('、')
      }
      return projects
    },

    /**
     * 格式化参赛选手
     */
    formatParticipants(athletes) {
      if (!athletes) return ''
      if (Array.isArray(athletes)) {
        return athletes.map(a => a.name || a.athleteName).join('、')
      }
      return athletes
    },

    handleTabChange(index) {
      this.currentTab = index;
      // 切换tab时重新加载
      this.pageParams.current = 1
      this.loadRegistrationList(true)
    },
    getStatusClass(status) {
      return {
        'status-ongoing': status === 'ongoing',
        'status-pending': status === 'pending',
        'status-finished': status === 'finished'
      };
    },
    getStatusText(status) {
      const statusMap = {
        ongoing: '进行中',
        pending: '待开始',
        finished: '已结束'
      };
      return statusMap[status] || '';
    },
    goToEventDetail(item) {
      uni.navigateTo({
        url: '/pages/event-detail/event-detail?id=' + item.competitionId + '&orderId=' + item.id
      });
    },
    handleViewCert(item) {
      // Get athlete list from the item
      if (item.athleteList && item.athleteList.length > 0) {
        this.certAthleteList = item.athleteList;
        this.showCertModal = true;
      } else {
        uni.showToast({
          title: '暂无选手证件信息',
          icon: 'none'
        });
      }
    },
    closeCertModal() {
      this.showCertModal = false;
      this.certAthleteList = [];
    }
  }
};
</script>

<style lang="scss" scoped>
.my-registration-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.event-list {
  padding: 30rpx;
}

.event-item {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  position: relative;
}

.status-tag {
  position: absolute;
  top: 30rpx;
  left: 30rpx;
  padding: 8rpx 20rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  color: #fff;
}

.status-ongoing {
  background-color: #4CAF50;
}

.status-pending {
  background-color: #FF9800;
}

.status-finished {
  background-color: #999999;
}

.event-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin: 50rpx 0 20rpx;
  line-height: 1.5;
}

.event-info {
  display: flex;
  margin-bottom: 10rpx;
}

.label {
  font-size: 26rpx;
  color: #666666;
  flex-shrink: 0;
}

.value {
  font-size: 26rpx;
  color: #666666;
  flex: 1;
}

.location-text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: block;
  max-width: 480rpx;
}

.participants {
  word-break: break-all;
}

.event-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f5f5f5;
}

.register-note {
  font-size: 24rpx;
  color: #C93639;
}

.view-cert-btn {
  display: flex;
  align-items: center;
  padding: 10rpx 20rpx;
  border: 2rpx solid #C93639;
  border-radius: 8rpx;
  font-size: 24rpx;
  color: #C93639;
}

.arrow {
  font-size: 28rpx;
  margin-left: 5rpx;
}

.empty-state {
  padding: 200rpx 0;
  text-align: center;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
}

/* Cert Modal Styles */
.cert-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.cert-modal-content {
  background-color: #fff;
  border-radius: 16rpx;
  width: 85%;
  max-height: 70vh;
  overflow: hidden;
}

.cert-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.cert-modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.cert-close-icon {
  font-size: 36rpx;
  color: #999;
  cursor: pointer;
}

.cert-modal-body {
  max-height: 50vh;
  padding: 20rpx 30rpx;
}

.cert-athlete-item {
  padding: 20rpx;
  background-color: #f9f9f9;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.cert-athlete-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.cert-athlete-info {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 6rpx;
}

.cert-empty {
  text-align: center;
  padding: 40rpx;
  color: #999;
}
</style>
