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

let videoPreviewInstance = null
let videoPreviewApp = null

/**
 * 初始化视频预览实例
 * @param {Array} videoList 视频列表
 * @param {Number} defaultIndex 当前查看的视频索引
 * @param {Function} callback 回调函数
 */
const initInstanceVideoPreview = (videoList, defaultIndex, callback) => {
	const mountNode = document.createElement('div')
	videoPreviewApp = createApp(VideoPreview, {
		videoList,
		defaultIndex,
		callback
	})
	// 注册 Ant Design Vue 组件
	videoPreviewApp.use(Antd)
	videoPreviewApp.use(snowy)
	videoPreviewInstance = videoPreviewApp.mount(mountNode)
	return mountNode
}

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

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

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

export default showVideoPreviewBox
