import { ref, computed, onMounted, watch, toRefs } from 'vue' import { useRootStore } from '@/store/root' import { useRouter } from 'vue-router' import { getBackTime } from '@/http/api/base' export const useHandleScreen = (callback: () => void) => { const MIN_TIME = 0 const MAX_TIME = 5 const CHECK_TIME = 1000 const DELAY_CHECK_TIME = 400 const router = useRouter() const store = useRootStore() const { nativeMethods, mapStatus } = toRefs(store) const totalTime = ref<[number, number]>([60, 60]) //总时间 const toIndexTime = ref(60) //回首页的时间 const toWallpaperTime = ref(60) //回屏保的时间 const isWallpaper = ref(false) //回首页是否已经跑完 const showCountDownDialog = ref(false) const title = computed(() => (isWallpaper.value ? '即将进入屏幕保护' : '即将进入首页')) const toIndexInterval = ref() const toWallpaperInterval = ref() const delayCheckRoutePathTimer = ref() function sleepToIndex() { isWallpaper.value = false return new Promise(resolve => { toIndexInterval.value = setInterval(() => { toIndexTime.value-- if (toIndexTime.value <= MIN_TIME) { clearInterval(toIndexInterval.value) toIndexTime.value = totalTime.value[0] resolve() } }, CHECK_TIME) }) } function sleepToWallpaper() { isWallpaper.value = true return new Promise(resolve => { toWallpaperInterval.value = setInterval(() => { toWallpaperTime.value-- if (toWallpaperTime.value <= MIN_TIME) { clearInterval(toWallpaperInterval.value) toWallpaperTime.value = totalTime.value[1] isWallpaper.value = false resolve() } }, CHECK_TIME) }) } //跳转屏保挂载到全局 供app使用 window.sleepToWallpaper = () => { checkHandleScreen() } function checkHandleScreen() { toIndexTime.value = totalTime.value[0] toWallpaperTime.value = totalTime.value[1] clearInterval(toIndexInterval.value) clearInterval(toWallpaperInterval.value) clearTimeout(delayCheckRoutePathTimer.value) delayCheckRoutePathTimer.value = setTimeout(async () => { if (router.currentRoute.value.fullPath !== '/') { await sleepToIndex() callback() } //调用原生方法 判断有无节目 if (!nativeMethods.value?.hasProgram()) { return } await sleepToWallpaper() callback() nativeMethods.value?.goScreenSave() }, DELAY_CHECK_TIME) } //监听时间 大于等于0且小于等于5时显示弹框 watch([toIndexTime, toWallpaperTime], ([indexTime, wallpaperTime]) => { showCountDownDialog.value = (indexTime >= MIN_TIME && indexTime <= MAX_TIME) || (wallpaperTime >= MIN_TIME && wallpaperTime <= MAX_TIME) }) watch(mapStatus, async (newVal: boolean) => { //当地图加载成功之后自动触发一次屏保弹框以便能进入屏保 if (newVal) { if (!nativeMethods.value?.hasProgram()) { return } await checkHandleScreen() } }) onMounted(() => { //获取返回首页和进入屏保的具体时间 getBackTime().then(({ data }) => { const noWallpaper = data[1] totalTime.value = noWallpaper ? [data[0], -1] : data toIndexTime.value = data[0] toWallpaperTime.value = noWallpaper ? -1 : data[1] }) }) return { isWallpaper, showCountDownDialog, title, totalTime, toIndexTime, toWallpaperTime, checkHandleScreen } }