import { createApp } from 'vue'
import Antd from 'ant-design-vue'
// 导入组件
import CopyFileDialog from './Dialog.vue'
import snowy from '@/snowy'
let copyFileInstance = null
let copyFileApp = null

/**
 * 初始化复制文件实例
 * @param {object | array} fileInfo 要复制的文件信息
 * @param {Function} callback 回调函数
 */
const initInstanceCopyFile = (fileInfo, callback) => {
	const mountNode = document.createElement('div')
	copyFileApp = createApp(CopyFileDialog, {
		fileInfo,
		callback
	})
	// 注册 Ant Design Vue 组件
	copyFileApp.use(Antd)
	// 注册全局函数
	copyFileApp.use(snowy)
	copyFileInstance = copyFileApp.mount(mountNode)
	return mountNode
}

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

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

		document.body.appendChild(mountNode) // 挂载 DOM
		// 使用 setTimeout 替代 Vue.nextTick 确保组件已完全挂载
		setTimeout(() => {
			if (copyFileInstance) {
				copyFileInstance.visible = true // 打开对话框
			}
		}, 0)
	})
}

export default showCopyFileDialog
