import { createVNode, render as VueRender, type Component } from "vue";
import zhCn from "element-plus/es/locale/lang/zh-cn";

export interface CreateModalOptions {
    [key: string]: any
    title: string
    visible?: boolean
    width?: number | string
    onConfirm?: Fn
    onCancel?: Fn
}

export interface ModalProps {
    [key: string]: any
    title: string
    visible: boolean
    width: number | string
    onConfirm?: Fn
    onCancel?: Fn
}
/**挂载 */
function render<T extends Component>(Component: T, props: Partial<ModalProps>, container: HTMLElement) {
    const vNode = createVNode(Component, props)
    VueRender(vNode, container)
    document.body.appendChild(container)
}
/**销毁 */
function destroy(container: HTMLElement) {
    document.body.removeChild(container)
}

export function useCreateModal<T extends Component>(Component: T) {
    const container = document.createElement('div')

    function close() {
        VueRender(null, container)
        destroy(container)
    }

    const commandComponent = (options: CreateModalOptions) => {
        const propsData: Partial<ModalProps> = {
            ...options,
            onConfirm: function (...args) {
                if (options.onConfirm) {
                    options.onConfirm(...args)
                }
            },
            onCancel: function () {
                if (options.onCancel) {
                    options.onCancel()
                }
                close()
            },
        }

        render(Component, propsData, container)
    }

    commandComponent.close = close

    return commandComponent
}