import { createApp } from 'vue'
import Antd from 'ant-design-vue'
// 导入组件
import MoveFileDialog from './Dialog.vue'
import snowy from '@/snowy'
let moveFileInstance = null
let moveFileApp = null

/**
 * 初始化移动文件实例
 * @param {boolean} isBatchOperation 是否为批量移动：true - 批量移动，false - 单文件移动
 * @param {object | array} fileInfo 文件信息，单文件移动时，为单个文件对象；批量移动时，为文件数组
 * @param {Function} callback 回调函数
 */
const initInstanceMoveFile = (isBatchOperation, fileInfo, callback) => {
	const mountNode = document.createElement('div')
	moveFileApp = createApp(MoveFileDialog, {
		isBatchOperation,
		fileInfo,
		callback
	})
	// 注册 Ant Design Vue 组件
	moveFileApp.use(Antd)
	moveFileApp.use(snowy)
	moveFileInstance = moveFileApp.mount(mountNode)
	return mountNode
}

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

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

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

export default showMoveFileDialog
