import { useThrottleFn } from '@vueuse/shared';
import { ref, computed, reactive, unref, onMounted, onUnmounted, nextTick } from 'vue'

interface NavBar {
    name: string//名称
    url: string//跳转路径
    show: boolean//是否显示
    children?: Partial<NavBar>[]
}

/**
 * 导航栏处理
 */
function useNavigationBar(props) {
    const navbarRef = ref<HTMLElement | null>(null);
    const stateNavBar = reactive({
        currentLeft: 0,
        clientWidth: 0,
        clientList: [] as Element[]
    })

    // 更新二级导航栏容器位置
    const updateOffset = computed(() => {
        const isWidth = stateNavBar.currentLeft + 640 > stateNavBar.clientWidth
        const position = isWidth ? { right: 0 } : { left: 0 }
        return {
            ...position
        }
    })
    // 默认背景颜色
    const navbarWarpStyle = computed(() => {
        return {
            '--base-bg': props.navBg
        }
    })

    // 移入
    const onMouseover = (item) => {
        item.show = !item.show
    }
    // 初始化屏幕宽度
    const initWidth = () => {
        const navbarDom = unref(navbarRef);
        if (!navbarDom) return;
        const pdClientWidth = document.documentElement.clientWidth - navbarDom.clientWidth
        // 当前导航栏相对于屏幕的宽度
        stateNavBar.clientWidth = navbarDom.clientWidth + pdClientWidth
        // 一级菜单的dom节点
        const nodeList = navbarDom.querySelectorAll('.nav-list .item')
        stateNavBar.clientList = Array.from(nodeList);
        nextTick(() => {
            // 初始化二级导航菜单的位置
            nodeList.forEach((item, index) => {
                const left = boundingInfo(stateNavBar.clientList[index]).left
                const isWidth = Math.round(left) + 680 > stateNavBar.clientWidth
                const warp = item.querySelector('.warp') as HTMLElement
                if (isWidth) {
                    warp.style.removeProperty("left")
                    warp.style.right = '0px'
                } else {
                    warp.style.removeProperty("right")
                    warp.style.left = '0px'
                }
            });
        })
    }
    // 移出
    const onMouseout = (item) => {
        item.show = !item.show
    }
    const boundingInfo = (target) => {
        return target.getBoundingClientRect()
    }

    // 使用节流防止多次触发屏幕
    const throttledFn = useThrottleFn(() => {
        initWidth()
    }, 3000, true)

    onMounted(() => {
        initWidth()
        window.addEventListener('resize', throttledFn)
    })
    onUnmounted(() => {
        window.removeEventListener('resize', throttledFn)
    })

    return {
        navbarRef,
        stateNavBar,
        updateOffset,
        navbarWarpStyle,
        onMouseover,
        onMouseout,
    }
}

export {
    useNavigationBar,
    NavBar
}