import { createApp } from 'vue'
import Antd from 'ant-design-vue'
import router from '@/router' // 添加这行导入
import snowy from '@/snowy' // 添加这行导入
// 导入组件
import ContextMenu from './Box.vue'

let contextMenuInstance = null
let contextMenuApp = null

/**
 * 初始化右键菜单实例
 * @param {string} selectedFile 文件信息，如果此值为 undefined，证明是在空白触右键
 * @param {object} domEvent 当前右键点击的元素
 * @param {} serviceEl 调用当前服务的组件实例
 * @param {} callType 是否组件本身
 * @param {Function} callback 回调函数
 */
const initInstanceContextMenu = (selectedFile, domEvent, serviceEl, callType, callback) => {
	const mountNode = document.createElement('div')
	contextMenuApp = createApp(ContextMenu, {
		selectedFile,
		domEvent,
		serviceEl,
		callType,
		callback
	})
	// 注册 Ant Design Vue 组件
	contextMenuApp.use(Antd)
	contextMenuApp.use(router) // 添加这行
	contextMenuApp.use(snowy) // 添加这行，注册 snowy 插件
	contextMenuInstance = contextMenuApp.mount(mountNode)
	return mountNode
}

/**
 * 右键菜单 Promise 函数
 * @returns {Promise} 抛出确认和取消回调函数
 */
const showContextMenuBox = (obj) => {
	// 非首次调用服务时，在 DOM 中移除上个实例
	if (contextMenuInstance !== null && contextMenuApp !== null) {
		contextMenuApp.unmount()
		contextMenuInstance = null
		contextMenuApp = null
	}

	let { selectedFile, domEvent, serviceEl, callType } = obj
	return new Promise((resolve) => {
		const mountNode = initInstanceContextMenu(selectedFile, domEvent, serviceEl, callType, (res) => {
			resolve(res)
			// 服务取消时卸载 DOM
			if (res === 'cancel' && contextMenuInstance !== null) {
				contextMenuApp.unmount()
				// 添加检查，确保节点存在于document.body中
				if (document.body.contains(mountNode)) {
					document.body.removeChild(mountNode)
				}
				contextMenuInstance = null
				contextMenuApp = null
			}
		})

		document.body.appendChild(mountNode) //  挂载 DOM
		// 使用 setTimeout 替代 Vue.nextTick
		setTimeout(() => {
			if (contextMenuInstance) {
				contextMenuInstance.handleOpenContextMenu() //  开始计算右键菜单需要显示的位置
			}
		}, 0)
	})
}

// 添加关闭事件
showContextMenuBox.close = () => {
	if (contextMenuInstance !== null && contextMenuApp !== null) {
		contextMenuApp.unmount()
		contextMenuInstance = null
		contextMenuApp = null
	}
}

export default showContextMenuBox
