import { ref } from 'vue'
//import { v4 } from 'uuid'

//const componentMap = new Map()

/**
 * @param callback 组件关闭时的回调
 * @returns 
 */
export function useComponent(callback?: (componentName?: string) => void) {
    //const uuid = v4()
    const components = new Set<string>() // 已打开的组件列表
    const componentId = ref<string>() // 当前显示的组件
    const componentRef = ref() // 组件实例

    /**
     * 是否存在组件
     * @returns 
     */
    const hasComponent = () => {
        return components.size > 0
    }

    /**
     * 打开组件
     * @param componentName 
     */
    const openComponent = (componentName: string) => {
        console.log('打开组件：' + componentName)
        components.add(componentName)
        componentId.value = componentName
    }

    /**
     * 关闭组件
     * @param isCallback 
     */
    const closeComponent = (isCallback?: boolean) => {
        const componentName = componentId.value
        if (componentName) {
            console.log('关闭组件：' + componentName)
            components.delete(componentName)
            componentId.value = [...components.values()].pop()

            // 是否刷新数据
            if (isCallback && callback) {
                callback(componentName)
            }
        }
    }

    /**
     * 组件关闭守卫
     * @returns 
     */
    const closeComponentEach = () => {
        if (hasComponent()) {
            const { closed } = componentRef.value ?? {}
            if (closed instanceof Function) {
                closed()
            } else {
                closeComponent()
            }
            return false
        }
        return true
    }

    return {
        componentId,
        componentRef,
        hasComponent,
        openComponent,
        closeComponent,
        closeComponentEach,
    }
}