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

export const useUserPostStore = defineStore('userPost', {
  state: () => ({
    posts: [], // 帖子列表
    total: 0, // 帖子总数
    page: 1, // 当前页码
    pageSize: 10, // 每页帖子数
    lastVal: Date.now(), // 用于滚动分页的时间戳
    offset: 0, // 偏移量
    loading: false, // 加载状态
    finished: false, // 是否加载完全部
  }),
  actions: {
    setPosts(posts) {
      this.posts = posts;
    },
    setTotal(total) {
      this.total = total;
    },
    setPage(page) {
      this.page = page;
    },
    setPageSize(pageSize) {
      this.pageSize = pageSize;
    },
    addPost(post) {
      this.posts.push(post);
      this.total += 1; // 更新总数
    },
    removePost(postId) {
      this.posts = this.posts.filter(post => post.id !== postId);
      this.total -= 1; // 更新总数
    },
    async getList({ lastVal = this.lastVal, offset = this.offset, size = this.pageSize } = {}) {
      if (this.loading || this.finished) return;
      this.loading = true;
      try {
        const res = await request.post('/post/user', { lastVal, offset, size });
        if (res.code === 200) {
          const { records, lastVal: newLastVal, offset: newOffset, size: newSize } = res.data;
          if (records && records.length > 0) {
            // 字段映射
            const mappedRecords = records.map(post => ({
              id: post.id,
              avatar: post.userAvatar || post.image || require('@/assets/default-avatar/boy_1.png'),
              title: post.title,
              summary: post.content ? post.content.slice(0, 40) + (post.content.length > 40 ? '...' : '') : '',
              likes: post.likeCount || 0,
              comments: post.commentCount || 0,
              favorites: post.favoriteCount || 0,
              category: post.category || '全部',
              createTime: post.createTime,
              userName: post.userName,
            }));
            this.posts = [...this.posts, ...mappedRecords];
            this.lastVal = newLastVal;
            this.offset = newOffset;
            this.pageSize = newSize;
          }
          if (!records || records.length < size) {
            this.finished = true; // 没有更多数据
          }
        } else {
          console.error('获取用户帖子列表返回错误:', res.msg);
          ElMessage({
            message: res.msg || '获取用户帖子列表失败，请稍后重试',
            type: 'error',
            duration: 1500
          });
        }
      } catch (error) {
        console.error("获取用户帖子列表失败:", error);
        ElMessage({
          message: error.response?.data?.msg || '获取用户帖子列表失败，请稍后重试',
          type: 'error',
          duration: 1500
        });
      } finally {
        this.loading = false;
      }
    },
    resetList() {
      this.posts = [];
      this.lastVal = Date.now();
      this.offset = 0;
      this.finished = false;
    }
  },
});