<template>
  <div class="forum-home">
    <h1>论坛管理</h1>

    <div class="controls">
      <input
          v-model="searchTitle"
          placeholder="搜索帖子标题"
          @keyup.enter="searchPosts"
          class="search-input"
      />
      <button @click="searchPosts" class="btn">搜索</button>
      <button @click="refreshPosts" class="btn btn-refresh">刷新</button>

      <!-- 查看全部举报按钮 -->
      <button @click="openAllReports" class="btn btn-report-all">查看全部举报</button>
    </div>

    <div v-if="loading" class="loading">加载中...</div>
    <div v-else>
      <ul class="posts-list">
        <li
            v-for="post in posts"
            :key="post.id"
            @click="goPostDetail(post.id)"
            class="post-card"
        >
          <!-- 红点 -->
          <span
              v-if="reportedPostIds.has(post.id)"
              class="red-dot"
              title="该帖子有举报"
          ></span>

          <h3 class="post-title">{{ post.title }}</h3>
          <p class="post-info">
            作者ID: {{ post.userId }} |
            用户名: {{ post.username }} |
            发布时间: {{ formatDateTime(post.createdAt) }}
          </p>

          <button class="btn btn-delete" @click.stop="deletePost(post.id)">
            删除
          </button>

          <button class="btn btn-report" @click.stop="openReportList(post)">
            查看举报
          </button>
        </li>
      </ul>

      <div v-if="posts.length === 0" class="no-data">无数据</div>
    </div>

    <!-- 单个帖子举报弹窗 -->
    <div
        v-if="showPostReportsModal"
        class="modal-overlay"
        @click.self="closePostReportList"
    >
      <div class="modal-content">
        <h3>举报列表 - 帖子：《{{ currentPost?.title }}》</h3>

        <div v-if="postReportLoading" class="loading">加载举报中...</div>
        <ul v-else-if="reportsForPost.length" class="report-list">
          <li v-for="report in reportsForPost" :key="report.id" class="report-item">
            <p><strong>举报人ID：</strong> {{ report.reporterId }}</p>
            <p><strong>举报内容：</strong> {{ report.reason }}</p>
            <p><strong>举报时间：</strong> {{ formatDateTime(report.createdAt) }}</p>
          </li>
        </ul>

        <div v-else class="no-data">暂无举报</div>

        <button class="btn btn-cancel" @click="closePostReportList">关闭</button>
      </div>
    </div>

    <!-- 查看所有举报弹窗 -->
    <div
        v-if="showAllReportsModal"
        class="modal-overlay"
        @click.self="closeAllReportList"
    >
      <div class="modal-content">
        <h3>全部举报列表</h3>

        <div v-if="allReportLoading" class="loading">加载举报中...</div>
        <ul v-else-if="allReports.length" class="report-list">
          <li v-for="report in allReports" :key="report.id" class="report-item">
            <p>
              <strong>被举报帖子：</strong>
              <span
                  class="report-post-title"
                  @click="goPostDetail(report.postId)"
                  title="点击查看帖子详情"
              >《{{ report.postTitle }}》</span
              >
            </p>
            <p>
              <strong>举报人：</strong> {{ report.reporterUsername }} (ID:
              {{ report.reporterId }})
            </p>
            <p><strong>举报内容：</strong> {{ report.reason }}</p>
            <p><strong>举报时间：</strong> {{ formatDateTime(report.createdAt) }}</p>
          </li>
        </ul>

        <div v-else class="no-data">暂无举报</div>

        <button class="btn btn-cancel" @click="closeAllReportList">关闭</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";
import dayjs from "dayjs";

const formatDateTime = (isoString) => {
  if (!isoString) return "";
  return dayjs(isoString).format("YYYY年MM月DD日 HH:mm:ss");
};

// 帖子列表及搜索
const searchTitle = ref("");
const posts = ref([]);
const loading = ref(false);

const router = useRouter();

// 新增：被举报帖子ID集合
const reportedPostIds = ref(new Set());

// 获取带举报帖子ID的函数
const fetchReportedPostIds = async () => {
  try {
    const res = await axios.get("http://localhost:8080/forum/post/reports", {
      params: { size: 1000 }, // 根据需要调整条数限制
    });
    // 假设接口返回格式如 [{id, postId, reporterId, reason, ...}, ...]
    const ids = res.data.map((report) => report.postId);
    reportedPostIds.value = new Set(ids);
  } catch (err) {
    console.error("获取带举报帖子ID失败:", err);
    reportedPostIds.value = new Set();
  }
};

const fetchPosts = async (title = "") => {
  loading.value = true;
  try {
    const res = await axios.get("http://localhost:8080/forum/posts", {
      params: { title },
    });
    posts.value = res.data;
    // 先拿帖子数据，再请求举报帖子ID
    await fetchReportedPostIds();
  } catch (err) {
    console.error(err);
    posts.value = [];
    reportedPostIds.value = new Set();
  } finally {
    loading.value = false;
  }
};

const searchPosts = () => {
  fetchPosts(searchTitle.value);
};

const refreshPosts = () => {
  fetchPosts(searchTitle.value);
};

const goPostDetail = (postId) => {
  router.push(`/post/${postId}`);
};

const deletePost = async (postId) => {
  if (!confirm("确定要删除该帖子吗？")) {
    return;
  }
  try {
    await axios.delete(`http://localhost:8080/forum/post/${postId}`);
    alert("删除成功");
    fetchPosts(searchTitle.value);
  } catch (error) {
    console.error(error);
    alert("删除失败");
  }
};

