<template>
  <div class="post-detail-container">
    <div v-if="isLoadingPost && !post" class="loading-message">正在加载帖子详情...</div>
    <div v-if="fetchPostError" class="error-message">{{ fetchPostError }}</div>

    <div v-if="post" class="post-content-area">
      <!-- 返回小组链接 -->
      <div class="back-to-group" v-if="post.group">
        <router-link :to="{ name: 'GroupDetail', params: { id: post.group.id } }">
          « 返回小组: {{ post.group.name }}
        </router-link>
      </div>

      <h1 class="post-detail-title">{{ post.title || '动态详情' }}</h1>
      <div class="post-detail-meta">
        <div class="author-info">
          <img 
            v-if="post.author && post.author.avatar_url" 
            :src="post.author.avatar_url" 
            alt="author avatar" 
            class="author-avatar-small"
          />
          <div v-else class="author-avatar-placeholder-small">{{ post.author ? post.author.nickname.charAt(0) : 'U' }}</div>
          <span class="author-name">{{ post.author ? post.author.nickname : '匿名用户' }}</span>
        </div>
        <span class="timestamp">发布于: {{ formatDateTime(post.created_at) }}</span>
        <span v-if="post.updated_at && post.updated_at !== post.created_at" class="timestamp">
          (编辑于: {{ formatDateTime(post.updated_at) }})
        </span>
      </div>
      
      <div class="post-detail-body" v-html="formatPostContent(post.content)"></div>

      <!-- 点赞区域 -->
      <div class="post-actions" v-if="authStore.isAuthenticated">
        <button 
          @click="toggleLikePost" 
          :disabled="isLikingPost"
          :class="{'liked': post.is_liked_by_current_user}" 
          class="like-button"
        >
          <svg v-if="!post.is_liked_by_current_user" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-heart" viewBox="0 0 16 16">
            <path d="m8 2.748-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 3.989 6.286 6.357 3.452-2.368 5.365-4.542 6.286-6.357.955-1.886.838-3.362.314-4.385C13.486.878 10.4.28 8.717 2.01zM8 15C-7.333 4.868 3.279-3.04 7.824 1.143q.09.083.176.171a3 3 0 0 1 .176-.17C12.72-3.042 23.333 4.867 8 15"/>
          </svg>
          <svg v-else xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-heart-fill" viewBox="0 0 16 16">
            <path fill-rule="evenodd" d="M8 1.314C12.438-3.248 23.534 4.735 8 15-7.534 4.736 3.562-3.248 8 1.314"/>
          </svg>
          {{ post.is_liked_by_current_user ? '已赞' : '赞' }} ({{ post.likes_count }})
        </button>
        <!-- 编辑/删除按钮 (仅作者可见) -->
        <div v-if="authStore.currentUser && post.author && authStore.currentUser.id === post.author.id" class="author-actions">
            <button @click="startEditPostMode" class="button-edit">编辑帖子</button>
            <button @click="confirmDeletePost" class="button-delete">删除帖子</button>
        </div>
      </div>
      <p v-if="likeError" class="error-message small-error">{{ likeError }}</p>
    </div>

    <!-- 编辑帖子表单 (条件渲染) -->
    <div v-if="isEditingPost" class="edit-post-form">
        <h3>编辑帖子</h3>
        <form @submit.prevent="handleUpdatePost">
            <div class="form-group">
                <label for="edit-post-title">标题 (可选):</label>
                <input type="text" id="edit-post-title" v-model="editablePost.title" maxlength="200">
            </div>
            <div class="form-group">
                <label for="edit-post-content">内容:</label>
                <textarea id="edit-post-content" v-model="editablePost.content" required></textarea>
            </div>
            <div class="form-actions">
                <button type="submit" :disabled="isSubmittingUpdate">
                    {{ isSubmittingUpdate ? '更新中...' : '保存更改' }}
                </button>
                <button type="button" @click="cancelEditPostMode" class="cancel-button">取消编辑</button>
            </div>
            <p v-if="updatePostError" class="error-message small-error">{{ updatePostError }}</p>
        </form>
    </div>


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

    <!-- 评论区 -->
    <div v-if="post" class="comments-section">
      <h3>评论 ({{ comments.length }})</h3>
      
      <!-- 发表评论表单 (仅登录用户可见) -->
      <form v-if="authStore.isAuthenticated" @submit.prevent="handleAddComment" class="add-comment-form">
        <div class="form-group">
          <textarea v-model="newCommentContent" placeholder="写下你的评论..." required></textarea>
        </div>
        <button type="submit" :disabled="isSubmittingComment">
          {{ isSubmittingComment ? '发表中...' : '发表评论' }}
        </button>
        <p v-if="addCommentError" class="error-message small-error">{{ addCommentError }}</p>
      </form>
      <p v-else class="info-message">
        <router-link :to="{ name: 'Login', query: { redirect: route.fullPath } }">登录</router-link>后才能发表评论。
      </p>

      <div v-if="isLoadingComments" class="loading-message">正在加载评论...</div>
      <div v-if="fetchCommentsError" class="error-message">{{ fetchCommentsError }}</div>
      
      <div v-if="comments.length > 0" class="comment-list">
        <div v-for="comment in comments" :key="comment.id" class="comment-item">
          <div class="comment-header">
             <img 
                v-if="comment.author && comment.author.avatar_url" 
                :src="comment.author.avatar_url" 
                alt="author avatar" 
                class="comment-author-avatar"
              />
              <div v-else class="comment-author-avatar-placeholder">{{ comment.author ? comment.author.nickname.charAt(0) : 'U' }}</div>
              <div class="comment-author-info">
                <span class="comment-author-name">{{ comment.author ? comment.author.nickname : '匿名用户' }}</span>
                <span class="comment-created-at">{{ formatDateTime(comment.created_at) }}</span>
              </div>
          </div>
          <p class="comment-content">{{ comment.content }}</p>
          <!-- (可选) 评论的点赞、回复、编辑、删除按钮 -->
        </div>
      </div>
      <p v-else-if="!isLoadingComments && !fetchCommentsError" class="info-message">暂无评论，快来抢沙发吧！</p>
    </div>

    <div v-if="!post && !isLoadingPost && !fetchPostError" class="not-found-message">
        <p>无法找到该帖子，或者帖子不存在。</p>
        <router-link :to="{ name: 'Home' }">返回首页</router-link> <!-- 或者返回小组列表 -->
    </div>
  </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';

