import { createApp } from 'vue'
import Antd from 'ant-design-vue'
// 导入组件
import ShareFileDialog from './Dialog.vue'
import snowy from '@/snowy'
let shareFileInstance = null
let shareFileApp = null

/**
 * 初始化分享文件实例
 * @param {array} fileInfo 要分享的文件数组
 * @param {Function} callback 回调函数
 */
const initInstanceShareFile = (fileInfo, callback) => {
	const mountNode = document.createElement('div')
	shareFileApp = createApp(ShareFileDialog, {
		fileInfo,
		callback
	})
	// 注册 Ant Design Vue 组件
	shareFileApp.use(Antd)
	shareFileApp.use(snowy)
	shareFileInstance = shareFileApp.mount(mountNode)
	return mountNode
}

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

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

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

export default showShareFileDialog