// **************** 单个帖子举报弹窗 ****************
const showPostReportsModal = ref(false);
const currentPost = ref(null);
const reportsForPost = ref([]);
const postReportLoading = ref(false);

const openReportList = async (post) => {
  currentPost.value = post;
  showPostReportsModal.value = true;
  postReportLoading.value = true;
  reportsForPost.value = [];
  try {
    const res = await axios.get(
        `http://localhost:8080/forum/post/reports/${post.id}`
    );
    reportsForPost.value = res.data || [];
  } catch (error) {
    console.error("获取帖子举报列表失败:", error);
    reportsForPost.value = [];
  } finally {
    postReportLoading.value = false;
  }
};

const closePostReportList = () => {
  showPostReportsModal.value = false;
  currentPost.value = null;
  reportsForPost.value = [];
};

// **************** 查看全部举报弹窗 ****************
const showAllReportsModal = ref(false);
const allReports = ref([]);
const allReportLoading = ref(false);

const openAllReports = async () => {
  showAllReportsModal.value = true;
  allReportLoading.value = true;
  allReports.value = [];
  try {
    const res = await axios.get("http://localhost:8080/forum/post/reports", {
      params: { size: 100 },
    });
    allReports.value = res.data || [];
  } catch (error) {
    console.error("获取全部举报失败:", error);
    allReports.value = [];
  } finally {
    allReportLoading.value = false;
  }
};

const closeAllReportList = () => {
  showAllReportsModal.value = false;
  allReports.value = [];
};

onMounted(() => {
  fetchPosts();
});
</script>

<style scoped>
.forum-home {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  color: #333;
}

.controls {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
  padding: 8px 12px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  transition: border-color 0.3s;
}
.search-input:focus {
  outline: none;
  border-color: #409eff;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.5);
}

.btn {
  padding: 8px 16px;
  border: none;
  background-color: #409eff;
  color: white;
  font-weight: 600;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}
.btn:hover {
  background-color: #66b1ff;
}
.btn-refresh {
  background-color: #67c23a;
}
.btn-refresh:hover {
  background-color: #85ce61;
}

.loading,
.no-data {
  font-size: 18px;
  text-align: center;
  color: #888;
  margin-top: 40px;
}