const post = ref(null);
const isLoadingPost = ref(true);
const fetchPostError = ref('');

const comments = ref([]);
const isLoadingComments = ref(false);
const fetchCommentsError = ref('');

const newCommentContent = ref('');
const isSubmittingComment = ref(false);
const addCommentError = ref('');

const isLikingPost = ref(false);
const likeError = ref('');

const isEditingPost = ref(false);
const editablePost = reactive({ title: '', content: '' });
const isSubmittingUpdate = ref(false);
const updatePostError = ref('');


const authStore = useAuthStore();
const route = useRoute();
const router = useRouter();

const postId = computed(() => route.params.id);

// 获取帖子详情
const fetchPostDetail = async () => {
  isLoadingPost.value = true;
  fetchPostError.value = '';
  try {
    const response = await apiClient.get(`posts/${postId.value}/`); // 使用PostViewSet的retrieve
    post.value = response.data;
  } catch (error) {
    console.error('获取帖子详情失败:', error);
    fetchPostError.value = '无法加载帖子详情。';
    if (error.response && error.response.status === 404) {
        fetchPostError.value = '该帖子不存在或已被删除。';
    }
  } finally {
    isLoadingPost.value = false;
  }
};

// 获取帖子评论列表
const fetchPostComments = async () => {
  if (!postId.value) return;
  isLoadingComments.value = true;
  fetchCommentsError.value = '';
  try {
    // 使用PostViewSet中定义的action: posts/<pk>/comment-list/
    const response = await apiClient.get(`posts/${postId.value}/comment-list/`);
    comments.value = response.data.results || response.data; // 处理分页或直接列表
  } catch (error) {
    console.error('获取帖子评论失败:', error);
    fetchCommentsError.value = '无法加载评论。';
  } finally {
    isLoadingComments.value = false;
  }
};

