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

let renameFileInstance = null
let renameFileApp = null

/**
 * 初始化重命名文件实例
 * @param {string} oldFileName 文件原本的名称
 * @param {string} userFileId 文件 ID
 * @param {Function} callback 回调函数
 */
const initInstanceRenameFile = (oldFileName, userFileId, callback) => {
	const mountNode = document.createElement('div')
	renameFileApp = createApp(RenameFileDialog, {
		oldFileName,
		userFileId,
		callback
	})
	// 注册 Ant Design Vue 组件
	renameFileApp.use(Antd)
	renameFileInstance = renameFileApp.mount(mountNode)
	return mountNode
}

/**
 * 重命名文件 Promise 函数
 * @returns {Promise} 抛出确认和取消回调函数
 */
const showRenameFileDialog = (obj) => {
	// 非首次调用服务时，在 DOM 中移除上个实例
	if (renameFileInstance !== null && renameFileApp !== null) {
		renameFileApp.unmount()
		renameFileInstance = null
		renameFileApp = null
	}

	let { oldFileName, userFileId } = obj
	return new Promise((resolve) => {
		const mountNode = initInstanceRenameFile(oldFileName, userFileId, (res) => {
			resolve(res)
			// 服务取消时卸载 DOM
			if (res === 'cancel' && renameFileInstance !== null) {
				renameFileApp.unmount()
				document.body.removeChild(mountNode)
				renameFileInstance = null
				renameFileApp = null
			}
		})

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

export default showRenameFileDialog
