xref: /MusicFree/src/pages/recommendSheets/hooks/useRecommendSheets.ts (revision ceb900cd812eb1b086ac040a306ddf325339e920)
1*ceb900cdS猫头猫import PluginManager from '@/core/pluginManager';
2*ceb900cdS猫头猫import {resetMediaItem} from '@/utils/mediaItem';
3*ceb900cdS猫头猫import {useCallback, useEffect, useRef, useState} from 'react';
4*ceb900cdS猫头猫
5*ceb900cdS猫头猫export default function (pluginHash: string, tag: ICommon.IUnique) {
6*ceb900cdS猫头猫    const [sheets, setSheets] = useState<IMusic.IMusicSheetItemBase[]>([]);
7*ceb900cdS猫头猫    const [status, setStatus] = useState<'loading' | 'idle' | 'done'>('idle');
8*ceb900cdS猫头猫    const currentTagRef = useRef<string>();
9*ceb900cdS猫头猫    const pageRef = useRef(0);
10*ceb900cdS猫头猫
11*ceb900cdS猫头猫    const query = useCallback(async () => {
12*ceb900cdS猫头猫        console.log(currentTagRef, tag, pageRef.current, status);
13*ceb900cdS猫头猫        if (
14*ceb900cdS猫头猫            (status === 'loading' || status === 'done') &&
15*ceb900cdS猫头猫            currentTagRef.current === tag.id
16*ceb900cdS猫头猫        ) {
17*ceb900cdS猫头猫            return;
18*ceb900cdS猫头猫        }
19*ceb900cdS猫头猫        if (currentTagRef.current !== tag.id) {
20*ceb900cdS猫头猫            setSheets([]);
21*ceb900cdS猫头猫            pageRef.current = 0;
22*ceb900cdS猫头猫        }
23*ceb900cdS猫头猫        pageRef.current++;
24*ceb900cdS猫头猫        currentTagRef.current = tag.id;
25*ceb900cdS猫头猫        const plugin = PluginManager.getByHash(pluginHash);
26*ceb900cdS猫头猫        if (plugin) {
27*ceb900cdS猫头猫            setStatus('loading');
28*ceb900cdS猫头猫            const res = await plugin.methods?.getRecommendSheetsByTag?.(
29*ceb900cdS猫头猫                tag,
30*ceb900cdS猫头猫                pageRef.current,
31*ceb900cdS猫头猫            );
32*ceb900cdS猫头猫            console.log(res.isEnd);
33*ceb900cdS猫头猫            if (tag.id === currentTagRef.current) {
34*ceb900cdS猫头猫                setSheets(prev => [
35*ceb900cdS猫头猫                    ...prev,
36*ceb900cdS猫头猫                    ...res.data!.map(item =>
37*ceb900cdS猫头猫                        resetMediaItem(item, plugin.instance.platform),
38*ceb900cdS猫头猫                    ),
39*ceb900cdS猫头猫                ]);
40*ceb900cdS猫头猫            }
41*ceb900cdS猫头猫
42*ceb900cdS猫头猫            if (res.isEnd) {
43*ceb900cdS猫头猫                setStatus('done');
44*ceb900cdS猫头猫            } else {
45*ceb900cdS猫头猫                setStatus('idle');
46*ceb900cdS猫头猫            }
47*ceb900cdS猫头猫        } else {
48*ceb900cdS猫头猫            setStatus('done');
49*ceb900cdS猫头猫            setSheets([]);
50*ceb900cdS猫头猫        }
51*ceb900cdS猫头猫    }, [tag, status]);
52*ceb900cdS猫头猫
53*ceb900cdS猫头猫    useEffect(() => {
54*ceb900cdS猫头猫        query();
55*ceb900cdS猫头猫    }, [tag]);
56*ceb900cdS猫头猫
57*ceb900cdS猫头猫    return [query, sheets, status] as const;
58*ceb900cdS猫头猫}
59