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