.posts-list {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.post-card {
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 16px 20px;
  box-shadow: 0 2px 6px rgb(0 0 0 / 0.05);
  cursor: pointer;
  transition: box-shadow 0.3s, border-color 0.3s;
  position: relative;
}
.post-card:hover {
  box-shadow: 0 8px 20px rgb(0 0 0 / 0.12);
  border-color: #409eff;
}

.post-title {
  margin: 0 0 8px;
  color: #409eff;
  font-weight: 700;
  font-size: 20px;
}

.post-info {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.btn-delete {
  position: absolute;
  top: 16px;
  right: 20px;
  background-color: #f56c6c;
  color: white;
  border: none;
  padding: 4px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 600;
  transition: background-color 0.3s;
  z-index: 10;
}
.btn-delete:hover {
  background-color: #f78989;
}

/* 新增举报按钮样式 */
.btn-report {
  position: absolute;
  top: 16px;
  right: 80px;
  background-color: #e6a23c;
  color: white;
  border: none;
  padding: 4px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 600;
  transition: background-color 0.3s;
  z-index: 10;
}
.btn-report:hover {
  background-color: #ebb563;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  width: 500px;
  max-width: 95%;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 4px 12px rgba(0,0,0,0.3);
}

.report-list {
  list-style: none;
  padding: 0;
  margin: 16px 0 0 0;
  max-height: 400px;
  overflow-y: auto;
  border-top: 1px solid #ebeef5;
}

.report-item {
  border-bottom: 1px solid #ebeef5;
  padding: 12px 0;
  font-size: 14px;
  color: #444;
}

.report-item p {
  margin: 4px 0;
}

.btn-cancel {
  background-color: #909399;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-top: 15px;
}
.btn-cancel:hover {
  background-color: #a6a9ad;
}

.btn-report-all {
  background-color: #f90;
  color: white;
  border: none;
  padding: 4px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 600;
  transition: background-color 0.3s;
  margin-left: 10px;
}
.btn-report-all:hover {
  background-color: #fb3;
}

.red-dot {
  position: absolute;
  top: 14px;
  left: 14px;
  width: 10px;
  height: 10px;
  background-color: #f56c6c;
  border-radius: 50%;
  box-shadow: 0 0 3px #f56c6c;
  z-index: 20;
}

.report-post-title {
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
}

.report-post-title:hover {
  color: #66b1ff;
}
</style>
<template>
  <div class="post-detail">
    <title>管理员详情页</title>
    <button @click="goBack" class="back-btn">返回主页</button>

    <h2 class="post-title">{{ post?.title }}</h2>
    <p class="post-info">
      作者: {{ post?.username || post?.userId }} |
      发布时间: {{ formatDateTime(post?.createdAt) }}
    </p>
    <p class="post-content monospace-content">{{ post?.content }}</p>

    <!-- 点赞 收藏 举报 按钮 -->
    <div class="post-actions">
      <button @click="toggleLike" :class="{ active: liked }" class="btn-like">
        {{ liked ? "已点赞" : "点赞" }} ({{ likeCount }})
      </button>
      <button @click="toggleFavorite" :class="{ active: favorited }" class="btn-favorite">
        {{ favorited ? "已收藏" : "收藏" }}
      </button>
      <button @click="openReportDialog" class="btn-report">
        举报
      </button>
    </div>

    <hr />

    <h3>评论区</h3>

    <div v-if="loadingComments" class="loading">加载评论中...</div>
    <div v-else>
      <ul class="comments-list">
        <li v-for="comment in rootComments" :key="comment.id" class="comment-item">
          <div class="comment-main">
            <div class="comment-header">
              <b>{{ comment.username || ("用户ID: " + comment.userId) }}</b>
              <span v-if="comment.createdAt" class="comment-time"
              >评论时间 {{ formatDateTime(comment.createdAt) }}</span
              >

              <!-- 统一删除按钮 -->
              <button
                  @click="adminDeleteComment(comment.id)"
                  class="btn-delete"
                  title="删除评论及其子评论"
              >
                删除
              </button>

              <button @click="toggleReplyBox(comment.id)" class="btn-reply">
                {{ replyingTo === comment.id ? "取消回复" : "回复" }}
              </button>

              <button @click="toggleRepliesCollapse(comment.id)" class="btn-collapse">
                {{ repliesCollapsed[comment.id] ? "展开回复" : "收起回复" }}
              </button>
            </div>

            <p class="comment-content monospace-content">{{ comment.content }}</p>

            <div v-if="replyingTo === comment.id" class="reply-box">
              <el-input
                  v-model="replyContent"
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 12 }"
                  placeholder="回复内容"
                  style="width: 100%;"
                  class="autosize-textarea monospace-textarea"
              />
              <button class="btn-submit" @click="submitReply(comment.id)">提交回复</button>
            </div>
          </div>

          <ul
              v-if="!repliesCollapsed[comment.id] && flattenReplies[comment.id]?.length"
              class="replies-list"
          >
            <li
                v-for="reply in flattenReplies[comment.id]"
                :key="reply.id"
                class="comment-reply"
            >
              <div class="comment-header">
                <b>{{ reply.username || ("用户ID: " + reply.userId) }}</b>
                <span class="comment-time"
                >回复时间 {{ formatDateTime(reply.createdAt) }}</span
                >

                <span class="reply-to" v-if="reply.parentCommentId">
                  回复 <b>{{ rootCommentUsernames[comment.id] }}</b>
                </span>

                <!-- 统一删除回复按钮 -->
                <button
                    @click="adminDeleteComment(reply.id)"
                    class="btn-delete"
                    title="删除回复及其子回复"
                >
                  删除
                </button>

                <button @click="toggleReplyBox(reply.id)" class="btn-reply">
                  {{ replyingTo === reply.id ? "取消回复" : "回复" }}
                </button>
              </div>

              <p class="comment-content monospace-content">
                {{ reply.content }}
              </p>

              <div v-if="replyingTo === reply.id" class="reply-box">
                <el-input
                    v-model="replyContent"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 12 }"
                    placeholder="回复内容"
                    style="width: 100%;"
                    class="autosize-textarea monospace-textarea"
                />
                <button class="btn-submit" @click="submitReply(reply.id)">
                  提交回复
                </button>
              </div>
            </li>
          </ul>
        </li>
      </ul>

      <hr />

      <h4>发表评论</h4>
      <el-input
          v-model="newComment"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 12 }"
          placeholder="请输入评论内容"
          class="new-comment-textarea autosize-textarea monospace-textarea"
          style="width: 100%;"
      />
      <button class="btn-submit" @click="submitComment">提交评论</button>
    </div>

    <el-dialog v-model="reportDialogVisible" title="举报帖子" width="400px">
      <el-input
          v-model="reportReason"
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 12 }"
          placeholder="请输入举报原因"
          style="width: 100%;"
          class="autosize-textarea monospace-textarea"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="reportDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReport">提交举报</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import axios from "axios";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";

const formatDateTime = (isoString) => {
  if (!isoString) return "";
  return dayjs(isoString).format("YYYY年MM月DD日 HH:mm:ss");
};

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

const postId = Number(route.params.id);
const post = ref(null);
const comments = ref([]);
const loadingComments = ref(false);
const userId = localStorage.getItem("userId");

const newComment = ref("");
const replyingTo = ref(null);
const replyContent = ref("");
const repliesCollapsed = ref({});

// 点赞收藏举报相关
const liked = ref(false);
const likeCount = ref(0);
const favorited = ref(false);
const reportDialogVisible = ref(false);
const reportReason = ref("");

const fetchPost = async () => {
  try {
    const res = await axios.get(`http://localhost:8080/forum/post/${postId}`);
    post.value = res.data;
    likeCount.value = res.data.likeCount || 0;
  } catch (error) {
    ElMessage.error("加载帖子详情失败");
    router.back();
  }
};

const fetchComments = async () => {
  loadingComments.value = true;
  try {
    const res = await axios.get(`http://localhost:8080/forum/comments/${postId}`);
    comments.value = res.data;
  } catch (error) {
    ElMessage.error("加载评论失败");
  } finally {
    loadingComments.value = false;
  }
};

const fetchLikeStatus = async () => {
  if (!userId) return;
  try {
    const res = await axios.get(`http://localhost:8080/forum/post/like/status`, {
      params: { userId, postId }
    });
    liked.value = res.data.liked;
  } catch (error) {
    console.error("查询点赞状态失败", error);
  }
};

