useOfflineBookingCachePolling.js 2.6 KB
import { ref, onMounted, onUnmounted } from 'vue'
import { refresh_offline_booking_cache } from '@/composables/useOfflineBookingCache'

let polling_timer_id = null
let polling_running = false
let polling_in_flight = false
let polling_ref_count = 0

/**
 * @description: 刷新离线预约缓存一次
 * @param {Object} options 选项
 * @param {Boolean} options.force 是否强制刷新
 */

const run_refresh_once = async (options) => {
    if (polling_in_flight) return
    polling_in_flight = true
    try {
        await refresh_offline_booking_cache({ force: !!options?.force })
    } finally {
        polling_in_flight = false
    }
}

/**
 * @description: 启动离线预约缓存轮询
 * @param {Object} options 选项
 * @param {Number} options.interval_ms 轮询间隔,单位毫秒
 * @param {Boolean} options.immediate 是否立即刷新一次
 */

export const start_offline_booking_cache_polling = (options) => {
    const interval_ms = Number(options?.interval_ms || 60000)
    if (polling_running) return

    polling_running = true

    if (options?.immediate !== false) {
        run_refresh_once(options)
    }

    polling_timer_id = setInterval(() => {
        run_refresh_once(options)
    }, interval_ms)
}

/**
 * @description: 停止离线预约缓存轮询
 */

export const stop_offline_booking_cache_polling = () => {
    if (!polling_timer_id) {
        polling_running = false
        return
    }
    clearInterval(polling_timer_id)
    polling_timer_id = null
    polling_running = false
}

/**
 * @description: 用于管理离线预约缓存轮询的组合式函数
 * @param {Object} options 选项
 * @param {Boolean} options.enabled 是否启用轮询
 * @param {Boolean} options.auto 是否自动启动轮询
 * @param {Number} options.interval_ms 轮询间隔,单位毫秒
 * @param {Boolean} options.immediate 是否立即刷新一次
 */

export const use_offline_booking_cache_polling = (options) => {
    const is_running = ref(false)
    const enabled = options?.enabled !== false

    const start = () => {
        if (!enabled) return
        polling_ref_count += 1
        start_offline_booking_cache_polling(options)
        is_running.value = true
    }

    const stop = () => {
        if (!is_running.value) return
        polling_ref_count = Math.max(0, polling_ref_count - 1)
        if (polling_ref_count === 0) {
            stop_offline_booking_cache_polling()
        }
        is_running.value = false
    }

    onMounted(() => {
        if (options?.auto !== false) start()
    })

    onUnmounted(() => {
        stop()
    })

    return {
        is_running,
        start,
        stop,
    }
}