// 添加评论
const handleAddComment = async () => {
  if (!newCommentContent.value.trim()) {
    addCommentError.value = '评论内容不能为空。';
    return;
  }
  if (!authStore.isAuthenticated) {
    addCommentError.value = '请先登录再发表评论。';
    return;
  }
  isSubmittingComment.value = true;
  addCommentError.value = '';
  try {
    // 使用PostViewSet中定义的action: posts/<pk>/comments/ (POST方法)
    const response = await apiClient.post(`posts/${postId.value}/comments/`, {
      content: newCommentContent.value,
    });
    comments.value.push(response.data); // 将新评论添加到列表底部
    newCommentContent.value = ''; // 清空输入框
  } catch (error) {
    console.error('发表评论失败:', error.response?.data || error.message);
    addCommentError.value = error.response?.data?.detail || Object.values(error.response?.data || {}).flat().join('; ') || '发表评论失败，请重试。';
  } finally {
    isSubmittingComment.value = false;
  }
};

// 点赞/取消点赞帖子
const toggleLikePost = async () => {
    if (!authStore.isAuthenticated || !post.value) return;
    isLikingPost.value = true;
    likeError.value = '';
    const actionUrl = post.value.is_liked_by_current_user ? 
                      `posts/${post.value.id}/unlike/` : 
                      `posts/${post.value.id}/like/`;
    try {
        const response = await apiClient.post(actionUrl); // 点赞/取消点赞都是POST
        // 后端返回了更新后的post对象，直接用它更新本地的post ref
        post.value = response.data; 
    } catch (error) {
        console.error('点赞/取消点赞失败:', error.response?.data || error.message);
        likeError.value = error.response?.data?.detail || '操作失败，请重试。';
    } finally {
        isLikingPost.value = false;
    }
};

// 编辑帖子相关
const startEditPostMode = () => {
    if (post.value) {
        editablePost.title = post.value.title || '';
        editablePost.content = post.value.content || '';
        isEditingPost.value = true;
        updatePostError.value = '';
    }
};
const cancelEditPostMode = () => {
    isEditingPost.value = false;
};
const handleUpdatePost = async () => {
    if (!editablePost.content.trim()) {
        updatePostError.value = "帖子内容不能为空。";
        return;
    }
    isSubmittingUpdate.value = true;
    updatePostError.value = '';
    try {
        const payload = {
            content: editablePost.content
        };
        if (editablePost.title !== (post.value?.title || '')) { // 只有标题改变了才发送
            payload.title = editablePost.title;
        }
        // 如果有图片上传，也需要用 FormData
        const response = await apiClient.patch(`posts/${postId.value}/`, payload);
        post.value = response.data; // 更新本地显示的帖子数据
        isEditingPost.value = false;
        alert('帖子更新成功！');
    } catch (error) {
        console.error('更新帖子失败:', error.response?.data || error.message);
        updatePostError.value = error.response?.data?.detail || Object.values(error.response?.data || {}).flat().join('; ') || '更新失败。';
    } finally {
        isSubmittingUpdate.value = false;
    }
};

// 删除帖子相关
const confirmDeletePost = async () => {
    if (post.value && window.confirm(`您确定要删除帖子 "${post.value.title || '该动态'}" 吗？此操作无法撤销。`)) {
        try {
            await apiClient.delete(`posts/${postId.value}/`);
            alert('帖子删除成功！');
            // 删除成功后跳转回小组详情页或首页
            if (post.value.group) {
                router.push({ name: 'GroupDetail', params: { id: post.value.group.id }});
            } else {
                router.push({ name: 'Home' });
            }
        } catch (error) {
            console.error('删除帖子失败:', error.response?.data || error.message);
            alert(error.response?.data?.detail || '删除失败，请重试。');
        }
    }
};


// 辅助函数
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '';
  const options = { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' };
  return new Date(dateTimeString).toLocaleDateString('zh-CN', options); // 使用中文区域设置
};

const formatPostContent = (content) => {
    if (!content) return '';
    // 简单地替换换行符为 <br> 以在HTML中显示换行
    // 更复杂的可以使用Markdown解析库
    return content.replace(/\n/g, '<br>');
};


// 组件挂载时获取数据
onMounted(async () => {
  await fetchPostDetail();
  if (post.value) { // 只有帖子存在才获取评论
    await fetchPostComments();
  }
});

// 监听路由参数变化，如果帖子ID变了，重新加载数据
watch(() => route.params.id, (newId, oldId) => {
  if (newId && newId !== oldId && route.name === 'PostDetail') { // 确保是当前路由
    fetchPostDetail();
    fetchPostComments();
  }
});
</script>

<style scoped>
.post-detail-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 25px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}
.loading-message, .error-message, .not-found-message, .info-message {
  text-align: center;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}