const fetchFavoriteStatus = async () => {
  if (!userId) return;
  try {
    const res = await axios.get(`http://localhost:8080/forum/post/favorite/status`, {
      params: { userId, postId }
    });
    favorited.value = res.data.favorited;
  } catch (error) {
    console.error("查询收藏状态失败", error);
  }
};

const toggleRepliesCollapse = (commentId) => {
  repliesCollapsed.value[commentId] = !repliesCollapsed.value[commentId];
};

const goBack = () => {
  router.back();
};

const submitComment = async () => {
  const content = newComment.value.trim();
  if (!content) {
    ElMessage.warning("请输入评论内容");
    return;
  }
  try {
    await axios.post("http://localhost:8080/forum/comment", {
      postId,
      userId,
      content,
      parentCommentId: null,
    });
    ElMessage.success("评论成功");
    newComment.value = "";
    fetchComments();
  } catch (error) {
    ElMessage.error("发表评论失败");
  }
};

const toggleReplyBox = (commentId) => {
  if (replyingTo.value === commentId) {
    replyingTo.value = null;
    replyContent.value = "";
  } else {
    replyingTo.value = commentId;
    replyContent.value = "";
  }
};

const submitReply = async (parentCommentId) => {
  const content = replyContent.value.trim();
  if (!content) {
    ElMessage.warning("请输入回复内容");
    return;
  }
  try {
    await axios.post("http://localhost:8080/forum/comment", {
      postId,
      userId,
      content,
      parentCommentId,
    });
    ElMessage.success("回复成功");
    replyingTo.value = null;
    replyContent.value = "";
    fetchComments();
  } catch (error) {
    ElMessage.error("回复失败");
  }
};

// 这里是你需要的管理员专用删除接口调用
const adminDeleteComment = async (commentId) => {
  try {
    await ElMessageBox.confirm("确认删除此评论及其所有子评论？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    await axios.delete(`http://localhost:8080/forum/admin/comment/${commentId}`);
    ElMessage.success("删除成功");
    fetchComments();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

const toggleLike = async () => {
  if (!userId) {
    ElMessage.warning("请先登录");
    return;
  }
  try {
    if (!liked.value) {
      await axios.post("http://localhost:8080/forum/post/like", { userId, postId });
      liked.value = true;
      likeCount.value++;
      ElMessage.success("点赞成功");
    } else {
      await axios.delete("http://localhost:8080/forum/post/like", { params: { userId, postId } });
      liked.value = false;
      likeCount.value--;
      ElMessage.success("取消点赞成功");
    }
  } catch {
    ElMessage.error("点赞操作失败");
  }
};

const toggleFavorite = async () => {
  if (!userId) {
    ElMessage.warning("请先登录");
    return;
  }
  try {
    if (!favorited.value) {
      await axios.post("http://localhost:8080/forum/post/favorite", { userId, postId });
      favorited.value = true;
      ElMessage.success("收藏成功");
    } else {
      await axios.delete("http://localhost:8080/forum/post/favorite", { params: { userId, postId } });
      favorited.value = false;
      ElMessage.success("取消收藏成功");
    }
  } catch {
    ElMessage.error("收藏操作失败");
  }
};

const openReportDialog = () => {
  if (!userId) {
    ElMessage.warning("请先登录");
    return;
  }
  reportReason.value = "";
  reportDialogVisible.value = true;
};

const submitReport = async () => {
  if (!reportReason.value.trim()) {
    ElMessage.warning("请输入举报原因");
    return;
  }
  try {
    await axios.post("http://localhost:8080/forum/post/report", {
      reporterId: userId,
      postId,
      reason: reportReason.value,
    });
    ElMessage.success("举报成功，管理员会尽快处理");
    reportDialogVisible.value = false;
  } catch {
    ElMessage.error("举报失败");
  }
};

// 计算一级评论（parentCommentId === null）
const rootComments = computed(() =>
    comments.value
        .filter((c) => !c.parentCommentId)
        .sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt))
);

// flattenReplies: 二级及以上回复折叠到一级评论
const flattenReplies = computed(() => {
  const map = {};
  rootComments.value.forEach((root) => {
    map[root.id] = [];
  });
  comments.value.forEach((c) => {
    if (c.parentCommentId) {
      let parentId = c.parentCommentId;
      let current = comments.value.find((cc) => cc.id === parentId);
      while (current && current.parentCommentId) {
        parentId = current.parentCommentId;
        current = comments.value.find((cc) => cc.id === parentId);
      }
      if (map[parentId]) {
        map[parentId].push(c);
      }
    }
  });
  Object.values(map).forEach((list) =>
      list.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt))
  );
  return map;
});

const rootCommentUsernames = computed(() => {
  const map = {};
  rootComments.value.forEach((root) => {
    map[root.id] = root.username || `用户ID: ${root.userId}`;
  });
  return map;
});

onMounted(() => {
  fetchPost();
  fetchComments();
  fetchLikeStatus();
  fetchFavoriteStatus();
});
</script>

<style scoped>
.post-detail {
  max-width: 800px;
  margin: auto;
  padding: 20px;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
  color: #222;
  background: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgb(0 0 0 / 0.1);
}

.back-btn {
  background: none;
  border: none;
  color: #409eff;
  font-size: 16px;
  cursor: pointer;
  margin-bottom: 10px;
  padding: 0;
  transition: color 0.3s;
}
.back-btn:hover {
  color: #66b1ff;
}

