<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>
    </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"
        >
          <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>
        </li>
      </ul>

      <div v-if="posts.length === 0" class="no-data">无数据</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()
const userId = localStorage.getItem('userId')

const fetchPosts = async (title = '') => {
  loading.value = true
  try {
    const res = await axios.get('http://localhost:8080/forum/posts', {
      params: { title }
    })
    posts.value = res.data
  } catch (err) {
    console.error(err)
    posts.value = []
  } 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('删除失败')
  }
}

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

<style scoped>
.forum-home {
  max-width: 720px;
  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;
}
</style>
加一个举报审核按钮，点击按钮，会出现report_post的内容，package com.example.springboot.controller;


import com.example.springboot.entity.Forum.*;
import com.example.springboot.service.ForumService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/forum")
public class ForumController {

    @Resource
    private ForumService forumService;

    // 发布帖子
    @PostMapping("/post")
    public String createPost(@RequestBody Post post) {
        int result = forumService.createPost(post);
        return result > 0 ? "Post created successfully" : "Post creation failed";
    }

    // 删除帖子（普通用户需要在业务层验证是否本人）
    @DeleteMapping("/post/{id}")
    public String deletePost(@PathVariable Integer id) {
        int result = forumService.deletePost(id);
        return result > 0 ? "Post deleted successfully" : "Post deletion failed";
    }

    // 修改帖子
    @PutMapping("/post")
    public String updatePost(@RequestBody Post post) {
        int result = forumService.updatePost(post);
        return result > 0 ? "Post updated successfully" : "Post update failed";
    }

    // 根据帖子ID获取帖子详情
    @GetMapping("/post/{id}")
    public Post getPostById(@PathVariable Integer id) {
        return forumService.getPostById(id);
    }

    // 模糊查询帖子标题
    @GetMapping("/posts")
    public List<Post> searchPostsByTitle(@RequestParam String title) {
        return forumService.searchPostsByTitle(title);
    }

    // 新增评论
    @PostMapping("/comment")
    public String createComment(@RequestBody Comment comment) {
        int result = forumService.createComment(comment);
        return result > 0 ? "Comment added successfully" : "Comment adding failed";
    }

    // 删除评论
    @DeleteMapping("/comment/{id}")
    public String deleteComment(@PathVariable Integer id) {
        int result = forumService.deleteComment(id);
        return result > 0 ? "Comment deleted successfully" : "Comment deletion failed";
    }

    // 修改评论
    @PutMapping("/comment")
    public String updateComment(@RequestBody Comment comment) {
        int result = forumService.updateComment(comment);
        return result > 0 ? "Comment updated successfully" : "Comment update failed";
    }

    // 获取某帖子的评论列表（包含回复）
    @GetMapping("/comments/{postId}")
    public List<Comment> getCommentsByPostId(@PathVariable Integer postId) {
        return forumService.getCommentsByPostId(postId);
    }

    // 点赞帖子
    @PostMapping("/post/like")
    public String likePost(@RequestBody LikePost likePost) {
        int result = forumService.createLikePost(likePost);
        return result > 0 ? "点赞成功" : "已经点赞过或点赞失败";
    }

    // 取消点赞
    @DeleteMapping("/post/like")
    public String unlikePost(@RequestParam Integer userId, @RequestParam Integer postId) {
        int result = forumService.deleteLikePost(userId, postId);
        return result > 0 ? "取消点赞成功" : "取消点赞失败";
    }

    // 收藏帖子
    @PostMapping("/post/favorite")
    public String favoritePost(@RequestBody FavoritePost favoritePost) {
        int result = forumService.createFavoritePost(favoritePost);
        return result > 0 ? "收藏成功" : "收藏失败或已收藏";
    }

    // 取消收藏
    @DeleteMapping("/post/favorite")
    public String unfavoritePost(@RequestParam Integer userId, @RequestParam Integer postId) {
        int result = forumService.deleteFavoritePost(userId, postId);
        return result > 0 ? "取消收藏成功" : "取消收藏失败";
    }

    // 举报帖子
    @PostMapping("/post/report")
    public String reportPost(@RequestBody ReportPost reportPost) {
        int result = forumService.createReportPost(reportPost);
        return result > 0 ? "举报成功" : "举报失败";
    }

    // 管理员查看举报
    @GetMapping("/post/reports/{postId}")
    public List<ReportPost> getReportsByPostId(@PathVariable Integer postId) {
        return forumService.getReportPostsByPostId(postId);
    }

    @GetMapping("/user/{userId}/posts")
    public List<Post> getPostsByUserId(@PathVariable Integer userId) {
        List<Post> posts = forumService.getPostsByUserId(userId);

        // 这里可以查询并设置每个帖子的点赞数，点赞和收藏状态，比如（简单示例，效率不错的话可DAO一次搞定）：
        posts.forEach(post -> {
            int likeCount = forumService.getLikeCountByPostId(post.getId());


            // 查询当前用户是否点赞/收藏，改成传参可改
            // 这里暂时userId是查询者，请改成当前登录用户id
            LikePost likePost = forumService.getLikePost(userId, post.getId());
            post.setLiked(likePost != null);

            FavoritePost favPost = forumService.getFavoritePost(userId, post.getId());
            post.setFavorited(favPost != null);
        });
        return posts;
    }
    /**
     * 获取用户点赞过的帖子列表
     */
    @GetMapping("/user/{userId}/liked-posts")
    public List<Post> getLikedPostsByUserId(@PathVariable Integer userId) {
        return forumService.getLikedPostsByUserId(userId);
    }

    /**
     * 获取用户收藏过的帖子列表
     */
    @GetMapping("/user/{userId}/favorited-posts")
    public List<Post> getFavoritedPostsByUserId(@PathVariable Integer userId) {
        return forumService.getFavoritedPostsByUserId(userId);
    }

    @GetMapping("/post/like/status")
    public Map<String, Boolean> getLikeStatus(@RequestParam Integer userId, @RequestParam Integer postId) {
        boolean liked = forumService.getLikePost(userId, postId) != null;
        return Collections.singletonMap("liked", liked);
    }

    @GetMapping("/post/favorite/status")
    public Map<String, Boolean> getFavoriteStatus(@RequestParam Integer userId, @RequestParam Integer postId) {
        boolean favorited = forumService.getFavoritePost(userId, postId) != null;
        return Collections.singletonMap("favorited", favorited);
    }
}