<template>
    <div class="post-detail-container">
        <!-- 作者信息栏 -->
        <div class="author-info" v-if="author && author.userName">
            <img 
                :src="author.userAvatar || require('@/assets/default-avatar/boy_1.png')" 
                alt="头像" 
                class="author-avatar"
                @click="goUserHome(author.userId)"
                style="cursor: pointer;"
            />
            <div class="author-details">
                <h3 class="author-name">{{ author.userName || '匿名用户' }}</h3>
                <p class="author-stats">粉丝数：{{ author.followers ?? 0 }}</p>
                <button @click="toggleFollow" class="follow-button">
                    {{ isFollowing ? '取消关注' : '关注' }}
                </button>
            </div>
        </div>

        <!-- 帖子内容 -->
        <div class="post-content">
            <img :src="author?.userAvatar || require('@/assets/default-avatar/boy_1.png')" alt="作者头像" class="post-author-avatar" />
            <h1 class="post-title">{{ postDetailStore.post?.title || '' }}</h1>
            <p class="post-body">{{ postDetailStore.post?.content || '' }}</p>
            <div class="post-stats">
                <span> 👁 {{ postDetailStore.post?.viewCount ?? 0 }}</span>
                <span> 🗨 {{ postDetailStore.post?.commentCount ?? 0 }}</span>
                <span>
                    <button
                        @click="postDetailStore.PostLike"
                        class="like-btn"
                        :class="{ liked: postDetailStore.isLike }"
                    >
                        <span v-if="!postDetailStore.isLike">♡</span>
                        <span v-else>♥</span>
                        {{ postDetailStore.post?.likeCount ?? 0 }}
                    </button>
                </span>
            </div>
            <div class="post-time">
                发布时间：{{ postDetailStore.post?.createTime ? formatTime(postDetailStore.post.createTime) : '' }}
            </div>
        </div>

        <!-- 评论区 -->
        <div class="comments-section">
            <h2 class="comments-title">评论</h2>
            <ul class="comments-list">
                <li v-for="comment in postDetailStore.comments" :key="comment.id" class="comment-item">
                    <img 
                        :src="comment.userAvatar || require('@/assets/default-avatar/boy_1.png')" 
                        alt="评论者头像" 
                        class="comment-avatar"
                        @click="goUserHome(comment.userId)" 
                        style="cursor: pointer;"
                    />
                    <div class="comment-content">
                        <p class="comment-name">{{ comment.userName || '匿名用户' }}</p>
                        <p class="comment-text">{{ comment.content || '' }}</p>
                        <div class="comment-meta">
                            <span class="comment-time">{{ comment.createTime ? formatTime(comment.createTime) : '' }}</span>
                            <button
                                @click="postDetailStore.CommentLike(comment)"
                                :class="['like-btn', { liked: comment.isLike }]"
                            >
                                <span v-if="!comment.isLike">♡</span>
                                <span v-else>♥</span>
                                {{ comment.likeCount ?? 0 }}
                            </button>
                            <span v-if="comment.replyCount > 0">
                            <button @click="loadReplies(comment)">
                                {{ comment.showReplies> 0 ? '收起回复' : '展开回复' }} ({{ comment.replyCount }})
                            </button>
                            </span>
                            <button class="reply-btn" @click="startReply(comment)">回复</button>
                            <button 
                                class="delete-btn" 
                                v-if="String(comment.userId) === String(userStore.userInfo?.userid)"
                                @click="handleDelete(comment)"
                            >删除</button>
                        </div>
                        <!-- 子评论列表 -->
                        <ul v-if="comment.showReplies && comment.replies && comment.replies.length > 0" class="replies-list">
                            <li v-for="reply in comment.replies" :key="reply.id" class="comment-item reply-item">
                                <img 
                                    :src="reply.userAvatar || require('@/assets/default-avatar/boy_1.png')" 
                                    alt="评论者头像" 
                                    class="comment-avatar"
                                    @click="goUserHome(reply.userId)"
                                    style="cursor: pointer;" 
                                    />
                                <div class="comment-content">
                                    <p class="comment-name">
                                        {{ reply.userName || '匿名用户' }}
                                        <span v-if="reply.replyUserName" class="reply-user">回复 @{{ reply.replyUserName }}</span>
                                    </p>
                                    <p class="comment-text">{{ reply.content || '' }}</p>
                                    <div class="comment-meta">
                                        <span class="comment-time">{{ reply.createTime ? formatTime(reply.createTime) : '' }}</span>
                                        <button
                                            @click="postDetailStore.CommentLike(reply)"
                                            :class="['like-btn', { liked: reply.isLike }]"
                                        >
                                            <span v-if="!reply.isLike">♡</span>
                                            <span v-else>♥</span>
                                            {{ reply.likeCount ?? 0 }}
                                        </button>
                                        <button class="reply-btn" @click="startReply(reply)">回复</button>
                                        <button 
                                            class="delete-btn" 
                                            v-if="String(reply.userId) === String(userStore.userInfo?.userid)"
                                            @click="handleDelete(reply)"
                                        >删除</button>
                                    </div>
                                </div>
                            </li>
                            <li v-if="comment.repliesLoading" class="reply-loading">加载中...</li>
                            <li v-if="comment.repliesFinished" class="reply-finished">没有更多回复了</li>
                        </ul>
                    </div>
                </li>
            </ul>
        </div>

        <!-- 发送评论 -->
        <div class="comment-box">
            <div v-if="replyingComment" class="replying-tip">
                正在回复 @{{ replyingComment.userName || '匿名用户' }}
                <button class="cancel-reply-btn" @click="cancelReply">取消回复</button>
            </div>
            <textarea
                v-model="newComment"
                placeholder="写下你的评论..."
                class="comment-input"
            ></textarea>
            <button @click="sendComment" class="send-button">发送</button>
        </div>
    </div>