.error-message { background-color: #f8d7da; color: #721c24; }
.loading-message, .info-message { color: #555; }

.back-to-group {
    margin-bottom: 20px;
    font-size: 0.95em;
}
.back-to-group a {
    color: #007bff;
    text-decoration: none;
}
.back-to-group a:hover {
    text-decoration: underline;
}

.post-content-area, .comments-section, .edit-post-form {
  text-align: left;
}
.post-detail-title {
  font-size: 2em;
  margin-bottom: 10px;
  color: #333;
  word-wrap: break-word;
}
.post-detail-meta {
  display: flex;
  align-items: center;
  gap: 15px; /* 间距 */
  font-size: 0.9em;
  color: #666;
  margin-bottom: 25px;
  flex-wrap: wrap; /* 换行 */
}
.author-info {
    display: flex;
    align-items: center;
}
.author-avatar-small, .author-avatar-placeholder-small {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 8px;
  object-fit: cover;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: #777;
}
.author-name {
  font-weight: 600;
}
.timestamp {
    white-space: nowrap;
}
.post-detail-body {
  font-size: 1.05em;
  line-height: 1.7;
  color: #333;
  white-space: pre-wrap; /* 保留文本中的换行和空格 */
  word-wrap: break-word;
  margin-bottom: 30px;
}
.post-actions {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-bottom: 20px;
    padding-top: 15px;
    border-top: 1px solid #eee;
}
.like-button {
    display: inline-flex;
    align-items: center;
    padding: 8px 15px;
    border: 1px solid #ccc;
    background-color: #f8f8f8;
    color: #555;
    border-radius: 20px; /* 圆角按钮 */
    cursor: pointer;
    font-size: 0.9em;
    transition: background-color 0.2s, color 0.2s;
}
.like-button svg {
    margin-right: 6px;
}
.like-button.liked {
    background-color: #ffe0e6; /* 点赞后的背景色 */
    color: #e50040; /* 点赞后的颜色 (例如红色) */
    border-color: #ffc2ce;
}
.like-button:hover:not(.liked) {
    background-color: #eee;
}
.author-actions button {
    font-size: 0.85em;
    padding: 6px 10px;
    margin-left: 10px;
    border-radius: 4px;
    cursor: pointer;
}
.button-edit { background-color: #ffc107; color: #333; border: none;}
.button-delete { background-color: #dc3545; color: white; border: none;}

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

.comments-section h3 {
  font-size: 1.4em;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}
.add-comment-form {
  margin-bottom: 30px;
}
.add-comment-form .form-group {
  margin-bottom: 10px;
}
.add-comment-form textarea {
  width: 100%;
  min-height: 70px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  resize: vertical;
}
.add-comment-form button[type="submit"] {
  padding: 8px 18px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.add-comment-form button:disabled {
    background-color: #aaa;
}

.comment-list {
  margin-top: 20px;
}
.comment-item {
  padding: 15px;
  margin-bottom: 15px;
  background-color: #f9f9f9;
  border: 1px solid #e7e7e7;
  border-radius: 6px;
}
.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.comment-author-avatar, .comment-author-avatar-placeholder {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 10px;
  object-fit: cover;
  background-color: #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.9em;
  font-weight: bold;
  color: #777;
}
.comment-author-info {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.comment-author-name {
  font-weight: 600;
  font-size: 0.9em;
}
.comment-created-at {
  font-size: 0.75em;
  color: #888;
}
.comment-content {
  font-size: 0.95em;
  line-height: 1.6;
  color: #444;
  white-space: pre-line;
}
.error-message.small-error {
  font-size: 0.85em;
  padding: 8px;
  margin-top: 10px;
}
.edit-post-form {
    margin-top: 30px;
    padding: 20px;
    background-color: #f9f9f9;
    border: 1px solid #e7e7e7;
    border-radius: 8px;
}
.edit-post-form h3 {
    margin-top: 0;
    margin-bottom: 20px;
}
.edit-post-form .form-group { margin-bottom: 15px; }
.edit-post-form label { display: block; margin-bottom: 5px; font-weight: 500; }
.edit-post-form input[type="text"], .edit-post-form textarea {
    width: 100%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
}
.edit-post-form textarea { min-height: 100px; resize: vertical; }
.edit-post-form .form-actions { margin-top: 20px; display: flex; gap: 10px; }
.edit-post-form .form-actions button { padding: 8px 15px; }
.edit-post-form .cancel-button { background-color: #eee; color: #333; }
</style>