import { ref, reactive, watch } from 'vue'

/**
 * 滚动显示隐藏元素
 * @param defaultOpacity 默认透明度
 * @returns 
 */
export function useScrollVisibility(defaultOpacity = 1) {
    // 滚动条高度
    const scrollTop = ref(0);
    // 目标元素
    const visibilityElement = ref<HTMLElement>();
    // 滚动元素样式
    const scrollElementStyles = reactive({
        paddingTop: '0px',
    })

    // 绑定元素
    const bindVisibilityElement = (el: HTMLElement) => {
        const { clientHeight, style } = el;
        visibilityElement.value = el;
        scrollElementStyles.paddingTop = (defaultOpacity ? clientHeight : 0) + 'px';
        style.setProperty('opacity', defaultOpacity.toString());
    }

    // 监听滚动条位置
    watch(scrollTop, (val) => {
        if (visibilityElement.value) {
            const { clientHeight, style } = visibilityElement.value;
            const alpha = (defaultOpacity ? (clientHeight * 2 - val) : (val - clientHeight)) / clientHeight; // 根据默认透明度判断渐变方向

            if (alpha > 1) {
                style.setProperty('opacity', '1');
            } else if (alpha < 0) {
                style.setProperty('opacity', '0');
            } else {
                style.setProperty('opacity', alpha.toString());
            }
        }
    })

    return {
        scrollTop,
        scrollElementStyles,
        bindVisibilityElement,
    }
}