</template>

<script setup lang="js" name="PostDetail">
import { ref, computed, onMounted , onUnmounted, watch } from 'vue';
import { useRoute,useRouter } from 'vue-router';
import { ElMessageBox } from 'element-plus';
import { usePostDetailStore } from '@/stores/postdetail.js';
import { useUserStore } from '@/stores/user.js';

const router = useRouter();
const route = useRoute();
const postDetailStore = usePostDetailStore();
const userStore = useUserStore();
const newComment = ref('');
const replyingComment = ref(null);

// 用计算属性保证 author 总是对象，避免 undefined
const author = computed(() => postDetailStore.post?.author || {});

const isFollowing = ref(false);
const toggleFollow = () => {
  isFollowing.value = !isFollowing.value;
};
const goUserHome = (userId) => {
  if (userId) router.push({name: 'UserPage',params: { userId: userId }})
}
function startReply(comment) {
  replyingComment.value = comment;
}
function cancelReply() {
  replyingComment.value = null;
}
function formatTime(timeStr) {
  const date = new Date(timeStr);
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
}

// 只有 postDetailStore.post 存在且有 postId 时才加载评论
function handleScroll() {
  const el = document.documentElement;
  if (
    el.scrollTop + window.innerHeight >= el.scrollHeight - 100 &&
    !postDetailStore.commentsLoading &&
    !postDetailStore.commentsFinished &&
    postDetailStore.post &&
    (postDetailStore.post.id || postDetailStore.post.postId)
  ) {
    postDetailStore.fetchComments();
  }
}
function loadReplies(comment) {
  // 如果已经展开，则收起
  if (comment.showReplies) {
    comment.showReplies = false;
    return;
  }
  // 否则展开并加载
  comment.showReplies = true;
  if (!comment.repliesLoading && !comment.repliesFinished && comment.replies.length === 0) {
    postDetailStore.fetchReplies(comment.id, comment);
  }
}

const sendComment = () => {
  if (!userStore.isLoggedIn) {
    alert('请先登录后再评论');
    return;
  }
  if (newComment.value.trim()) {
    const newCommentData = {
      content: newComment.value,
      userAvatar: userStore.userInfo.avatar,
      userName: userStore.userInfo.username,
      userId: userStore.userInfo.userid,
      createTime: new Date().toISOString(),
      likeCount: 0,
      replyCount: 0,
      postId: postDetailStore.post?.id || postDetailStore.post?.postId,
      parentCommentId: replyingComment.value ? replyingComment.value.id : null,
      replyUserName: replyingComment.value ? replyingComment.value.userName : null,
      topId: replyingComment.value ? replyingComment.value.topId : null,
      isLike: false,
    }
    postDetailStore.sendComment(newCommentData);
    newComment.value = '';
  }
};

function handleDelete(comment) {
  ElMessageBox.confirm(
    '确定要删除这条评论吗？',
    '提示',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    postDetailStore.deleteComment(comment);
  }).catch(() => {});
}
// 监听 postDetailStore.post 加载完成后再允许滚动加载评论
watch(
  () => postDetailStore.post,
  (val) => {
    if (val && (val.id || val.postId)) {
      postDetailStore.fetchComments();
    }
  },
  { immediate: true }
);

onMounted(() => {
  postDetailStore.fetchPostDetail(route.params.id);
  window.addEventListener('scroll', handleScroll);
});
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
});
</script>

<style scoped>
.post-detail-container {
    display: grid;
    grid-template-areas:
        "post-content author-info"
        "comments-section author-info"
        "comment-box author-info";
    grid-template-columns: 3fr 1fr; /* 左侧内容占 3/4，右侧作者信息占 1/4 */
    gap: 20px;
    padding: 20px;
    box-sizing: border-box;
    max-width: 1200px; /* 设置页面最大宽度 */
    margin: 0 auto; /* 居中页面并添加左右留白 */
}

