import { createApp } from 'vue'
import Antd from 'ant-design-vue'
// 导入组件
import MarkdownPreview from './BoxMask.vue'
import snowy from '@/snowy'
let markdownPreviewInstance = null
let markdownPreviewApp = null

/**
 * 初始化 markdown 预览实例
 * @param {string} fileInfo 文件信息
 * @param {boolean} editable 是否可编辑
 * @param {Function} callback 回调函数
 */
const initInstanceMarkdownPreview = (fileInfo, editable, callback) => {
	const mountNode = document.createElement('div')
	markdownPreviewApp = createApp(MarkdownPreview, {
		fileInfo,
		editable,
		callback
	})
	// 注册 Ant Design Vue 组件
	markdownPreviewApp.use(Antd)
	markdownPreviewApp.use(snowy)
	markdownPreviewInstance = markdownPreviewApp.mount(mountNode)
	return mountNode
}

/**
 *  markdown 预览 Promise 函数
 * @returns {Promise} 抛出确认和取消回调函数
 */
const showMarkdownPreviewBox = (obj) => {
	// 非首次调用服务时，在 DOM 中移除上个实例
	if (markdownPreviewInstance !== null && markdownPreviewApp !== null) {
		markdownPreviewApp.unmount()
		markdownPreviewInstance = null
		markdownPreviewApp = null
	}

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

		document.body.appendChild(mountNode) //  挂载 DOM
		// 使用 setTimeout 替代 Vue.nextTick
		setTimeout(() => {
			if (markdownPreviewInstance) {
				markdownPreviewInstance.visible = true //  打开 markdown 预览遮罩层
			}
		}, 0)
	})
}

export default showMarkdownPreviewBox
