import { h, nextTick, render, ref } from "vue";

const dialog = (aRender: any, option: any) => {
  return new Promise((resolve, reject) => {
    const divDom = document.createElement("div");
    document.body.appendChild(divDom);

    // 👇 创建 ref 来引用组件实例
    // const componentRef = ref();

    const onSubmit = (data: any) => {
      resolve(data);
      onClosed();
      // componentRef.value.hide(); // 调用组件内部方法
    };

    const onCancel = () => {
      reject();
      onClosed();
    };

    const onClosed = () => {
      // nextTick(() => {
      console.log("closeddd :>> ");
      render(null, divDom);
      divDom.remove();
      // });
    };

    const vNode = h(aRender, {
      ...option,
      modelValue: true,
      onSubmit,
      onCancel,
      onClose: onCancel,
      onClosed

      // 👇 将组件实例赋值给 componentRef
      // ref: componentRef
    });
    render(vNode, divDom);

    // // 👇 提供一个外部可调用的方法来触发组件内部函数
    // (dialog as any).invokeComponentMethod = () => {
    //   if (componentRef.value) {
    //     console.log("componentRef valll:>> ", componentRef.value);
    //     componentRef.value.show(); // 调用组件内部方法
    //   }
    // };
  });
};
export default dialog;
