<template>
    <div class="post-detail-container">
        <!-- 作者信息栏 -->
        <div class="author-info" v-if="author && author.userName">
            <img 
                :src="(author.userName === '匿名用户' || postDetailStore.post?.status === 1 ) 
                ? require('@/assets/default-avatar/boy_4.png') 
                : author.userAvatar|| require('@/assets/default-avatar/boy_1.png') "  
                alt="头像" 
                class="author-avatar"
                :style="{ cursor: (author.userName === '匿名用户' || postDetailStore.post?.status === 1 )  ? 'not-allowed' : 'pointer' }"
                @click="handleAuthorAvatarClick"
            />
            <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="main-content">
            <!-- 帖子内容 -->
            <div class="post-content">
                <img
                    v-if="postDetailStore.post?.image"
                    :src="postDetailStore.post.image"
                    alt="帖子封面"
                    class="post-cover"
                />
                <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-if="postDetailStore.comments.length === 0" class="comments-finished-tip">
                        暂时没有评论哦，快来发表吧！！！
                    </li>
                    <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>
                            <button 
                                class="delete-btn" 
                                v-if="String(comment.userId) === String(userStore.userInfo?.userid)"
                                @click="handleDelete(comment)"
                            >✖</button>
                            <div class="comment-meta">
                                <span class="comment-time">{{ comment.createTime ? formatTime(comment.createTime) : '' }}</span>
                                <button class="reply-btn" @click="startReply(comment)">回复</button>
                                <span v-if="comment.replyCount > 0">
                                <button @click="loadReplies(comment)" class="expand-reply-btn">
                                    {{ comment.showReplies> 0 ? '收起回复' : '展开回复' }} ({{ comment.replyCount }})
                                </button>
                                </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>
                            </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>
                                        <button 
                                            class="delete-btn" 
                                            v-if="String(reply.userId) === String(userStore.userInfo?.userid)"
                                            @click="handleDelete(reply)"
                                        >✖</button>
                                        <div class="comment-meta">
                                            <span class="comment-time">{{ reply.createTime ? formatTime(reply.createTime) : '' }}</span>
                                            <button class="reply-btn" @click="startReply(reply)">回复</button>
                                            <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> 
                                        </div>
                                    </div>
                                </li>
                                <li v-if="comment.repliesLoading" class="reply-loading">加载中...</li>
                                <li v-if="comment.repliesFinished" class="reply-finished">没有更多回复了</li>
                            </ul>
                        </div>
                    </li>
                    <li v-if="postDetailStore.comments.length > 0 && postDetailStore.commentsFinished" class="comments-finished-tip">
                        没有更多评论啦......
                    </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>
                <div style="position:relative;">
                    <textarea
                        v-model="newComment"
                        placeholder="写下你的评论..."
                        class="comment-input"
                    ></textarea>
                    <button @click="sendComment" class="send-button" style="position:absolute; right:16px; bottom:16px;">发送</button>
                </div>
            </div>
        </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, ElMessage } 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(() => {});
}

function handleAuthorAvatarClick() {
  // 判断用户名为匿名用户且头像为空时不跳转
  if (
    (author.value.userName === '匿名用户' || postDetailStore.post?.status === 1) &&
    (!author.value.userAvatar || author.value.userAvatar === '')
  ) {
    ElMessage.info('该用户为匿名用户');
    return;
  }
  goUserHome(author.value.userId);
}

// 监听 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:
        "main-content author-info";
    grid-template-columns: 3fr 1fr;
    gap: 20px;
    padding: 20px;
    box-sizing: border-box;
    max-width: 1200px;
    margin: 0 auto;
    height: 100vh;
}

.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;
}

.main-content {
    grid-area: main-content;
    display: flex;
    flex-direction: column;
    height: 100%;
    gap:20px;
    min-width: 0;
    min-height: 0;
}

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

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

.post-title {
    font-size: 32px;
    margin-bottom: 10px;
    text-align: left;
    padding-left: 5px; 
}

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

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

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

.comments-section {
    flex: 1 1 0;
    min-height: 0;
    background-color: #ffffff;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 8px;
    overflow-y: auto;
}

.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;
    padding-left: 12px; 
}

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

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

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

.comment-time {
    font-size: 12px;
    color: #666;
}
.expand-reply-btn {
    background: none;
    border: none;
    color: #409eff;
    cursor: pointer;
    font-size: 13px;
    padding: 2px 8px;
    z-index: 1;
}
.comment-likes {
    font-size: 12px;
    color: #666;
}
.comments-finished-tip {
    color: #999;
    font-size: 14px;
    text-align: center;
    padding: 16px 0 8px 0;
    letter-spacing: 1px;
}
.comment-box {
    display: flex;
    flex-direction: column;
    gap: 10px;
    background: #fff;
    padding: 6px 24px 12px 24px;
    box-shadow: 0 -2px 12px rgba(0,0,0,0.06);
    border-radius: 8px;
}

.comment-input {
    width: 100%;
    height: 80px;
    padding: 10px 80px 32px 10px; /* 右下留空间给按钮 */
    border: 1px solid #ccc;
    border-radius: 8px;
    resize: none;
    font-size: 14px;
    box-sizing: border-box;
}

.send-button {
    /* 位置已由内联style控制 */
    padding: 8px 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: 18px;
  margin-left: 10px;
  position: absolute;
  top: 0;
  right: 0;
  z-index: 2;
}
.delete-btn:hover {
  color: #ff2222;
  background: #f9eaea;
  border-radius: 50%;
}
.like-btn {
  margin-left: 8px;
  background: none;
  border: none;
  color: #222323;
  cursor: pointer;
  font-size: 14px;
}
.like-btn.liked {
  color: #f56c6c;
}

</style>