.post-title {
  margin-bottom: 8px;
  color: #303133;
  font-weight: 700;
}

.post-info {
  margin-bottom: 20px;
  color: #909399;
  font-size: 14px;
}

/* 内容显示用等宽字体，保留换行和空格 */
.post-content.monospace-content,
.comment-content.monospace-content {
  font-family: monospace, "Courier New", Courier, monospace !important;
  white-space: pre-wrap !important;
  word-break: break-word !important;
  overflow-wrap: break-word !important;
}

.post-content {
  background: white;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 30px;
  line-height: 1.5;
  box-shadow: inset 0 0 8px rgb(0 0 0 / 0.03);
}

.post-actions {
  margin: 10px 0 20px;
  display: flex;
  gap: 12px;
}
.post-actions button {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 14px;
  background-color: #f0f2f5;
  border: 1px solid #dcdfe6;
  border-radius: 18px;
  font-size: 14px;
  font-weight: 600;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s ease;
  user-select: none;
}

.btn-like.active,
.btn-favorite.active {
  color: #f56c6c;
}

.comments-list,
.replies-list {
  list-style-type: none;
  padding-left: 0;
  margin: 0;
}

.comment-item {
  background: white;
  border-radius: 6px;
  padding: 14px 20px;
  margin-bottom: 16px;
  box-shadow: 0 1px 3px rgb(0 0 0 / 0.1);
}

.comment-main {
  position: relative;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
  font-size: 14px;
  margin-bottom: 8px;
}

.comment-header b {
  color: #409eff;
  font-weight: 600;
}

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

.reply-to {
  color: #606266;
  font-size: 12px;
  margin-left: 4px;
}

/* 评论文字等宽 */
.comment-content {
  font-size: 15px;
  color: #606266;
  line-height: 1.5;
  margin: 0;
  padding-left: 4px;
}

/* 回复框及发表评论输入框等宽字体 */
.autosize-textarea.monospace-textarea .el-textarea__inner {
  font-family: monospace, "Courier New", Courier, monospace !important;
  white-space: pre-wrap !important;
  word-break: break-word !important;
  overflow-wrap: break-word !important;
  resize: vertical;
}

.reply-box {
  margin-top: 8px;
  width: 100%;
}

/* 让 el-input 宽度撑满容器 */
.reply-box .autosize-textarea,
.new-comment-textarea.autosize-textarea {
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
}

.btn-delete,
.btn-reply,
.btn-submit,
.btn-collapse {
  background: none;
  border: none;
  color: #409eff;
  cursor: pointer;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 13px;
  transition: background-color 0.3s;
  user-select: none;
}

.btn-delete {
  color: #f56c6c;
}
.btn-delete:hover {
  background-color: #fde2e2;
}

.btn-reply:hover,
.btn-submit:hover,
.btn-collapse:hover {
  background-color: #ecf5ff;
  color: #66b1ff;
}

.reply-box .btn-submit {
  margin-top: 6px;
  font-weight: 600;
}

.replies-list {
  margin-top: 10px;
  padding-left: 30px;
  border-left: 2px solid #ebeef5;
}

.comment-reply {
  background: #f5f7fa;
  border-radius: 6px;
  padding: 10px 16px;
  margin-bottom: 12px;
  box-shadow: inset 0 1px 3px rgb(0 0 0 / 0.03);
}

.new-comment-textarea {
  margin-bottom: 10px;
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  padding: 8px 10px;
  font-size: 15px;
  resize: vertical;
}

.btn-submit {
  background-color: #409eff;
  color: white;
  border-radius: 4px;
  padding: 8px 18px;
  font-weight: 600;
  transition: background-color 0.3s;
}
.btn-submit:hover {
  background-color: #66b1ff;
}

.loading {
  font-size: 16px;
  color: #909399;
  text-align: center;
  padding: 20px 0;
}

