<template>
  <div class="group-detail-container">
    <div v-if="isLoadingGroup" class="loading-message">正在加载小组信息...</div>
    <div v-if="fetchGroupError" class="error-message">{{ fetchGroupError }}</div>
<div v-if="group" class="group-header">
  <img v-if="group.cover_image_url" :src="group.cover_image_url" :alt="group.name + '封面'" class="group-detail-cover">
  <div v-else class="group-detail-cover-placeholder">{{ group.name ? group.name.charAt(0).toUpperCase() : 'G' }}</div>
  <div class="group-info">
    <h1>{{ group.name }}</h1>
    <p class="group-description-detail">{{ group.description }}</p>
    <div class="group-meta-detail">
      <span>创建者: {{ group.creator ? group.creator.nickname : '未知' }}</span>
      <span>成员: {{ group.members_count }}</span>
      <span v-if="group.tags_details && group.tags_details.length > 0">
        标签: {{ group.tags_details.map(t => t.name).join(', ') }}
      </span>
    </div>
    <div class="group-actions" v-if="authStore.isAuthenticated">
      <button 
        @click="toggleJoinLeaveGroup" 
        :disabled="isJoiningOrLeaving"
        :class="{'button-leave': isMember, 'button-join': !isMember}"
      >
        {{ isJoiningOrLeaving ? '处理中...' : (isMember ? '退出小组' : '加入小组') }}
      </button>
      <!-- 未来可以添加编辑小组按钮 (如果当前用户是创建者/管理员) -->
    </div>
    <p v-if="joinLeaveError" class="error-message small-error">{{ joinLeaveError }}</p>
    <p v-if="joinLeaveSuccess" class="success-message small-success">{{ joinLeaveSuccess }}</p>
  </div>
</div>

<hr class="divider" v-if="group">

<div v-if="group" class="posts-section">
  <h3>小组内帖子/动态</h3>
  
  <!-- 创建新帖子的表单/入口 (仅对小组成员显示) -->
  <div v-if="isMember && authStore.isAuthenticated" class="create-post-section">
    <h4>发布新动态</h4>
    <form @submit.prevent="handleCreatePost" class="create-post-form">
      <div class="form-group">
        <label for="post-title">标题 (可选):</label>
        <input type="text" id="post-title" v-model="newPost.title" maxlength="200">
      </div>
      <div class="form-group">
        <label for="post-content">内容:</label>
        <textarea id="post-content" v-model="newPost.content" required></textarea>
      </div>
      <!-- (可选) 帖子图片上传 -->
      <!-- <div class="form-group">
        <label for="post-image">图片 (可选):</label>
        <input type="file" id="post-image" @change="handlePostImageChange" accept="image/*">
      </div> -->
      <button type="submit" :disabled="isSubmittingPost">
        {{ isSubmittingPost ? '发布中...' : '发布动态' }}
      </button>
      <p v-if="createPostError" class="error-message small-error">{{ createPostError }}</p>
    </form>
  </div>
  <p v-else-if="!isMember && authStore.isAuthenticated && group" class="info-message">
    加入小组后才能发布动态。
  </p>


  <div v-if="isLoadingPosts" class="loading-message">正在加载帖子...</div>
  <div v-if="fetchPostsError" class="error-message">{{ fetchPostsError }}</div>
  
  <div v-if="posts.length > 0" class="post-list">
    <div v-for="post in posts" :key="post.id" class="post-item">
      <router-link :to="{ name: 'PostDetail', params: { id: post.id } }" class="post-link">
        <div class="post-header">
          <img v-if="post.author && post.author.avatar_url" :src="post.author.avatar_url" alt="author avatar" class="post-author-avatar">
          <div v-else class="post-author-avatar-placeholder">{{ post.author ? post.author.nickname.charAt(0) : 'U' }}</div>
          <div class="post-author-info">
            <span class="post-author-name">{{ post.author ? post.author.nickname : '匿名用户' }}</span>
            <span class="post-created-at">{{ formatDateTime(post.created_at) }}</span>
          </div>
        </div>
        <h4 class="post-title">{{ post.title || '动态分享' }}</h4>
        <p class="post-content-preview">{{ truncateText(post.content, 150) }}</p>
        <div class="post-meta">
          <span>赞: {{ post.likes_count }}</span>
          <span>评论: {{ post.comments_count || 0 }}</span> <!-- 假设PostSerializer未来会加comments_count -->
        </div>
      </router-link>
    </div>
  </div>
  <p v-else-if="!isLoadingPosts && !fetchPostsError" class="info-message">
    这个小组还没有任何动态，快来发布第一条吧！
  </p>
  <!-- (可选) 帖子列表的分页 -->
