import { defineStore } from "pinia" import { reactive, ref } from "vue" import type { PostItem, PostDetail, Pagination } from "../type" import { getPostController } from "../api/post-controller" import type { ResponsePostVo, ResponsePageVoListPostVo, PostVo } from "../api/models" function mapPostVo(v: PostVo): PostItem { const now = new Date() const pub = v.publishTime ? new Date(v.publishTime) : new Date(0) const isToday = pub.getFullYear() === now.getFullYear() && pub.getMonth() === now.getMonth() && pub.getDate() === now.getDate() const tags: string[] = [] if (v.expertIsRealname) tags.push('已认证') return { id: v.id ?? '', title: v.title ?? '', expertName: v.expertName ?? '', expertAvatar: v.expertAvatar ?? '', expertLevel: v.expertLevel ?? 'gold', expertIsRealname: v.expertIsRealname ?? false, tags, price: v.price ?? 0, publishTime: v.publishTime ?? '', viewCount: v.viewCount ?? 0, isPublic: v.isPublic ?? false, hitStatus: v.hitStatus ?? 'pending', isTodayNew: isToday, expireTime: v.expireTime ?? '', } } export const usePostStore = defineStore('post', () => { const posts = ref([]) const currentDetail = ref(null) const currentStatus = ref('all') const searchKeyword = ref('') const pagination = reactive({ page: 1, pageSize: 10, total: 0 }) const loading = ref(false) async function fetchPosts(status?: string, keyword?: string): Promise { if (status !== undefined) currentStatus.value = status if (keyword !== undefined) searchKeyword.value = keyword loading.value = true try { const res: ResponsePageVoListPostVo = await getPostController().listPosts({ status: currentStatus.value, keyword: searchKeyword.value, pageNum: pagination.page, pageSize: pagination.pageSize, }) if (res.code === 200 && res.data) { posts.value = (res.data.data ?? []).map(mapPostVo) pagination.total = res.data.total ?? 0 } } catch { posts.value = [] } finally { loading.value = false } } async function fetchPostDetail(id: string): Promise { loading.value = true try { const res: ResponsePostVo = await getPostController().getPostDetail(Number(id)) if (res.code === 200 && res.data) { const v = res.data currentDetail.value = { id: v.id ?? '', title: v.title ?? '', contentIntro: v.contentIntro ?? '', contentPaid: v.contentPaid ?? '', price: v.price ?? 0, isPaid: v.isPaid ?? false, isPublic: v.isPublic ?? false, hitStatus: v.hitStatus ?? 'pending', publishTime: v.publishTime ?? '', expireTime: v.expireTime ?? '', expert: { name: v.expertName ?? '', avatar: v.expertAvatar ?? '', level: v.expertLevel ?? 'gold', isRealname: v.expertIsRealname ?? false, tags: v.expertIsRealname ? ['已认证'] : [], }, previousPosts: [], } } else { currentDetail.value = null } } catch { currentDetail.value = null } finally { loading.value = false } } function loadMore(): void { pagination.page++ fetchPosts() } return { posts, currentDetail, currentStatus, searchKeyword, pagination, loading, fetchPosts, fetchPostDetail, loadMore } })