import {onPageScroll} from '@dcloudio/uni-app'
import {ref, onActivated, onDeactivated, watch} from 'vue'
import {injectLocal, provideLocal} from "@vueuse/core";

const injectKey = Symbol('PAGE_SCROLL')

export const useProvidePageScroll = function () {
    const scrollTop = ref(0)
    const scrollTopCache = ref(0)

    onPageScroll((e) => {
        scrollTop.value = e.scrollTop
    })

    // onPageScroll貌似是个全局事件，
    // 用onActivated，onDeactivated来尝试修复页面跳转导致的scrollTop被重置的问题
    onDeactivated(() => scrollTopCache.value = scrollTop.value)
    onActivated(() => scrollTop.value = scrollTopCache.value)

    // watch(scrollTop, val => console.log('scrollTop set', val)) // 调试用
    provideLocal(injectKey, {scrollTop, scrollTopCache}) // 形成解构模式
    return scrollTop
}

export const useInjectPageScroll = function () {
    return injectLocal(injectKey)
}
