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

let restoreFileInstance = null
let restoreFileApp = null

/**
 * 初始化还原文件实例
 * @param {string} deleteBatchNum 删除批次号
 * @param {number} filePath 文件路径
 * @param {Function} callback 回调函数
 */
const initInstanceRestoreFile = (deleteBatchNum, filePath, callback) => {
	const mountNode = document.createElement('div')
	restoreFileApp = createApp(RestoreFileDialog, {
		deleteBatchNum,
		filePath,
		callback
	})
	// 注册 Ant Design Vue 组件
	restoreFileApp.use(Antd)
	restoreFileInstance = restoreFileApp.mount(mountNode)
	return mountNode
}

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

	let { deleteBatchNum, filePath } = obj
	return new Promise((resolve) => {
		const mountNode = initInstanceRestoreFile(deleteBatchNum, filePath, (res) => {
			resolve(res)
			// 服务取消时卸载 DOM
			if (res === 'cancel' && restoreFileInstance !== null) {
				restoreFileApp.unmount()
				document.body.removeChild(mountNode)
				restoreFileInstance = null
				restoreFileApp = null
			}
		})

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

export default showRestoreFileDialog
