import { shallowRef, computed } from 'vue'
import { useMenu } from '@/hooks/menu'
import { ActionMenu, ActionMenuOptions } from './types'

export function useActionMenu<T>(options: ActionMenuOptions = {}) {
    const { authCode, preventDefault = true, queryFn } = options
    const { componentMap, getAuthButtons } = useMenu(authCode)

    // 当前激活的菜单
    const activeMenu = shallowRef<Partial<ActionMenu<T>>>({})

    // 当前打开的组件
    const asyncComponent = computed(() => {
        const { name = '' } = activeMenu.value
        return componentMap.get(name)
    })

    // 打开组件
    const openComponent = (e: ActionMenu<T>) => {
        if (preventDefault) {
            e.disabled = true
        }
        activeMenu.value = e
    }

    // 关闭组件
    const closeComponent = (refresh: boolean) => {
        const name = activeMenu.value.name
        if (preventDefault) {
            activeMenu.value.disabled = false
        }
        activeMenu.value = {}
        refresh && queryFn && queryFn(name)
    }

    return {
        componentMap,
        asyncComponent,
        activeMenu,
        getAuthButtons,
        openComponent,
        closeComponent,
    }
}