import { root } from '@repo/core' import { TemplateGenerationController, type ListTemplateGenerationsInput, type ListTemplateGenerationsResult, type TemplateGeneration, } from '@repo/sdk' import { useCallback, useRef, useState } from 'react' import { type ApiError } from '@/lib/types' import { handleError } from './use-error' export const useTemplateGenerations = () => { const [loading, setLoading] = useState(false) const [loadingMore, setLoadingMore] = useState(false) const [error, setError] = useState(null) const [data, setData] = useState() const currentPageRef = useRef(1) const hasMoreRef = useRef(true) const execute = useCallback(async (params?: ListTemplateGenerationsInput) => { setLoading(true) setError(null) currentPageRef.current = params?.page || 1 const templateGeneration = root.get(TemplateGenerationController) const { data, error } = await handleError( async () => await templateGeneration.list({ page: params?.page || 1, limit: params?.limit || 20, ...params, }), ) if (error) { setError(error) setLoading(false) return { data: undefined, error } } const generations = data?.data || [] hasMoreRef.current = generations.length >= (params?.limit || 20) setData(data) setLoading(false) return { data, error: null } }, []) const loadMore = useCallback( async (params?: Omit) => { if (loadingMore || loading || !hasMoreRef.current) return { data: undefined, error: null } setLoadingMore(true) const nextPage = currentPageRef.current + 1 const templateGeneration = root.get(TemplateGenerationController) const { data: newData, error } = await handleError( async () => await templateGeneration.list({ page: nextPage, limit: params?.limit || 20, ...params, }), ) if (error) { setLoadingMore(false) return { data: undefined, error } } const newGenerations = newData?.data || [] hasMoreRef.current = newGenerations.length >= (params?.limit || 20) currentPageRef.current = nextPage // 合并数据并去重 setData((prev) => { const existingIds = new Set((prev?.data || []).map(item => item.id)) const uniqueNewGenerations = newGenerations.filter(item => !existingIds.has(item.id)) return { ...newData, data: [...(prev?.data || []), ...uniqueNewGenerations], } }) setLoadingMore(false) return { data: newData, error: null } }, [loading, loadingMore], ) const refetch = useCallback( (params?: ListTemplateGenerationsInput) => { hasMoreRef.current = true return execute(params) }, [execute], ) return { data, generations: data?.data || [], loading, loadingMore, error, execute, refetch, loadMore, hasMore: hasMoreRef.current, } } export type { TemplateGeneration }