import { defineStore } from "pinia";
import request from "@/utils/request";
import { ElMessage } from "element-plus";

export const usePostDetailStore = defineStore("postDetail", {
  state: () => ({
    post: null,           // 帖子主要信息
    comments: [],         // 评论列表
    userInfo: null,       // 用户信息
    isLike: false,        // 是否点赞
    lastVal: Date.now(),         // 用于滚动分页的时间戳
    offset: 0,           // 偏移量
    size: 5,           // 每页评论数
    detailLoading: false,      // 加载状态
    commentsLoading: false, // 评论加载状态
    commentsFinished: false, // 是否加载完全部评论
  }),
  actions: {
    async fetchComments() {
      if (this.commentsLoading || this.commentsFinished) return;
      this.commentsLoading = true;
      // 拼接参数到URL
      const params = [
        `lastVal=${this.lastVal}`,
        `offset=${this.offset}`,
        `size=${this.size}`,
        `postId=${this.post.postId}`
      ].join('&');
      const url = `/comment/list?${params}`;
      try {
        const response = await request.get(url);
        if (response.code === 200) {
          // 初始化每条评论的子评论分页状态
          const comments = (response.data.records || []).map(item => ({
            ...item,
            replies: [],
            showReplies: false, // 是否显示子评论
            repliesLastVal: Date.now(),
            repliesOffset: 0,
            repliesSize: 5,
            repliesLoading: false,
            repliesFinished: false,
          }));
          this.comments.push(...comments);
          this.lastVal = response.data.lastVal;
          this.offset = response.data.offset;
          if (comments.length < this.size) {
            this.commentsFinished = true; // 如果评论数少于每页大小，标记为已加载完
          }
        }
        else {
          ElMessage({
            message: '获取评论失败，请稍后重试',
            type: 'error',
            duration: 500
          });
        }
      } catch (error) {
        console.error("获取评论失败:", error);
        alert(error.response?.message || '获取评论失败，请稍后重试');
      }finally {
        this.commentsLoading = false;
      }
    },
    // 获取某条评论的子评论
    async fetchReplies(parentCommentId, commentObj) {
      if (commentObj.repliesLoading || commentObj.repliesFinished) return;
      commentObj.repliesLoading = true;
      /// 拼接参数到URL
      const params = [
        `lastVal=${commentObj.repliesLastVal}`,
        `offset=${commentObj.repliesOffset}`,
        `size=${commentObj.repliesSize}`,
        `postId=${this.post?.postId}`,
        `parentCommentId=${parentCommentId}`
      ].join('&');
      const url = `/comment/list/reply?${params}`;
      try {
        const res = await request.get(url);
        if (res.code === 200) {
          const records = (res.data.records || []).map(item => ({
            ...item,
            replyUserName: item.replyUserName, 
          }));
          commentObj.replies.push(...records);
          commentObj.repliesLastVal = res.data.lastVal;
          commentObj.repliesOffset = res.data.offset;
          if (records.length < commentObj.repliesSize) {
            commentObj.repliesFinished = true;
          }
        }
        else {
          ElMessage({
            message: '获取子评论失败，请稍后重试',
            type: 'error',
            duration: 500
          });
        }
      } catch (error) {
        console.error("获取子评论失败:", error);
        alert(error.response?.message || '获取子评论失败，请稍后重试');
      } finally {
        commentObj.repliesLoading = false;
      }
    },

    async fetchPostDetail(postId) {
      this.detailLoading = true;
      // 先重置评论相关状态，防止串数据
      this.comments = [];
      this.lastVal = Date.now();
      this.offset = 0;
      this.commentsFinished = false;
      this.commentsLoading = false;
      try {
        // 获取帖子详情
        const postRes = await request.get('/post/detail', { params: { id: postId } });
        if (postRes.code === 200 && postRes.data) {
          const {
            id,
            image,
            title,
            content,
            likeCount,
            commentCount,
            favoriteCount,
            viewCount,
            isLike,
            userId,
            userName,
            userAvatar,
            createTime
          } = postRes.data;
          console.log("获取帖子详情返回:", postRes.data);
          // 主要帖子信息
          this.post = {
            postId: id,
            image: image,
            title,
            content,
            createTime,
            commentCount,
            likeCount,
            favoriteCount,
            viewCount,
            author: { 
              userId,
              userName,
              userAvatar,
              followers: 1234, // 先预设粉丝占位
            },
          };

          // 其余字段
          this.isLike = isLike;
          // 获取评论列表
        this.lastVal = Date.now();
        this.fetchComments();
        }
        else {
          ElMessage({
            message: '获取帖子详情失败，请稍后重试',
            type: 'error',
            duration: 500
          });
        } 
      } catch (error) {
        console.error("获取帖子详情失败:", error);
        alert(error.response?.message || '获取帖子详情失败，请稍后重试');
      }finally {
        this.detailLoading = false;
      }
    },
    // 发送评论或回复
    async sendComment(newCommentData) {
      if (!newCommentData.content || !this.post?.postId) return;
      const RequestData = {
        id:null,
        postId: newCommentData.postId, // 帖子ID
        content: newCommentData.content, // 评论内容
        parentCommentId: newCommentData.parentCommentId, 
      };
      try {
        const res = await request.post('/comment', RequestData);
        console.log("发送评论返回:", res.data);
        if (res.code === 200) {
          const commentObj = {
            id: res.data,
            content: newCommentData.content,
            userId: newCommentData.userId,
            userName: newCommentData.userName,
            userAvatar: newCommentData.userAvatar,
            createTime: new Date().toISOString(),
            likeCount: 0,
            replyCount: 0,
            postId: this.post.postId,
            parentCommentId: newCommentData.parentCommentId,
            replyUserName: newCommentData.replyUserName,
            topId: newCommentData.topId,
            isLike: 0,
          };
          console.log("发送评论数据:", commentObj.id);
          // 新增评论后刷新评论列表或插入到对应位置
          if (!newCommentData.parentCommentId) {
            // 一级评论，插入到最前面
            commentObj.topId = commentObj.id; // 一级评论的顶级ID就是自己的ID
            commentObj.replies = [];
            commentObj.repliesLastVal = Date.now();
            commentObj.repliesOffset = 0;
            commentObj.repliesSize = 5;
            commentObj.repliesLoading = false;
            commentObj.repliesFinished = false;
            this.comments.unshift(commentObj);     
          } else {
            // 回复，只插入到一级评论的 replies
            let parent = this.comments.find(c => c.id === newCommentData.topId);
            if (parent) {
              parent.replies.push(commentObj);
              parent.replyCount = (parent.replyCount || 0) + 1;
            }
          }
          this.post.commentCount = (this.post.commentCount || 0) + 1; // 更新帖子评论数
          console.log("评论成功:", commentObj);
        }else {
          console.error("评论失败:", res);
          ElMessage.error(res.message || '评论失败');
        }
      } catch (e) {
        alert(e.response?.message || '发送评论失败，请稍后重试');
      }
    },
    // 删除评论或回复
    async deleteComment(commentObj) {
      try {
        const commentId = commentObj.id;
        const topId = commentObj.topId;
        const res = await request.delete('/comment', { params: { id: commentId} });
        if (res.code === 200) {
          // 一级评论
          if (commentObj.id === commentObj.topId) {
            // 删除一级评论及其所有回复
            const idx = this.comments.findIndex(c => c.id === commentId);
            if (idx !== -1) {
              const comment = this.comments[idx];
              // 总评论数 -= replyCount
              if (this.post && this.post.commentCount > 0) {
                this.post.commentCount -= (comment.replyCount || 0);
                if (this.post.commentCount < 0) this.post.commentCount = 0;
              }
              this.comments.splice(idx, 1);
            }
          } else {
            const topComment = this.comments.find(c => c.id === topId);
            if (topComment) {
              const replyIdx = topComment.replies.findIndex(r => r.id === commentId);
              if (replyIdx !== -1) {
                topComment.replies.splice(replyIdx, 1);
                if (topComment.replyCount > 0) topComment.replyCount--;
              }
            }
          }
          // 更新评论数
          if (this.post && this.post.commentCount > 0) {
            this.post.commentCount--;
          }
          ElMessage.success('删除成功');
        } else {
          ElMessage.error(res.message || '删除失败');
        }
      } catch (e) {
        ElMessage.error(e.response?.message || '删除失败，请稍后重试');
      }
    },
    //帖子点赞和取消
    async PostLike() {
      if (!this.post || !this.post.postId) return;
      try {
        const url = `/post/like/${this.post.postId}`;
        if (!this.isLike) {
          // 点赞
          const res = await request.put(url);
          if (res.code === 200) {
            this.isLike = true;
            this.post.likeCount = (this.post.likeCount || 0) + 1;
            ElMessage.success('点赞成功');
          } else {
            ElMessage.error(res.message || '点赞失败');
          }
        } else {
          // 取消点赞
          const res = await request.put(url);
          if (res.code === 200) {
            this.isLike = false;
            this.post.likeCount = Math.max((this.post.likeCount || 1) - 1, 0);
            ElMessage.success('已取消点赞');
          } else {
            ElMessage.error(res.message || '取消点赞失败');
          }
        }
      } catch (e) {
        ElMessage.error(e.response?.message || '操作失败，请稍后重试');
      }
    },
    // 评论点赞和取消
    async CommentLike(commentObj) {
      if (!commentObj || !commentObj.id) return;
      try {
        const url = `/comment/like/${commentObj.id}`;
        if (!commentObj.isLike) {
          // 点赞
          const res = await request.put(url);
          if (res.code === 200) {
            commentObj.isLike = true;
            commentObj.likeCount = (commentObj.likeCount || 0) + 1;
            ElMessage.success('点赞成功');
          } else {
            ElMessage.error(res.message || '点赞失败');
          }
        } else {
          // 取消点赞
          const res = await request.put(url);
          if (res.code === 200) {
            commentObj.isLike = false;
            commentObj.likeCount = Math.max((commentObj.likeCount || 1) - 1, 0);
            ElMessage.success('已取消点赞');
          } else {
            ElMessage.error(res.message || '取消点赞失败');
          }
        }
      } catch (e) {
        ElMessage.error(e.response?.message || '操作失败，请稍后重试');
      }
    }
  },
});