<template>
  <div class="league-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="queryParams.keyword"
        :placeholder="t('搜索联赛名称')"
        clearable
        @clear="handleSearch"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button @click="handleSearch">{{ t('搜索') }}</el-button>
        </template>
      </el-input>
    </div>

    <!-- 联赛列表 -->
    <div class="league-list" v-loading="loading">
      <div v-for="league in leagues" :key="league.league_id" class="league-item">
        <!-- 联赛头部 -->
        <div class="league-header" @click="toggleLeague(league)">
          <span class="league-name">
            {{ currentLocale === 'zh' ? league.league : league.league_en }}
          </span>
          
          <div class="header-right">
            <span class="play-count">{{ league.sport_count || league.match_count || 0 }}</span>
            <div class="arrow-icon" :class="{ 'is-active': expandedIds.includes(league.league_id) }">
              <el-icon><ArrowRight /></el-icon>
            </div>
          </div>
        </div>

        <!-- 展开后的赛事列表 -->
        <div v-if="expandedIds.includes(league.league_id)" class="match-expand-content">
          <div v-if="matchData[league.league_id]?.loading" class="match-loading">
            {{ t('加载中...') }}
          </div>
          
          <template v-else-if="matchData[league.league_id]?.list?.length">
            <div v-for="item in matchData[league.league_id].list" :key="item.id" 
            class="match-card" @click="goDetail(item)">
              <div class="match-info">
                <span class="game-time">{{ item.game_time }}</span>
                <span class="match-state" :class="'state-' + item.state">
                  {{ getStateName(item.state) }}
                </span>
              </div>

              <div class="match-teams-vertical">
                <div class="team-row">
                  <div class="team-info">
                    <el-image :src="item.home_team_logo" class="team-logo-small">
                      <template #error><div class="image-slot">Logo</div></template>
                    </el-image>
                    <div class="team-name">{{ item.home_team }}</div>
                  </div>
                  <div class="score" v-if="item.state !== 0">{{ item.home_score ?? 0 }}</div>
                </div>

                <div class="team-row">
                  <div class="team-info">
                    <el-image :src="item.guest_team_logo" class="team-logo-small">
                      <template #error><div class="image-slot">Logo</div></template>
                    </el-image>
                    <div class="team-name">{{ item.guest_team }}</div>
                  </div>
                  <div class="score" v-if="item.state !== 0">{{ item.guest_score ?? 0 }}</div>
                </div>
              </div>
            </div>
          </template>
          
          <el-empty v-else :image-size="40" :description="t('暂无赛事')" />
        </div>
      </div>

      <el-empty 
        v-if="leagues.length === 0 && !loading" 
        :description="t('暂无联赛数据')" 
      />
    </div>

    <!-- 分页组件 -->
    <div class="pagination-wrapper">
      <el-pagination
        style="width: 100%;"
        small 
        v-model:current-page="queryParams.page"
        :total="total"
        layout="prev, pager, next"
        :page-size="queryParams.limit"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ArrowRight } from '@element-plus/icons-vue'
import { getLeagueList, getSportSchedule } from "@/request/api.js"
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'

const router = useRouter()
const { t, locale } = useI18n()
const currentLocale = computed(() => locale.value)

// 数据
const loading = ref(false)
const leagues = ref([])
const expandedIds = ref([])
const matchData = reactive({})

const total = ref(0)   // 新增：总数据条数

const queryParams = reactive({
  page: 1,
  limit: 10,
  keyword: ''
})

