xref: /MusicFree/src/pages/recommendSheets/hooks/useRecommendSheets.ts (revision 5830c002c929157c4836f153afb60293c1da54e5)
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猫头猫        if (
13*ceb900cdS猫头猫            (status === 'loading' || status === 'done') &&
14*ceb900cdS猫头猫            currentTagRef.current === tag.id
15*ceb900cdS猫头猫        ) {
16*ceb900cdS猫头猫            return;
17*ceb900cdS猫头猫        }
18*ceb900cdS猫头猫        if (currentTagRef.current !== tag.id) {
19*ceb900cdS猫头猫            setSheets([]);
20*ceb900cdS猫头猫            pageRef.current = 0;
21*ceb900cdS猫头猫        }
22*ceb900cdS猫头猫        pageRef.current++;
23*ceb900cdS猫头猫        currentTagRef.current = tag.id;
24*ceb900cdS猫头猫        const plugin = PluginManager.getByHash(pluginHash);
25*ceb900cdS猫头猫        if (plugin) {
26*ceb900cdS猫头猫            setStatus('loading');
27*ceb900cdS猫头猫            const res = await plugin.methods?.getRecommendSheetsByTag?.(
28*ceb900cdS猫头猫                tag,
29*ceb900cdS猫头猫                pageRef.current,
30*ceb900cdS猫头猫            );
31*ceb900cdS猫头猫            console.log(res.isEnd);
32*ceb900cdS猫头猫            if (tag.id === currentTagRef.current) {
33*ceb900cdS猫头猫                setSheets(prev => [
34*ceb900cdS猫头猫                    ...prev,
35*ceb900cdS猫头猫                    ...res.data!.map(item =>
36*ceb900cdS猫头猫                        resetMediaItem(item, plugin.instance.platform),
37*ceb900cdS猫头猫                    ),
38*ceb900cdS猫头猫                ]);
39*ceb900cdS猫头猫            }
40*ceb900cdS猫头猫
41*ceb900cdS猫头猫            if (res.isEnd) {
42*ceb900cdS猫头猫                setStatus('done');
43*ceb900cdS猫头猫            } else {
44*ceb900cdS猫头猫                setStatus('idle');
45*ceb900cdS猫头猫            }
46*ceb900cdS猫头猫        } else {
47*ceb900cdS猫头猫            setStatus('done');
48*ceb900cdS猫头猫            setSheets([]);
49*ceb900cdS猫头猫        }
50*ceb900cdS猫头猫    }, [tag, status]);
51*ceb900cdS猫头猫
52*ceb900cdS猫头猫    useEffect(() => {
53*ceb900cdS猫头猫        query();
54*ceb900cdS猫头猫    }, [tag]);
55*ceb900cdS猫头猫
56*ceb900cdS猫头猫    return [query, sheets, status] as const;
57*ceb900cdS猫头猫}
58