<template>
  <div class="my-posts">
    <h2>我的帖子</h2>
    <button @click="fetchMyPosts" class="btn-refresh">刷新</button>
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else>
      <div v-if="posts.length === 0" class="no-posts">还没有发表任何帖子</div>
      <ul class="posts-list">
        <li v-for="post in posts" :key="post.id" class="post-item">
          <div class="post-info">
            <router-link :to="`/post/${post.id}`" class="post-title">{{ post.title }}</router-link>
            <span class="post-date">发布时间: {{ formatDateTime(post.createdAt) }}</span>
          </div>
          <div class="post-actions">
            <button
                @click="toggleLike(post)"
                :class="['btn-like', { active: post.liked }]"
                title="点赞 / 取消点赞"
            >
              {{ post.liked ? "已点赞" : "点赞" }} ({{ post.likeCount }})
            </button>
            <button
                @click="toggleFavorite(post)"
                :class="['btn-favorite', { active: post.favorited }]"
                title="收藏 / 取消收藏"
            >
              {{ post.favorited ? "已收藏" : "收藏" }}
            </button>
            <button @click="deletePost(post)" class="btn-delete" title="删除帖子">删除</button>
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>

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

const userId = localStorage.getItem("userId");
const router = useRouter();

if (!userId) {
  ElMessage.warning("请先登录");
  router.push("/login"); // 需要你的登录路由路径
}

const posts = ref([]);
const loading = ref(false);

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

// 获取我的帖子列表，同时带上点赞状态和收藏状态和点赞数
const fetchMyPosts = async () => {
  if (!userId) return;
  loading.value = true;
  try {
    // 先获取我的帖子列表
    const res = await axios.get(`http://localhost:8080/forum/user/${userId}/posts`);
    const myPosts = res.data;

    // 批量获取点赞和收藏状态（如果接口支持批量查询，改成批量请求更好；这里示范单条请求合并）

    // 这里假设接口只支持单个帖子获取点赞和收藏状态，批量请求示例：
    // 你可以根据实际后端接口优化请求方式

    // 并发请求点赞和收藏状态
    const statusPromises = myPosts.map(async (post) => {
      // 点赞状态
      try {
        const likeRes = await axios.get(`http://localhost:8080/forum/post/like/status`, {
          params: { userId, postId: post.id },
        });
        post.liked = likeRes.data.liked;
      } catch {
        post.liked = false;
      }
      // 收藏状态
      try {
        const favRes = await axios.get(`http://localhost:8080/forum/post/favorite/status`, {
          params: { userId, postId: post.id },
        });
        post.favorited = favRes.data.favorited;
      } catch {
        post.favorited = false;
      }
      // 点赞数
      post.likeCount = post.likeCount || 0;
      return post;
    });

    const postsWithStatus = await Promise.all(statusPromises);
    posts.value = postsWithStatus;
  } catch (error) {
    ElMessage.error("加载我的帖子失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 删除帖子
const deletePost = async (post) => {
  try {
    await ElMessageBox.confirm("确定删除此帖子吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    await axios.delete(`http://localhost:8080/forum/post/${post.id}`);
    ElMessage.success("删除成功");
    // 重新加载列表
    fetchMyPosts();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

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

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

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

<style scoped>
.my-posts {
  max-width: 800px;
  margin: auto;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

h2 {
  color: #303133;
  margin-bottom: 10px;
  font-weight: 700;
}

.btn-refresh {
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  cursor: pointer;
  font-weight: 600;
  margin-bottom: 20px;
  transition: background-color 0.3s;
}
.btn-refresh:hover {
  background-color: #66b1ff;
}

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

.post-item {
  background: white;
  padding: 16px 20px;
  border-radius: 6px;
  margin-bottom: 16px;
  box-shadow: 0 1px 3px rgb(0 0 0 / 0.1);
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.post-info {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
}

.post-title {
  font-weight: 600;
  font-size: 18px;
  color: #409eff;
  text-decoration: none;
}

.post-title:hover {
  text-decoration: underline;
}

.post-date {
  font-size: 13px;
  color: #909399;
  margin-left: 10px;
  white-space: nowrap;
}

.post-actions {
  display: flex;
  gap: 12px;
  margin-top: 6px;
}

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

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

.btn-like.active {
  color: #f56c6c;
  font-weight: 700;
  background-color: #ffccc7;
  border-color: #ff4d4f;
  box-shadow: 0 0 6px rgb(255 77 79 / 0.8);
}

.btn-favorite.active {
  color: #faad14;
  font-weight: 700;
  background-color: #fff7e6;
  border-color: #ffc53d;
  box-shadow: 0 0 6px rgb(255 197 0 / 0.8);
}

.btn-delete {
  color: #f5222d;
  border-color: #ffccc7;
  background-color: #fff1f0;
  font-weight: 600;
}

.btn-delete:hover {
  background-color: #ff4d4f;
  color: white;
  border-color: #a8071a;
  box-shadow: 0 0 6px rgb(168 7 26 / 0.9);
}

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

.no-posts {
  font-size: 16px;
  color: #606266;
  text-align: center;
  margin-top: 30px;
}
</style>
没有分类显示哪些帖子是我点赞过的，哪些帖子是我收藏的，哪些是我自己的。现在只能看到我自己的，麻烦做成和tiktok一样的页面