import modalFrame from "./modalFrame.vue"
import { createApp, DefineComponent, App } from "vue"
import ElementPlus from "element-plus"
import zhCn from "element-plus/es/locale/lang/zh-cn"

export const modalFrameSet = new Set<App<Element>>()
export function closeAllModalFrame() {
   modalFrameSet.forEach(modalFrameItem => {
      if (modalFrameItem) {
         modalFrameSet.delete(modalFrameItem)
         modalFrameItem.unmount()
      }
   })
}

type vmType = InstanceType<typeof modalFrame>
// eslint-disable-next-line @typescript-eslint/ban-types
export interface modalFrameOptType<T extends DefineComponent<{}, {}, any, any, any, any, any, any, any, unknown, any>> {
   template: T
   className?: string // 传入的class,可以依靠这个class控制内部样式
   modalData: ExtractVByK<InstanceType<T>["$props"], "modalData">
   width?: string | number //宽度
   height?: string | number //高度
   onCancel?: (vm: vmType, instance: InstanceType<T>) => any //取消回调  返回vm
   onOk?: (vm: vmType, instance: InstanceType<T>) => any //确认回调 返回 vm
   onClose?: (vm: vmType, instance: InstanceType<T>) => any //关闭回调 返回 vm
   title?: string //弹窗title
   btnShow?: [boolean?, boolean?] //是否显示按钮，[true,false],可以控制按钮的显示隐藏
   btnTit?: [string?, string?] // 按钮的文字，["确认"]
   maskClose?: boolean //点击遮罩关闭
   draggable?: boolean //是否可以拖动
}

// eslint-disable-next-line @typescript-eslint/ban-types
const instanceModalFrame = <T extends DefineComponent<{}, {}, any, any, any, any, any, any, any, unknown, any>>(
   opt: ExtractVByK<InstanceType<T>["$props"], "modalData"> extends Record<string, any>
      ? modalFrameOptType<T>
      : Omit<modalFrameOptType<T>, "modalData">
) => {
   const modalFrameApp = createApp(modalFrame, { ...opt })
   modalFrameApp.use(ElementPlus, {
      locale: zhCn
   })
   const vmModalFrame = modalFrameApp.mount(document.createElement("div")) as vmType
   vmModalFrame.vm = vmModalFrame
   vmModalFrame.vmApp = modalFrameApp
   modalFrameSet.add(vmModalFrame.vmApp)
   document.body.appendChild(vmModalFrame.$el)
   vmModalFrame.$nextTick(() => {
      vmModalFrame.show = true
   })
}
export default instanceModalFrame