.post-actions button:hover {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

.post-actions button.active {
  background-color: #bae7ff;
  border-color: #40a9ff;
  color: #096dd9;
  box-shadow: 0 0 6px rgb(24 144 255 / 0.6);
}

/* 点赞按钮单独颜色 */
.btn-like {
  color: #fa541c;
  border-color: #ffa39e;
}
.btn-like.active {
  background-color: #ffccc7;
  border-color: #ff4d4f;
  color: #a8071a;
  box-shadow: 0 0 6px rgb(255 77 79 / 0.8);
}

/* 收藏按钮单独颜色 */
.btn-favorite {
  color: #faad14;
  border-color: #ffe58f;
}
.btn-favorite.active {
  background-color: #fff7e6;
  border-color: #ffc53d;
  color: #ad6800;
  box-shadow: 0 0 6px rgb(255 197 0 / 0.8);
}

/* 举报按钮采用警告色 */
.btn-report {
  color: #f5222d;
  border-color: #ffccc7;
}
.btn-report:hover {
  background-color: #fff1f0;
  border-color: #ff4d4f;
  color: #a8071a;
  box-shadow: 0 0 6px rgb(255 77 79 / 0.8);
}
</style>
<template>
  <div class="post-detail">
    <title>用户详情页</title>
    <button @click="goBack" class="back-btn">返回主页</button>

    <h2 class="post-title">{{ post?.title }}</h2>
    <p class="post-info">
      作者: {{ post?.username || post?.userId }} |
      发布时间: {{ formatDateTime(post?.createdAt) }}
    </p>
    <p class="post-content monospace-content">{{ post?.content }}</p>

    <!-- 点赞 收藏 举报 按钮 -->
    <div class="post-actions">
      <button @click="toggleLike" :class="{ active: liked }" class="btn-like">
        {{ liked ? "已点赞" : "点赞" }} ({{ likeCount }})
      </button>
      <button @click="toggleFavorite" :class="{ active: favorited }" class="btn-favorite">
        {{ favorited ? "已收藏" : "收藏" }}
      </button>
      <button @click="openReportDialog" class="btn-report">
        举报
      </button>
    </div>

    <hr />

    <h3>评论区</h3>

    <div v-if="loadingComments" class="loading">加载评论中...</div>
    <div v-else>
      <ul class="comments-list">
        <li v-for="comment in rootComments" :key="comment.id" class="comment-item">
          <div class="comment-main">
            <div class="comment-header">
              <b>{{ comment.username || ("用户ID: " + comment.userId) }}</b>
              <span v-if="comment.createdAt" class="comment-time"
              >评论时间 {{ formatDateTime(comment.createdAt) }}</span
              >
              <button
                  v-if="comment.userId == userId"
                  @click="deleteComment(comment.id)"
                  class="btn-delete"
                  title="删除评论"
              >
                删除
              </button>

              <button @click="toggleReplyBox(comment.id)" class="btn-reply">
                {{ replyingTo === comment.id ? "取消回复" : "回复" }}
              </button>

              <button @click="toggleRepliesCollapse(comment.id)" class="btn-collapse">
                {{ repliesCollapsed[comment.id] ? "展开回复" : "收起回复" }}
              </button>
            </div>

            <p class="comment-content monospace-content">{{ comment.content }}</p>

            <div v-if="replyingTo === comment.id" class="reply-box">
              <el-input
                  v-model="replyContent"
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 12 }"
                  placeholder="回复内容"
                  style="width: 100%;"
                  class="autosize-textarea monospace-textarea"
              />
              <button class="btn-submit" @click="submitReply(comment.id)">提交回复</button>
            </div>
          </div>

          <ul
              v-if="!repliesCollapsed[comment.id] && flattenReplies[comment.id]?.length"
              class="replies-list"
          >
            <li
                v-for="reply in flattenReplies[comment.id]"
                :key="reply.id"
                class="comment-reply"
            >
              <div class="comment-header">
                <b>{{ reply.username || ("用户ID: " + reply.userId) }}</b>
                <span class="comment-time"
                >回复时间 {{ formatDateTime(reply.createdAt) }}</span
                >

                <span class="reply-to" v-if="reply.parentCommentId">
                  回复 <b>{{ rootCommentUsernames[comment.id] }}</b>
                </span>

                <button
                    v-if="reply.userId == userId"
                    @click="deleteComment(reply.id)"
                    class="btn-delete"
                    title="删除回复"
                >
                  删除
                </button>

                <button @click="toggleReplyBox(reply.id)" class="btn-reply">
                  {{ replyingTo === reply.id ? "取消回复" : "回复" }}
                </button>
              </div>

              <p class="comment-content monospace-content">
                {{ reply.content }}
              </p>

              <div v-if="replyingTo === reply.id" class="reply-box">
                <el-input
                    v-model="replyContent"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 12 }"
                    placeholder="回复内容"
                    style="width: 100%;"
                    class="autosize-textarea monospace-textarea"
                />
                <button class="btn-submit" @click="submitReply(reply.id)">
                  提交回复
                </button>
              </div>
            </li>
          </ul>
        </li>
      </ul>

      <hr />

      <h4>发表评论</h4>
      <el-input
          v-model="newComment"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 12 }"
          placeholder="请输入评论内容"
          class="new-comment-textarea autosize-textarea monospace-textarea"
          style="width: 100%;"
      />
      <button class="btn-submit" @click="submitComment">提交评论</button>
    </div>

    <el-dialog v-model="reportDialogVisible" title="举报帖子" width="400px">
      <el-input
          v-model="reportReason"
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 12 }"
          placeholder="请输入举报原因"
          style="width: 100%;"
          class="autosize-textarea monospace-textarea"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="reportDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReport">提交举报</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import axios from "axios";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";

const formatDateTime = (isoString) => {
  if (!isoString) return "";
  return dayjs(isoString).format("YYYY年MM月DD日 HH:mm:ss");
};

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

const postId = Number(route.params.id);
const post = ref(null);
const comments = ref([]);
const loadingComments = ref(false);
const userId = localStorage.getItem("userId");

const newComment = ref("");
const replyingTo = ref(null);
const replyContent = ref("");
const repliesCollapsed = ref({});

// 点赞收藏举报相关
const liked = ref(false);
const likeCount = ref(0);
const favorited = ref(false);
const reportDialogVisible = ref(false);
const reportReason = ref("");

const fetchPost = async () => {
  try {
    const res = await axios.get(`http://localhost:8080/forum/post/${postId}`);
    post.value = res.data;
    likeCount.value = res.data.likeCount || 0;
  } catch (error) {
    ElMessage.error("加载帖子详情失败");
    router.back();
  }
};

const fetchComments = async () => {
  loadingComments.value = true;
  try {
    const res = await axios.get(`http://localhost:8080/forum/comments/${postId}`);
    comments.value = res.data;
  } catch (error) {
    ElMessage.error("加载评论失败");
  } finally {
    loadingComments.value = false;
  }
};

