import { createApp } from 'vue'
import Antd from 'ant-design-vue'
// 导入组件
import ImgPreview from './BoxMask.vue'
import snowy from '@/snowy'

let imgPreviewInstance = null
let imgPreviewApp = null

/**
 * 初始化图片预览实例
 * @param {string} imgList 图片列表
 * @param {object} defaultIndex 当前查看的图片索引
 * @param {Function} callback 回调函数
 */
const initInstanceImgPreview = (imgList, defaultIndex, callback) => {
	const mountNode = document.createElement('div')
	imgPreviewApp = createApp(ImgPreview, {
		imgList,
		defaultIndex,
		callback
	})
	// 注册 Ant Design Vue 组件
	imgPreviewApp.use(Antd)
	imgPreviewApp.use(snowy)
	imgPreviewInstance = imgPreviewApp.mount(mountNode)
	return mountNode
}

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

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

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

export default showImgPreviewBox
