import {defineStore} from 'pinia';
import request from '@/utils/request';

export const usePostListStore = defineStore('postList', {
  state: () => ({
    posts: [], // 帖子列表
    total: 0, // 帖子总数
    page: 1, // 当前页码
    pageSize: 10, // 每页帖子数
    lastVal: Date.now(), // 用于滚动分页的时间戳
    offset: 0, // 偏移量
    loading: false, // 加载状态
    finished: false, // 是否加载完全部
    currentCategory: null, // 当前分类id
  }),
  actions: {
    async getList(categoryId = null) {
      if (this.loading || this.finished) return;
      this.loading = true;
      // 记录当前分类
      this.currentCategory = categoryId;
      try {
        // 保证 lastVal 不为 null
        const lastVal = (typeof this.lastVal === 'number' && this.lastVal > 0) ? this.lastVal : Date.now();
        // 拼接参数到URL
        let url = `/post/list?lastVal=${lastVal}&offset=${this.offset}&size=${this.pageSize}`;
        if(categoryId!== null) {
          url += `&categoryId=${categoryId}`;
        }
        const res = await request.get(url);
        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,
              image: post.image,
              avatar: post.userAvatar || require('@/assets/default-avatar/boy_1.png'),
              title: post.title,
              summary: post.content ? post.content.slice(0, 40) + (post.content.length > 40 ? '...' : '') : '',
              viewCount: post.viewCount || 0,
              likes: post.likeCount || 0,
              comments: post.commentCount || 0,
              categoryId: post.categoryId,
              createTime: post.createTime,
              userName: post.userName,
            }));
            this.posts = [...this.posts, ...mappedRecords];
            // 只在 newLastVal 有效时才赋值
            this.lastVal = (typeof newLastVal === 'number' && newLastVal > 0) ? newLastVal : lastVal;
            this.offset = newOffset;
            this.pageSize = newSize;
          }
          console.log('获取帖子列表成功', this.posts);
          if (!records || records.length < this.pageSize) {
            this.finished = true; // 没有更多数据
          }
        } else {
          // 处理错误情况

        }
      } catch (error) {
        // 处理异常情况
      } finally {
        this.loading = false;
      }
    },
    resetList() {
      this.posts = [];
      this.lastVal = Date.now();
      this.offset = 0;
      this.finished = false;
    }
  },
});