// @ts-nocheck

// #ifdef APP-NVUE
// 當編譯環境是 APP-NVUE 時，引入 uni.requireNativePlugin('dom')，具體插件用途未知
const dom = uni.requireNativePlugin('dom')
// #endif

/** 
 * 獲取節點信息
 * @param selector 選擇器字符串
 * @param context ComponentInternalInstance 對象
 * @param node 是否獲取node
 * @returns 包含節點信息的 Promise 對象
 */
export function getRect(selector : string, context : ComponentInternalInstance, node: boolean = false) {
	// 之前是個對象，現在改成實例，防止舊版會報錯
	if(context== null) {
		return Promise.reject('context is null')
	}
	if(context.context){
		context = context.context
	}
	// #ifdef MP || VUE2
	if (context.proxy) context = context.proxy
	// #endif
	return new Promise<UniNamespace.NodeInfo>((resolve, reject) => {
		// #ifndef APP-NVUE
		const dom = uni.createSelectorQuery().in(context).select(selector);
		const result = (rect: UniNamespace.NodeInfo) => {
			if (rect) {
				resolve(rect)
			} else {
				reject('no rect')
			}
		}
		
		if (!node) {
			dom.boundingClientRect(result).exec()
		} else {
			dom.fields({
				node: true,
				size: true,
				rect: true
			}, result).exec()
		}
		// #endif
		// #ifdef APP-NVUE
		let { context } = options
		if (/#|\./.test(selector) && context.refs) {
			selector = selector.replace(/#|\./, '')
			if (context.refs[selector]) {
				selector = context.refs[selector]
				if(Array.isArray(selector)) {
					selector = selector[0]
				}
			}
		}
		dom.getComponentRect(selector, (res) => {
			if (res.size) {
				resolve(res.size)
			} else {
				reject('no rect')
			}
		})
		// #endif
	});
};


export function getAllRect(selector : string, context: ComponentInternalInstance, node:boolean = false) {
	if(context== null) {
		return Promise.reject('context is null')
	}
	// #ifdef MP || VUE2
	if (context.proxy) context = context.proxy
	// #endif
	return new Promise<UniNamespace.NodeInfo>((resolve, reject) => {
		// #ifndef APP-NVUE
		const dom = uni.createSelectorQuery().in(context).selectAll(selector);
		const result = (rect: UniNamespace.NodeInfo[]) => {
			if (rect) {
				resolve(rect)
			} else {
				reject('no rect')
			}
		}
		if (!node) {
			dom.boundingClientRect(result).exec()
		} else {
			dom.fields({
				node: true,
				size: true,
				rect: true
			}, result).exec()
		}
		// #endif
		// #ifdef APP-NVUE
		let { context } = options
		if (/#|\./.test(selector) && context.refs) {
			selector = selector.replace(/#|\./, '')
			if (context.refs[selector]) {
				selector = context.refs[selector]
				if(Array.isArray(selector)) {
					selector = selector[0]
				}
			}
		}
		dom.getComponentRect(selector, (res) => {
			if (res.size) {
				resolve([res.size])
			} else {
				reject('no rect')
			}
		})
		// #endif
	});
};