import { ref, onMounted, onUnmounted, onActivated, onDeactivated, nextTick } from 'vue';
import { useWindowSize, useThrottleFn } from '@vueuse/core';
/**
 * 初始化屏幕的高度
 */
export default function useResizeHeight(defaultHeight = 243) {
    // 是否挂着状态
    let mounted: boolean;
    //表格的自适应高度
    const tableHeight = ref(0);
    // 获取屏幕高度
    const { height } = useWindowSize()

    // 使用节流防止多次触发屏幕
    const throttledFn = useThrottleFn(() => {
        nextTick(() => {
            tableHeight.value = height.value - defaultHeight;
        })
    }, 500, true)

    const init = () => {
        window.addEventListener('resize', throttledFn)
        nextTick(() => {
            mounted = true
            tableHeight.value = height.value - defaultHeight;
        })
    }

    // 初始化高度、销毁事件
    onMounted(() => {
        init()
    })
    onUnmounted(() => {
        window.removeEventListener('resize', throttledFn)
    })
    onActivated(() => {
        if (mounted) {
            init()
        }
    })
    onDeactivated(() => {
        window.removeEventListener('resize', throttledFn)
    })

    return {
        tableHeight
    }
}