</div>

<div v-if="!group && !isLoadingGroup && !fetchGroupError" class="not-found-message">
    <p>无法找到该小组，或者小组不存在。</p>
    <router-link to="/groups">返回小组列表</router-link>
</div>
Use code with caution.
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import apiClient from '../services/api';
import { useAuthStore } from '../store/auth';
import { useRoute, useRouter } from 'vue-router'; // useRoute 获取当前路由信息

const group = ref(null);
const isLoadingGroup = ref(true);
const fetchGroupError = ref('');

const posts = ref([]);
const isLoadingPosts = ref(false);
const fetchPostsError = ref('');

const authStore = useAuthStore();
const route = useRoute(); // 获取当前路由对象
const router = useRouter(); // 用于编程式导航

const groupId = computed(() => route.params.id); // 从路由参数获取小组ID

const isMember = ref(false); // 当前用户是否是小组成员
const isJoiningOrLeaving = ref(false);
const joinLeaveError = ref('');
const joinLeaveSuccess = ref('');

const newPost = reactive({
  title: '',
  content: '',
  // image: null,
});
const isSubmittingPost = ref(false);
const createPostError = ref('');

// 获取小组详情
const fetchGroupDetail = async () => {
  isLoadingGroup.value = true;
  fetchGroupError.value = '';
  try {
    const response = await apiClient.get(`groups/${groupId.value}/`);
    group.value = response.data;
    checkMembership(); // 获取小组详情后检查成员状态
  } catch (error) {
    console.error('获取小组详情失败:', error);
    fetchGroupError.value = '无法加载小组信息。';
     if (error.response && error.response.status === 404) {
        fetchGroupError.value = '该小组不存在或已被删除。';
    }
  } finally {
    isLoadingGroup.value = false;
  }
};

// 获取小组内帖子列表
const fetchGroupPosts = async () => {
  if (!groupId.value) return;
  isLoadingPosts.value = true;
  fetchPostsError.value = '';
  try {
    // 使用我们之前在GroupViewSet中定义的action: groups/<pk>/posts/
    const response = await apiClient.get(`groups/${groupId.value}/posts/`);
    posts.value = response.data.results || response.data; // 处理分页或直接列表
  } catch (error) {
    console.error('获取小组帖子失败:', error);
    fetchPostsError.value = '无法加载小组动态。';
  } finally {
    isLoadingPosts.value = false;
  }
};

