<template>
  <div class="group-list-container">
    <div class="header-bar">
      <h2>兴趣小组</h2>
      <router-link v-if="authStore.isAuthenticated" :to="{ name: 'CreateGroup' }" class="button-create-group">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-plus-circle-fill" viewBox="0 0 16 16">
          <path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0M8.5 4.5a.5.5 0 0 0-1 0v3h-3a.5.5 0 0 0 0 1h3v3a.5.5 0 0 0 1 0v-3h3a.5.5 0 0 0 0-1h-3z"/>
        </svg>
        创建小组
      </router-link>
    </div>

    <div v-if="isLoading" class="loading-message">正在加载小组列表...</div>
    <div v-if="fetchError" class="error-message">{{ fetchError }}</div>
    
    <div v-if="!isLoading && groups.length === 0 && !fetchError" class="empty-state">
      <p>目前还没有任何小组。</p>
      <p v-if="authStore.isAuthenticated">成为第一个<router-link :to="{ name: 'CreateGroup' }">创建小组</router-link>的人吧！</p>
      <p v-else>请<router-link :to="{ name: 'Login' }">登录</router-link>后创建或加入小组。</p>
    </div>

    <div v-if="groups.length > 0" class="groups-grid">
      <div v-for="group in groups" :key="group.id" class="group-card">
        <router-link :to="{ name: 'GroupDetail', params: { id: group.id } }" class="group-link">
          <div class="group-cover-wrapper">
            <img 
              v-if="group.cover_image_url" 
              :src="group.cover_image_url" 
              :alt="group.name + '封面'" 
              class="group-cover"
              @error="setDefaultCover"
            />
            <div v-else class="group-cover-placeholder">
              <span>{{ group.name ? group.name.charAt(0).toUpperCase() : 'G' }}</span>
            </div>
          </div>
          <div class="group-card-content">
            <h3 class="group-name">{{ group.name }}</h3>
            <p class="group-description">{{ truncateText(group.description, 80) }}</p>
            <div class="group-meta">
              <span class="members-count">
                <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="currentColor" class="bi bi-people-fill" viewBox="0 0 16 16">
                  <path d="M7 14s-1 0-1-1 1-4 5-4 5 3 5 4-1 1-1 1zm4-6a3 3 0 1 0 0-6 3 3 0 0 0 0 6m-5.784 6A2.24 2.24 0 0 1 5 13c0-1.355.68-2.75 1.936-3.72A6.3 6.3 0 0 0 5 9c-4 0-5 3-5 4s1 1 1 1zM4.5 8a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5"/>
                </svg>
                {{ group.members_count }} 成员
              </span>
              <span v-if="group.tags_details && group.tags_details.length > 0" class="tags-preview">
                {{ group.tags_details.slice(0, 1).map(t => t.name).join('') }}
                {{ group.tags_details.length > 1 ? '...' : '' }}
              </span>
            </div>
          </div>
        </router-link>
      </div>
    </div>
    
    <div v-if="pagination.totalPages > 1 && groups.length > 0" class="pagination-controls">
      <button @click="fetchGroups(pagination.currentPage - 1)" :disabled="!pagination.previous || isLoading">上一页</button>
      <span>第 {{ pagination.currentPage }} / {{ pagination.totalPages }} 页 (共 {{ pagination.count }} 条)</span>
      <button @click="fetchGroups(pagination.currentPage + 1)" :disabled="!pagination.next || isLoading">下一页</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue';
import apiClient from '../services/api'; // 确保路径正确
import { useAuthStore } from '../store/auth'; // 确保路径正确
import { useRouter } from 'vue-router'; // 如果需要编程式导航

const groups = ref([]);
const isLoading = ref(true);
const fetchError = ref('');
const authStore = useAuthStore();
const router = useRouter(); // 如果要用router.push等

const pagination = reactive({
    currentPage: 1,
    totalPages: 1,
    next: null,
    previous: null,
    count: 0,
    pageSize: 10, // 假设每页10条，与后端分页设置匹配
});

const fetchGroups = async (page = 1) => {
  isLoading.value = true;
  fetchError.value = '';
  try {
    const response = await apiClient.get('groups/', {
      params: { page: page }
    });
    
    if (response.data && typeof response.data.count !== 'undefined') { // 检查是否是DRF分页结构
        groups.value = response.data.results;
        pagination.count = response.data.count;
        pagination.next = response.data.next;
        pagination.previous = response.data.previous;
        pagination.currentPage = page;
        // 从返回的results长度或预设值来确定pageSize
        const resultsLength = response.data.results ? response.data.results.length : 0;
        if (resultsLength > 0 && pagination.count > 0) {
             // 如果后端返回了数据，可以尝试从 next/previous URL中推断或使用实际返回数量
             // 但更可靠的是后端API能明确告知每页数量，或前端与后端约定好
             // 这里我们假设如果第一页有数据，那么pageSize就是第一页数据的长度，否则用默认值
            pagination.pageSize = resultsLength;
        } else if (pagination.count === 0) {
            pagination.pageSize = 10; // Fallback
        }
        // 如果 pageSize 能被确定，则totalPages可以这样算
        pagination.totalPages = Math.ceil(pagination.count / pagination.pageSize) || 1;
    } else { // 如果不是标准分页结构，直接赋值 (例如后端未配置分页)
        groups.value = Array.isArray(response.data) ? response.data : [];
        pagination.count = groups.value.length;
        pagination.totalPages = 1;
        pagination.currentPage = 1;
        pagination.next = null;
        pagination.previous = null;
    }
    
  } catch (error) {
    console.error('获取小组列表失败:', error.response || error);
    fetchError.value = '无法加载小组列表，请稍后重试。';
    if (error.response && error.response.status === 401 && authStore.isAuthenticated) {
        fetchError.value = '会话可能已过期，请尝试重新登录。';
        // 可以在这里触发登出或跳转
        // authStore.logout();
        // router.push('/login');
    }
  } finally {
    isLoading.value = false;
  }
};

