import { createApp } from 'vue'
import Antd from 'ant-design-vue'
// 导入组件
import AddFolderDialog from './Dialog.vue'

let addFolderInstance = null
let addFolderApp = null

/**
 * 初始化新建文件夹实例
 * @param {string} filePath 新建文件的父路径
 * @param {Function} callback 回调函数
 */
const initInstanceAddFolder = (filePath, callback) => {
	const mountNode = document.createElement('div')
	addFolderApp = createApp(AddFolderDialog, {
		filePath,
		callback
	})
	// 注册 Ant Design Vue 组件
	addFolderApp.use(Antd)
	addFolderInstance = addFolderApp.mount(mountNode)
	return mountNode
}

/**
 * 新建文件夹 Promise 函数
 * @returns {Promise} 抛出确认和取消回调函数
 */
const showAddFolderDialog = ({ filePath }) => {
	// 非首次调用服务时，在 DOM 中移除上个实例
	if (addFolderInstance !== null && addFolderApp !== null) {
		addFolderApp.unmount()
		addFolderInstance = null
		addFolderApp = null
	}

	return new Promise((resolve) => {
		const mountNode = initInstanceAddFolder(filePath, (res) => {
			resolve(res)
			// 服务取消时卸载 DOM
			if (res === 'cancel' && addFolderInstance !== null) {
				addFolderApp.unmount()
				document.body.removeChild(mountNode)
				addFolderInstance = null
				addFolderApp = null
			}
		})

		document.body.appendChild(mountNode) // 挂载 DOM
		// 使用 setTimeout 替代 Vue.nextTick
		setTimeout(() => {
			if (addFolderInstance) {
				addFolderInstance.visible = true // 打开对话框
			}
		}, 0)
	})
}

export default showAddFolderDialog