// 检查当前用户是否是小组成员
const checkMembership = async () => {
    if (!authStore.isAuthenticated || !group.value) {
        isMember.value = false;
        return;
    }
    try {
        // 可以通过比较group.members中的ID，或者调用一个专门的API检查成员资格
        // 简单起见，如果后端GroupSerializer返回了members ID列表 (我们目前返回members_count)
        // 或者，更可靠的是，当用户加入/退出时维护一个本地状态或重新获取用户加入的小组列表
        // 为了演示，我们假设需要一个方式来判断。
        // 实际项目中，可以在获取小组详情时，后端API返回一个字段 is_current_user_member
        // 或者前端在获取 "我的小组" 列表后存起来对比。
        // 这里我们模拟一个简单的检查，假设group对象中有一个members ID列表 (实际上我们只有members_count)
        // 因此，更准确的做法是调用 "my_groups" API 然后检查，或者后端API直接返回这个信息
        // **为了简化，我们先假设如果用户是创建者，他就是成员；否则需要加入。**
        // **更完善的逻辑是，当用户加入/退出小组时，更新 isMember 的状态。**
        if (group.value.creator && group.value.creator.id === authStore.currentUser?.id) {
            isMember.value = true; // 创建者默认是成员
        } else {
            // 需要更可靠的方式来判断成员资格，例如查看 authStore.currentUser.joined_groups
            // 或者在小组详情API中，后端返回一个字段告知当前用户是否是成员。
            // 我们先假设一个简单的占位逻辑，或者在用户点击加入/退出后更新isMember
            // 调用 "my_groups" 然后检查
            if (authStore.currentUser) {
                const myGroupsResponse = await apiClient.get('groups/my-groups/');
                const myGroupIds = (myGroupsResponse.data.results || myGroupsResponse.data).map(g => g.id);
                isMember.value = myGroupIds.includes(parseInt(groupId.value));
            } else {
                isMember.value = false;
            }
        }
    } catch(e) {
        console.error("Check membership error", e);
        isMember.value = false; // 出错则认为不是成员
    }
};

// 加入/退出小组的逻辑
const toggleJoinLeaveGroup = async () => {
  if (!authStore.isAuthenticated) {
    router.push('/login');
    return;
  }
  isJoiningOrLeaving.value = true;
  joinLeaveError.value = '';
  joinLeaveSuccess.value = '';
  const actionUrl = isMember.value ? `groups/${groupId.value}/leave_group/` : `groups/${groupId.value}/join_group/`;
  try {
    await apiClient.post(actionUrl);
    isMember.value = !isMember.value; // 切换成员状态
    joinLeaveSuccess.value = isMember.value ? '成功加入小组！' : '已成功退出小组。';
    // 成功后应该更新小组成员数量 (group.value.members_count)
    // 最好的方式是重新获取小组详情，或者后端API返回更新后的小组数据
    fetchGroupDetail(); // 重新获取小组信息以更新成员数
  } catch (error) {
    console.error('加入/退出小组失败:', error.response?.data?.detail || error.message);
    joinLeaveError.value = error.response?.data?.detail || '操作失败，请重试。';
  } finally {
    isJoiningOrLeaving.value = false;
    setTimeout(() => { // 消息显示一会儿后消失
        joinLeaveSuccess.value = '';
        joinLeaveError.value = '';
    }, 3000);
  }
};

// 创建新帖子的逻辑
const handleCreatePost = async () => {
  if (!newPost.content.trim()) {
    createPostError.value = "帖子内容不能为空。";
    return;
  }
  isSubmittingPost.value = true;
  createPostError.value = '';
  try {
    // 使用 GroupViewSet 中的 create_group_post action
    // URL: groups/<group_pk>/create-post/
    const response = await apiClient.post(`groups/${groupId.value}/create-post/`, {
      title: newPost.title,
      content: newPost.content,
      // image: newPost.image, // 如果有图片上传
    });
    posts.value.unshift(response.data); // 将新帖子添加到列表顶部
    newPost.title = ''; // 清空表单
    newPost.content = '';
    // newPost.image = null;
  } catch (error) {
    console.error('发布帖子失败:', error.response?.data || error.message);
    createPostError.value = error.response?.data?.detail || Object.values(error.response?.data || {}).flat().join('; ') || '发布失败，请重试。';
  } finally {
    isSubmittingPost.value = false;
  }
};

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

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '';
  const options = { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' };
  return new Date(dateTimeString).toLocaleDateString(undefined, options);
};