const truncateText = (text, maxLength) => {
  if (!text) return '';
  if (text.length <= maxLength) return text;
  return text.substring(0, maxLength) + '...';
};

const setDefaultCover = (event) => {
  // 当图片加载失败时，可以设置一个默认图片或隐藏图片元素
  // 这里我们让它显示占位符的背景色（通过CSS实现）
  // event.target.style.display = 'none'; // 隐藏损坏的图片
  // 或者 event.target.src = '/path/to/default-cover.png'; // 设置默认图片
  // 为简单起见，如果图片加载失败，CSS中的占位符会因img标签存在而不显示，可以调整逻辑
  const wrapper = event.target.parentElement;
  if (wrapper && wrapper.classList.contains('group-cover-wrapper')) {
    const placeholder = wrapper.querySelector('.group-cover-placeholder');
    if (placeholder) placeholder.style.display = 'flex'; // 显示占位符
    event.target.style.display = 'none'; // 隐藏加载失败的img
  }
};

onMounted(() => {
  fetchGroups(); // 获取第一页数据
});
</script>

<style scoped>
.group-list-container {
  max-width: 1200px; /* 稍微加宽以容纳更多卡片 */
  margin: 20px auto;
  padding: 20px;
}
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}
.header-bar h2 {
  margin: 0;
  font-size: 1.8em;
}
.button-create-group {
  display: inline-flex; /* 改为inline-flex使图标和文字在同一行且垂直居中 */
  align-items: center;
  padding: 8px 15px;
  background-color: #28a745;
  color: white;
  text-decoration: none;
  border-radius: 5px;
  font-size: 0.95em;
  transition: background-color 0.3s;
}
.button-create-group svg {
  margin-right: 6px; /* 图标和文字间距 */
}
.button-create-group:hover {
  background-color: #218838;
}

.groups-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); /* 调整卡片最小宽度 */
  gap: 25px; /* 调整间距 */
}
.group-card {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background-color: #fff;
  transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
  overflow: hidden; /* 确保内容不超过卡片 */
}
.group-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}
.group-link {
  text-decoration: none;
  color: inherit;
  display: flex; /* 改为flex布局使内容垂直排列 */
  flex-direction: column;
  height: 100%; /* 使链接填满卡片 */
}
.group-cover-wrapper {
  width: 100%;
  padding-top: 56.25%; /* 16:9 aspect ratio */
  position: relative;
  background-color: #f0f2f5; /* Placeholder background */
}
.group-cover {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover; /* 图片裁剪以填充 */
}
.group-cover-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2em;
  color: #bdc3c7;
  background-color: #ecf0f1;
  user-select: none;
}
.group-card-content {
  padding: 15px;
  flex-grow: 1; /* 使内容区填满剩余空间 */
  display: flex;
  flex-direction: column;
}
.group-name {
  font-size: 1.25em;
  font-weight: 600; /* 稍微加粗 */
  margin-top: 0;
  margin-bottom: 8px;
  color: #2c3e50;
}
.group-description {
  font-size: 0.9em;
  color: #555; /* 深一点的灰色 */
  line-height: 1.5;
  margin-bottom: 12px;
  flex-grow: 1; /* 使描述填满可用空间，为元数据留出底部空间 */
  /* 多行省略实现 (需要固定高度或行数) */
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 显示3行 */
  -webkit-box-orient: vertical;  
  overflow: hidden;
  text-overflow: ellipsis;
  min-height: 4.5em; /* 0.9em * 1.5 * 3行 */
}
.group-meta {
  font-size: 0.8em;
  color: #7f8c8d; /* 稍浅的灰色 */
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto; /* 将元数据推到卡片底部 */
  border-top: 1px solid #f0f0f0; /* 分隔线 */
  padding-top: 10px;
}
.members-count {
  display: inline-flex;
  align-items: center;
}
.members-count svg {
  margin-right: 4px;
}
.tags-preview {
  max-width: 50%; /* 限制标签预览宽度 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: right;
}
.loading-message, .error-message, .empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #555;
}
.empty-state p {
  margin-bottom: 10px;
}
.empty-state a {
  color: #007bff;
  font-weight: bold;
}
.pagination-controls {
  margin-top: 30px;
  text-align: center;
}
.pagination-controls button {
  margin: 0 8px;
  padding: 8px 16px;
  cursor: pointer;
  border: 1px solid #ddd;
  background-color: #fff;
  border-radius: 4px;
  transition: background-color 0.2s;
}
.pagination-controls button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
.pagination-controls button:hover:not(:disabled) {
  background-color: #f0f0f0;
}
.pagination-controls span {
  margin: 0 10px;
  color: #555;
}
</style>