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

let deleteFileInstance = null
let deleteFileApp = null

/**
 * 初始化删除文件实例
 * @param {boolean} isBatchOperation 是否为批量删除：true - 批量删除，false - 单文件删除
 * @param {object | array} fileInfo 文件信息，批量时为数组、单文件时为对象
 * @param {number} deleteMode 删除模式：1-删除到回收站 2-彻底删除
 * @param {Function} callback 回调函数
 */
const initInstanceDeleteFile = (isBatchOperation, fileInfo, deleteMode, callback) => {
	const mountNode = document.createElement('div')
	deleteFileApp = createApp(DeleteFileDialog, {
		isBatchOperation,
		fileInfo,
		deleteMode,
		callback
	})
	// 注册 Ant Design Vue 组件
	deleteFileApp.use(Antd)
	deleteFileInstance = deleteFileApp.mount(mountNode)
	return mountNode
}

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

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

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

export default showDeleteFileDialog