const fetchLikeStatus = async () => {
  if (!userId) return;
  try {
    const res = await axios.get(`http://localhost:8080/forum/post/like/status`, {
      params: { userId, postId }
    });
    liked.value = res.data.liked;
  } catch (error) {
    console.error("查询点赞状态失败", error);
  }
};

const fetchFavoriteStatus = async () => {
  if (!userId) return;
  try {
    const res = await axios.get(`http://localhost:8080/forum/post/favorite/status`, {
      params: { userId, postId }
    });
    favorited.value = res.data.favorited;
  } catch (error) {
    console.error("查询收藏状态失败", error);
  }
};

const toggleRepliesCollapse = (commentId) => {
  repliesCollapsed.value[commentId] = !repliesCollapsed.value[commentId];
};

const goBack = () => {
  router.back();
};

const submitComment = async () => {
  const content = newComment.value.trim();
  if (!content) {
    ElMessage.warning("请输入评论内容");
    return;
  }
  try {
    await axios.post("http://localhost:8080/forum/comment", {
      postId,
      userId,
      content,
      parentCommentId: null,
    });
    ElMessage.success("评论成功");
    newComment.value = "";
    fetchComments();
  } catch (error) {
    ElMessage.error("发表评论失败");
  }
};

const toggleReplyBox = (commentId) => {
  if (replyingTo.value === commentId) {
    replyingTo.value = null;
    replyContent.value = "";
  } else {
    replyingTo.value = commentId;
    replyContent.value = "";
  }
};

const submitReply = async (parentCommentId) => {
  const content = replyContent.value.trim();
  if (!content) {
    ElMessage.warning("请输入回复内容");
    return;
  }
  try {
    await axios.post("http://localhost:8080/forum/comment", {
      postId,
      userId,
      content,
      parentCommentId,
    });
    ElMessage.success("回复成功");
    replyingTo.value = null;
    replyContent.value = "";
    fetchComments();
  } catch (error) {
    ElMessage.error("回复失败");
  }
};

const deleteComment = async (commentId) => {
  try {
    await ElMessageBox.confirm("确定删除此评论吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    await axios.delete(`http://localhost:8080/forum/comment/${commentId}`);
    ElMessage.success("删除成功");
    fetchComments();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

const toggleLike = async () => {
  if (!userId) {
    ElMessage.warning("请先登录");
    return;
  }
  try {
    if (!liked.value) {
      await axios.post("http://localhost:8080/forum/post/like", { userId, postId });
      liked.value = true;
      likeCount.value++;
      ElMessage.success("点赞成功");
    } else {
      await axios.delete("http://localhost:8080/forum/post/like", { params: { userId, postId } });
      liked.value = false;
      likeCount.value--;
      ElMessage.success("取消点赞成功");
    }
  } catch {
    ElMessage.error("点赞操作失败");
  }
};

const toggleFavorite = async () => {
  if (!userId) {
    ElMessage.warning("请先登录");
    return;
  }
  try {
    if (!favorited.value) {
      await axios.post("http://localhost:8080/forum/post/favorite", { userId, postId });
      favorited.value = true;
      ElMessage.success("收藏成功");
    } else {
      await axios.delete("http://localhost:8080/forum/post/favorite", { params: { userId, postId } });
      favorited.value = false;
      ElMessage.success("取消收藏成功");
    }
  } catch {
    ElMessage.error("收藏操作失败");
  }
};

const openReportDialog = () => {
  if (!userId) {
    ElMessage.warning("请先登录");
    return;
  }
  reportReason.value = "";
  reportDialogVisible.value = true;
};

const submitReport = async () => {
  if (!reportReason.value.trim()) {
    ElMessage.warning("请输入举报原因");
    return;
  }
  try {
    await axios.post("http://localhost:8080/forum/post/report", {
      reporterId: userId,
      postId,
      reason: reportReason.value,
    });
    ElMessage.success("举报成功，管理员会尽快处理");
    reportDialogVisible.value = false;
  } catch {
    ElMessage.error("举报失败");
  }
};

// 计算一级评论（parentCommentId === null）
const rootComments = computed(() =>
    comments.value
        .filter((c) => !c.parentCommentId)
        .sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt))
);

// flattenReplies: 二级及以上回复折叠到一级评论
const flattenReplies = computed(() => {
  const map = {};
  rootComments.value.forEach((root) => {
    map[root.id] = [];
  });
  comments.value.forEach((c) => {
    if (c.parentCommentId) {
      let parentId = c.parentCommentId;
      let current = comments.value.find((cc) => cc.id === parentId);
      while (current && current.parentCommentId) {
        parentId = current.parentCommentId;
        current = comments.value.find((cc) => cc.id === parentId);
      }
      if (map[parentId]) {
        map[parentId].push(c);
      }
    }
  });
  Object.values(map).forEach((list) =>
      list.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt))
  );
  return map;
});

const rootCommentUsernames = computed(() => {
  const map = {};
  rootComments.value.forEach((root) => {
    map[root.id] = root.username || `用户ID: ${root.userId}`;
  });
  return map;
});

onMounted(() => {
  fetchPost();
  fetchComments();
  fetchLikeStatus();
  fetchFavoriteStatus();
});
</script>

<style scoped>
.post-detail {
  max-width: 800px;
  margin: auto;
  padding: 20px;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
  color: #222;
  background: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgb(0 0 0 / 0.1);
}

