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

let saveShareFileInstance = null
let saveShareFileApp = null

/**
 * 初始化保存分享文件实例
 * @param {array} userFileIds 要保存的文件ID数组
 * @param {string} shareBatchNum 分享批次号
 * @param {Function} callback 回调函数
 */
const initInstanceSaveShareFile = (userFileIds, shareBatchNum, callback) => {
	const mountNode = document.createElement('div')
	saveShareFileApp = createApp(SaveShareFileDialog, {
		userFileIds,
		shareBatchNum,
		callback
	})
	// 注册 Ant Design Vue 组件
	saveShareFileApp.use(Antd)
	saveShareFileInstance = saveShareFileApp.mount(mountNode)
	return mountNode
}

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

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

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

export default showSaveShareFileDialog
