xref: /MusicFree/src/utils/timingClose.ts (revision 15900d057ad4df766b2f9ea5b48f92a8ce2664db)
1import TrackPlayer from '@/core/trackPlayer';
2import NativeUtils from '@/native/utils';
3import StateMapper from '@/utils/stateMapper';
4import {useEffect, useRef, useState} from 'react';
5import BackgroundTimer from 'react-native-background-timer';
6// import TrackPlayer from "react-native-track-player";
7
8let deadline: number | null = null;
9const stateMapper = new StateMapper(() => deadline);
10// let closeAfterPlayEnd = false;
11// const closeAfterPlayEndStateMapper = new StateMapper(() => closeAfterPlayEnd);
12let timerId: any;
13
14function setTimingClose(_deadline: number | null) {
15    deadline = _deadline;
16    stateMapper.notify();
17    timerId && BackgroundTimer.clearTimeout(timerId);
18    if (_deadline) {
19        timerId = BackgroundTimer.setTimeout(async () => {
20            // todo: 播完整首歌再关闭
21            await TrackPlayer.reset();
22            NativeUtils.exitApp();
23            // if(closeAfterPlayEnd) {
24            //     TrackPlayer.addEventListener()
25            // } else {
26            //     // 立即关闭
27            //     NativeUtils.exitApp();
28            // }
29        }, _deadline - Date.now());
30    } else {
31        timerId = null;
32    }
33}
34
35function useTimingClose() {
36    const _deadline = stateMapper.useMappedState();
37    const [countDown, setCountDown] = useState(
38        deadline ? deadline - Date.now() : null,
39    );
40    const intervalRef = useRef<any>();
41
42    useEffect(() => {
43        // deadline改变时,更新定时器
44        // 清除原有的定时器
45        intervalRef.current && clearInterval(intervalRef.current);
46        intervalRef.current = null;
47
48        // 清空定时
49        if (!_deadline || _deadline <= Date.now()) {
50            setCountDown(null);
51            return;
52        } else {
53            // 更新倒计时
54            setCountDown(Math.max(_deadline - Date.now(), 0) / 1000);
55            intervalRef.current = setInterval(() => {
56                setCountDown(Math.max(_deadline - Date.now(), 0) / 1000);
57            }, 1000);
58        }
59    }, [_deadline]);
60
61    return countDown;
62}
63
64export {setTimingClose, useTimingClose};
65