// 组件挂载时获取数据
onMounted(async () => {
  await fetchGroupDetail(); // 先获取小组详情
  if (group.value) { // 只有小组存在才获取帖子和检查成员
    await fetchGroupPosts();
    // checkMembership(); // fetchGroupDetail 内部会调用 checkMembership
  }
});

// 监听路由参数变化，如果小组ID变了，重新加载数据
watch(() => route.params.id, (newId, oldId) => {
  if (newId && newId !== oldId) {
    fetchGroupDetail();
    fetchGroupPosts();
  }
});
// 监听登录状态变化，如果用户登录/登出，重新检查成员资格
watch(() => authStore.isAuthenticated, (isAuth) => {
    if (group.value) { // 只有在小组数据已加载时才重新检查
        checkMembership();
    }
});

</script>
<style scoped>
.group-detail-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}
.group-header {
  display: flex;
  align-items: flex-start; /* 顶部对齐 */
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}
.group-detail-cover, .group-detail-cover-placeholder {
  width: 150px;
  height: 150px;
  object-fit: cover;
  border-radius: 8px;
  margin-right: 20px;
  flex-shrink: 0; /* 防止图片被压缩 */
  background-color: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 3em;
  color: #bdc3c7;
}
.group-info {
  text-align: left;
  flex-grow: 1;
}
.group-info h1 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 2em;
  color: #333;
}
.group-description-detail {
  font-size: 1em;
  color: #555;
  line-height: 1.6;
  margin-bottom: 15px;
}
.group-meta-detail {
  font-size: 0.9em;
  color: #777;
}
.group-meta-detail span {
  margin-right: 15px;
}
.group-actions {
  margin-top: 15px;
}
.group-actions button {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 500;
}
.button-join { background-color: #28a745; color: white; }
.button-join:hover { background-color: #218838; }
.button-leave { background-color: #dc3545; color: white; }
.button-leave:hover { background-color: #c82333; }
.button-leave:disabled, .button-join:disabled { background-color: #ccc; }

.divider {
    margin: 30px 0;
    border: 0;
    border-top: 1px solid #eee;
}

.posts-section h3 {
  font-size: 1.5em;
  margin-bottom: 20px;
  color: #333;
}
.create-post-section {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
  border: 1px solid #e7e7e7;
}
.create-post-section h4 {
  margin-top: 0;
  margin-bottom: 15px;
}
.create-post-form .form-group {
  margin-bottom: 15px;
}
.create-post-form label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}
.create-post-form input[type="text"],
.create-post-form textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}
.create-post-form textarea {
  min-height: 80px;
  resize: vertical;
}
.create-post-form button[type="submit"] {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.create-post-form button:disabled {
    background-color: #aaa;
}

.post-list {
  margin-top: 20px;
}
.post-item {
  background-color: #fff;
  border: 1px solid #e7e7e7;
  border-radius: 6px;
  margin-bottom: 15px;
  padding: 15px;
  transition: box-shadow 0.2s;
}
.post-item:hover {
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}
.post-link {
    text-decoration: none;
    color: inherit;
}
.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.post-author-avatar, .post-author-avatar-placeholder {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin-right: 10px;
  object-fit: cover;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: #777;
}
.post-author-info {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.post-author-name {
  font-weight: 600;
  font-size: 0.95em;
}
.post-created-at {
  font-size: 0.8em;
  color: #777;
}
.post-title {
  font-size: 1.15em;
  font-weight: 600;
  margin-bottom: 8px;
  color: #333;
}
.post-content-preview {
  font-size: 0.95em;
  color: #444;
  line-height: 1.6;
  white-space: pre-line; /* 保留换行 */
}
.post-meta {
  margin-top: 10px;
  font-size: 0.85em;
  color: #888;
}
.post-meta span {
  margin-right: 15px;
}
.info-message, .not-found-message {
  text-align: center;
  padding: 20px;
  color: #666;
}
.error-message.small-error, .success-message.small-success {
  font-size: 0.85em;
  padding: 8px;
  margin-top: 10px;
}
</style>