import { createApp, reactive, nextTick } from 'vue'
// 导入组件
import UploadFileBox from './Box.vue'
import uploader from 'vue-simple-uploader'
import 'vue-simple-uploader/dist/style.css'
import Antd from 'ant-design-vue'
import snowy from '@/snowy'
let appInstance = null
let vm = null
let currentPropsData = null // 保存当前的 props 数据

/**
 * 初始化上传文件实例
 */
const initInstanceUploadFile = (params, uploadWay, serviceEl, callType, callback) => {
	currentPropsData = reactive({
		params,
		uploadWay,
		serviceEl,
		callType,
		callback
	})

	const container = document.createElement('div')

	// 创建应用实例，但不直接传递 props
	appInstance = createApp(UploadFileBox)

	// 使用 provide 来提供响应式数据
	appInstance.provide('uploadProps', currentPropsData)

	appInstance.use(uploader)
	appInstance.use(Antd)
	appInstance.use(snowy)
	vm = appInstance.mount(container)
	document.body.appendChild(container)

	return { appInstance, vm, propsData: currentPropsData }
}

/**
 * 显示上传文件浮层 Promise 函数
 */
const showUploadFileBox = (obj) => {
	if (vm !== null && appInstance !== null && currentPropsData !== null) {
		// 更新响应式数据
		currentPropsData.params = obj.params
		currentPropsData.uploadWay = obj.uploadWay
		currentPropsData.serviceEl = obj.serviceEl
		currentPropsData.callType = obj.callType

		// 确保 Box.vue 中有 handlePrepareUpload 方法并且可以被外部调用
		if (typeof vm.handlePrepareUpload === 'function') {
			vm.handlePrepareUpload()
		} else {
			console.warn('handlePrepareUpload method not found on Box.vue instance')
		}
	} else {
		// 首次调用服务时创建实例
		return new Promise((resolve) => {
			const { propsData } = initInstanceUploadFile(obj.params, obj.uploadWay, obj.serviceEl, obj.callType, (res) => {
				resolve(res)
				// 服务取消或完成后卸载 DOM
				if ((res === 'cancel' || res === 'completed') && vm !== null && appInstance !== null) {
					appInstance.unmount()
					if (vm.$el && vm.$el.parentNode) {
						document.body.removeChild(vm.$el.parentNode)
					}
					appInstance = null
					vm = null
					currentPropsData = null
				}
			})

			nextTick(() => {
				if (vm && typeof vm.handlePrepareUpload === 'function') {
					vm.handlePrepareUpload()
				} else {
					console.warn('handlePrepareUpload method not found on Box.vue instance after mount')
				}
			})
		})
	}
}

// 直接导出函数，而不是包装在对象中
export default showUploadFileBox