.author-info {
    grid-area: author-info;
    display: flex;
    flex-direction: row; /* 水平排列头像和详情 */
    align-items: flex-start;
    background-color: #f5f5f5;
    padding: 20px;
    border: 1px solid #ccc;
    max-height: 200px;
    border-radius: 8px;
}

.author-avatar {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    object-fit: cover;
    margin-right: 15px; /* 与作者详情的间距 */
}

.author-details {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.author-name {
    font-size: 18px;
    margin: 0;
    }

.author-stats {
    font-size: 14px;
    color: #666;
    margin: 5px 0;
    text-align: left; /* 设置居左 */
}

.follow-button {
    margin-top: 10px;
    padding: 8px 16px;
    background-color: #5aa76f;
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 14px;
}

.follow-button:hover {
    background-color: #4a8a5a;
}

.post-content {
    grid-area: post-content;
    background-color: #ffffff;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 8px;
    position: relative; /* 为绝对定位的元素提供参考 */
}

.post-author-avatar {
    position: absolute;
    top: 20px;
    right: 20px;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid #ccc;
}

.post-title {
    font-size: 24px;
    margin-bottom: 10px;
    text-align: left; /* 设置居左 */
}

.post-body {
    font-size: 16px;
    line-height: 1.5;
    margin-bottom: 20px;
}

.post-stats {
    display: flex;
    gap: 15px; /* 图标之间的间距 */
    font-size: 14px;
    color: #666;
    margin-top: 20px;
    text-align: left; /* 设置居左 */
}

.post-time {
    position: absolute;
    bottom: 20px; /* 距离底部 20px */
    right: 20px; /* 距离右侧 20px */
    font-size: 12px;
    color: #999;
}

.comments-section {
    grid-area: comments-section;
    background-color: #ffffff;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 8px;
}

.comments-title {
    font-size: 20px;
    margin-bottom: 10px;
    text-align: left; /* 设置居左 */
    }

.comments-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.comment-item {
    display: flex;
    align-items: flex-start;
    padding: 10px;
    border-bottom: 1px solid #eee;
    font-size: 14px;
    position: relative;
}

.comment-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
    margin-right: 10px;
}

.comment-content {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.comment-name {
    font-weight: bold;
    margin-bottom: 5px;
}

.comment-text {
    margin: 0;
    font-size: 14px;
    color: #333;
}

.comment-meta {
    display: flex;
    justify-content: space-between;
    margin-top: 5px;
    font-size: 12px;
    color: #999;
}

.comment-time {
    font-size: 12px;
    color: #666;
}

.comment-likes {
    font-size: 12px;
    color: #666;
}

.comment-box {
    grid-area: comment-box;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.comment-input {
    width: 100%;
    height: 80px;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 8px;
    resize: none;
    font-size: 14px;
}

.send-button {
    align-self: flex-end;
    padding: 10px 20px;
    background-color: #5aa76f;
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 14px;
}

.send-button:hover {
    background-color: #4a8a5a;
}

.comment-name {
    
    font-size: 14px;
    font-weight: bold;
    margin: 0 0 5px 0; /* 与评论内容分隔 */
    text-align: left; /* 设置居左 */
    color: #333;
}

.replies-list {
    list-style: none;
    padding-left: 48px; /* 更明显的缩进 */
    margin: 8px 0 0 0;
    border-left: 2px solid #e0e0e0;
}

.reply-item {
    display: flex;
    align-items: flex-start;
    padding: 8px 0;
    border-bottom: 1px solid #f3f3f3;
    font-size: 13px;
    color: #444;
    background: #f9f9f9;
    border-radius: 4px;
    margin-bottom: 4px;
}

.reply-user {
    font-weight: normal;
    margin-left: 6px;
    color: #5aa76f;
    font-size: 13px;
}

.reply-content {
    flex: 1;
    color: #333;
    margin: 0;
    font-size: 14px;
    word-break: break-all;
}

.reply-loading,
.reply-finished {
    color: #999;
    font-size: 12px;
    padding: 6px 0;
    text-align: left;
}
.replying-tip {
    color: #409eff;
    margin-bottom: 6px;
    font-size: 14px;
}
.cancel-reply-btn {
    background: none;
    border: none;
    color: #f56c6c;
    margin-left: 8px;
    cursor: pointer;
    font-size: 13px;
}
.reply-btn {
    background: none;
    border: none;
    color: #409eff;
    cursor: pointer;
    font-size: 13px;
    margin-left: 10px;
}
.reply-btn:hover {
    text-decoration: underline;
}
.delete-btn {
  background: none;
  border: none;
  color: #f56c6c;
  cursor: pointer;
  font-size: 13px;
  margin-left: 10px;
}
.delete-btn:hover {
  text-decoration: underline;
}
.like-btn {
  margin-left: 8px;
  background: none;
  border: none;
  color: #409eff;
  cursor: pointer;
  font-size: 14px;
}
.like-btn.liked {
  color: #f56c6c;
}
</style>