import { createApp } from 'vue'
import Antd from 'ant-design-vue'
import router from '@/router'
// 导入组件
import FileDetailDialog from './Dialog.vue'
import snowy from '@/snowy'
let fileDetailInstance = null
let fileDetailApp = null

/**
 * 初始化文件详情文件实例
 * @param {object | array} fileInfo 文件信息，批量时为数组、单文件时为对象
 * @param {Function} callback 回调函数
 */
const initInstanceFileDetail = (fileInfo, callback) => {
	const mountNode = document.createElement('div')
	fileDetailApp = createApp(FileDetailDialog, {
		fileInfo,
		callback
	})
	// 注册 Ant Design Vue 组件
	fileDetailApp.use(Antd)
	fileDetailApp.use(router)
	fileDetailApp.use(snowy)
	fileDetailInstance = fileDetailApp.mount(mountNode)
	return mountNode
}

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

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

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

export default showFileDetailDialog