// 获取联赛列表
const fetchLeagues = async () => {
  loading.value = true
  try {
    const res = await getLeagueList(queryParams)
    if (res.code === 1) {
      leagues.value = res.data.list || []
      total.value = res.data.count || 0   // 获取总条数
    }
  } catch (error) {
    console.error('获取联赛失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取赛事列表
const fetchMatches = async (leagueId) => {
  matchData[leagueId] = { list: [], loading: true }
  try {
    const res = await getSportSchedule({
      page: 1,
      limit: 999,
      league_id: leagueId,
      from: 'pc'
    })
    if (res.code === 1) {
      matchData[leagueId].list = res.data.list || []
    }
  } catch (error) {
    console.error('获取赛事详情失败:', error)
  } finally {
    matchData[leagueId].loading = false
  }
}

// 切换展开
const toggleLeague = (league) => {
  const index = expandedIds.value.indexOf(league.league_id)
  if (index > -1) {
    expandedIds.value.splice(index, 1)
  } else {
    expandedIds.value.push(league.league_id)
    if (!matchData[league.league_id]) {
      fetchMatches(league.league_id)
    }
  }
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  fetchLeagues()
}

// 分页切换
const handlePageChange = (page) => {
  queryParams.page = page
  fetchLeagues()
  // 可选：切换分页时收起所有已展开的联赛
  // expandedIds.value = []
}

const getStateName = (state) => {
  const states = {
    0: t('未开始'),
    1: t('进行中'),
    2: t('已完场')
  }
  return states[state] || ''
}

const goDetail = (item) => {
  router.push({ name: 'SportDetail', query: { data_id: item.data_id } });
};

onMounted(() => {
  fetchLeagues()
})
</script>

<style scoped>
/* 卡片样式 */
.match-card {
  margin-bottom: 12px;
  border-radius: 12px;
  border: none;
  background-color: #212121;
  --el-card-padding: 16px;
  cursor: pointer;
}

.match-info {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 10px;
}

.league-box {
  flex: 1;
}

.league-name {
  color: #ffffff;
  font-weight: 600;
  font-size: 12px;
  line-height: 1.4;
  display: block;
}

.status-box {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
  flex-shrink: 0;
}

.match-state {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 11px;
  background: #2a2a2a;
  border: 1px solid #3d3d3d;
}

.state-1 { color: #ff4d4f; border-color: rgba(255, 77, 79, 0.3); }
.state-0 { color: #f2ba45; border-color: rgba(242, 186, 69, 0.3); }
.state-2 { color: #858585; }

.game-time {
  color: #858585;
  font-size: 11px;
}

.match-teams-vertical {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding-top: 4px;
}

.team-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.team-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.team-logo-small {
  width: 20px;
  height: 20px;
  flex-shrink: 0;
}

.team-name {
  font-size: 12px;
  font-weight: 500;
  color: #ffffff;
}

.score {
  font-size: 18px;
  font-weight: 700;
  color: #f2ba45;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #2a2a2a;
  color: #555;
  font-size: 8px;
}
.league-container {
}

/* 搜索栏和列表样式（省略前面已有的样式，保持一致） */
.search-bar { margin-bottom: 16px; }

:deep(.el-input-group__append) {
  background-color: #f2ba45;
  color: #000;
  border: none;
}
:deep(.el-input__wrapper) {
  background-color: #212121;
  box-shadow: none !important;
  border: 1px solid #333;
}
:deep(.el-input__inner) {
  color: #fff;
}

.league-item { margin-bottom: 8px; background-color: #212121; border-radius: 8px; overflow: hidden; }

.league-header {
  padding: 10px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  transition: background 0.3s;
}

.league-header:hover { background-color: #2a2a2a; }

.league-name {
  color: #ffffff;
  font-weight: 600;
  font-size: 14px;
  flex: 1;
  margin-right: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.header-right { display: flex; align-items: center; gap: 8px; }

.play-count {
  color: #f2ba45;
  font-size: 13px;
  font-weight: 500;
}

.arrow-icon {
  color: #666;
  transition: transform 0.3s;
}
.arrow-icon.is-active {
  transform: rotate(90deg);
  color: #f2ba45;
}

.match-expand-content {
  padding: 4px 0 12px 0;
  background-color: #1a1a1a;
  .match-loading{
    text-align: center;
    margin: 20px 0;
  }
}

.match-card {
  margin: 8px 0;
  padding: 12px 16px;
  border-radius: 8px;
  background-color: #212121;
  border: 1px solid #2a2a2a;
}

/* ========== 新增：分页样式 ========== */
.pagination-wrapper {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  width: 100%;
  box-sizing: border-box;
}

/* 可选：自定义分页样式 */
:deep(.el-pagination) {
  border-radius: 8px;
}
</style>