.back-btn {
  background: none;
  border: none;
  color: #409eff;
  font-size: 16px;
  cursor: pointer;
  margin-bottom: 10px;
  padding: 0;
  transition: color 0.3s;
}
.back-btn:hover {
  color: #66b1ff;
}

.post-title {
  margin-bottom: 8px;
  color: #303133;
  font-weight: 700;
}

.post-info {
  margin-bottom: 20px;
  color: #909399;
  font-size: 14px;
}

/* 内容显示用等宽字体，保留换行和空格 */
.post-content.monospace-content,
.comment-content.monospace-content {
  font-family: monospace, "Courier New", Courier, monospace !important;
  white-space: pre-wrap !important;
  word-break: break-word !important;
  overflow-wrap: break-word !important;
}

.post-content {
  background: white;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 30px;
  line-height: 1.5;
  box-shadow: inset 0 0 8px rgb(0 0 0 / 0.03);
}

.post-actions {
  margin: 10px 0 20px;
  display: flex;
  gap: 12px;
}
.post-actions button {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 14px;
  background-color: #f0f2f5;
  border: 1px solid #dcdfe6;
  border-radius: 18px;
  font-size: 14px;
  font-weight: 600;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s ease;
  user-select: none;
}

.btn-like.active,
.btn-favorite.active {
  color: #f56c6c;
}

.comments-list,
.replies-list {
  list-style-type: none;
  padding-left: 0;
  margin: 0;
}

.comment-item {
  background: white;
  border-radius: 6px;
  padding: 14px 20px;
  margin-bottom: 16px;
  box-shadow: 0 1px 3px rgb(0 0 0 / 0.1);
}

.comment-main {
  position: relative;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
  font-size: 14px;
  margin-bottom: 8px;
}

.comment-header b {
  color: #409eff;
  font-weight: 600;
}

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

.reply-to {
  color: #606266;
  font-size: 12px;
  margin-left: 4px;
}

/* 评论文字等宽 */
.comment-content {
  font-size: 15px;
  color: #606266;
  line-height: 1.5;
  margin: 0;
  padding-left: 4px;
}

/* 回复框及发表评论输入框等宽字体 */
.autosize-textarea.monospace-textarea .el-textarea__inner {
  font-family: monospace, "Courier New", Courier, monospace !important;
  white-space: pre-wrap !important;
  word-break: break-word !important;
  overflow-wrap: break-word !important;
  resize: vertical;
}

.reply-box {
  margin-top: 8px;
  width: 100%;
}

/* 让 el-input 宽度撑满容器 */
.reply-box .autosize-textarea,
.new-comment-textarea.autosize-textarea {
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
}

.btn-delete,
.btn-reply,
.btn-submit,
.btn-collapse {
  background: none;
  border: none;
  color: #409eff;
  cursor: pointer;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 13px;
  transition: background-color 0.3s;
  user-select: none;
}

.btn-delete {
  color: #f56c6c;
}
.btn-delete:hover {
  background-color: #fde2e2;
}

.btn-reply:hover,
.btn-submit:hover,
.btn-collapse:hover {
  background-color: #ecf5ff;
  color: #66b1ff;
}

.reply-box .btn-submit {
  margin-top: 6px;
  font-weight: 600;
}

.replies-list {
  margin-top: 10px;
  padding-left: 30px;
  border-left: 2px solid #ebeef5;
}

.comment-reply {
  background: #f5f7fa;
  border-radius: 6px;
  padding: 10px 16px;
  margin-bottom: 12px;
  box-shadow: inset 0 1px 3px rgb(0 0 0 / 0.03);
}

.new-comment-textarea {
  margin-bottom: 10px;
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  padding: 8px 10px;
  font-size: 15px;
  resize: vertical;
}

.btn-submit {
  background-color: #409eff;
  color: white;
  border-radius: 4px;
  padding: 8px 18px;
  font-weight: 600;
  transition: background-color 0.3s;
}
.btn-submit:hover {
  background-color: #66b1ff;
}

.loading {
  font-size: 16px;
  color: #909399;
  text-align: center;
  padding: 20px 0;
}

.post-actions button:hover {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

.post-actions button.active {
  background-color: #bae7ff;
  border-color: #40a9ff;
  color: #096dd9;
  box-shadow: 0 0 6px rgb(24 144 255 / 0.6);
}

/* 点赞按钮单独颜色 */
.btn-like {
  color: #fa541c;
  border-color: #ffa39e;
}
.btn-like.active {
  background-color: #ffccc7;
  border-color: #ff4d4f;
  color: #a8071a;
  box-shadow: 0 0 6px rgb(255 77 79 / 0.8);
}

/* 收藏按钮单独颜色 */
.btn-favorite {
  color: #faad14;
  border-color: #ffe58f;
}
.btn-favorite.active {
  background-color: #fff7e6;
  border-color: #ffc53d;
  color: #ad6800;
  box-shadow: 0 0 6px rgb(255 197 0 / 0.8);
}

/* 举报按钮采用警告色 */
.btn-report {
  color: #f5222d;
  border-color: #ffccc7;
}
.btn-report:hover {
  background-color: #fff1f0;
  border-color: #ff4d4f;
  color: #a8071a;
  box-shadow: 0 0 6px rgb(255 77 79 / 0.8);
}
</style>
如何让论坛管理进入详情页的时候，跳的是管理员详情页而不是用户详情页