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

let authWeChatInstance = null
let authWeChatApp = null

/**
 * 初始化微信认证实例
 */
const initInstanceAuthWeChat = (callback) => {
	const mountNode = document.createElement('div')
	authWeChatApp = createApp(AuthWeChatDialog, {
		callback
	})
	// 注册 Ant Design Vue 组件
	authWeChatApp.use(Antd)
	authWeChatInstance = authWeChatApp.mount(mountNode)
	return mountNode
}

/**
 * 微信认证 Promise 函数
 * @returns {Promise} 抛出确认和取消回调函数
 */
const showAuthWeChatDialog = () => {
	// 非首次调用服务时，在 DOM 中移除上个实例
	if (authWeChatInstance !== null && authWeChatApp !== null) {
		authWeChatApp.unmount()
		authWeChatInstance = null
		authWeChatApp = null
	}

	return new Promise((resolve) => {
		const mountNode = initInstanceAuthWeChat((res) => {
			resolve(res)
			// 服务取消时卸载 DOM
			if (res === 'cancel' && authWeChatInstance !== null) {
				authWeChatApp.unmount()
				document.body.removeChild(mountNode)
				authWeChatInstance = null
				authWeChatApp = null
			}
		})

		document.body.appendChild(mountNode) // 挂载 DOM
		// 使用 nextTick 确保组件已完全挂载
		setTimeout(() => {
			if (authWeChatInstance) {
				authWeChatInstance.getWeChatAuthStateData()
			}
		}, 0)
	})
}

export default showAuthWeChatDialog
