/**
 * 获取元素信息
 * */
export default {
	data() {
		return {}
	},

	methods:{
		// 获取元素信息
		getDomInfo(selector, context = null, pageScroll = false) {
			return new Promise(async (resolve, reject) => {
				let scrollTop = 0
				// #ifndef WEB
				const query = uni.createSelectorQuery().in(context)
				query
					.select(selector)
					.boundingClientRect(async (res) => {
						if (pageScroll) {
							scrollTop = await this.getPageScroll(context)
						}
						resolve(Object.assign(res || {}, {
							scrollTop
						}))
					})
					.exec()
				// #endif
				// #ifdef WEB
				const elementQuery = document.querySelector(selector)
				const elementRect = elementQuery.getBoundingClientRect()
				if (pageScroll) {
					scrollTop = await this.getPageScroll(context)
				}
				resolve(Object.assign(elementRect, {
					scrollTop
				}))
				// #endif
			})
		},
		// 获取context
		getContext(eleConfig, instance) {
			// #ifdef WEB
			return null
			// #endif
			let context = null
			if (typeof eleConfig.context === 'function') {
				context = eleConfig.context()
			} else if (Array.isArray(eleConfig.context) && eleConfig.context.length) {
				// #ifdef VUE2
				context = this.getChildComponentContextInVue2(eleConfig, instance)
				// #endif
				// #ifdef VUE3
				context = this.getChildComponentContextInVue3(eleConfig, instance)
				// #endif
			} else {
				// #ifdef MP-ALIPAY
				context = eleConfig.context || instance.$parent.ctx
				// #endif
				// #ifndef MP-ALIPAY
				context = eleConfig.context || instance.$parent
				// #endif
			}
			// 如果是组件，可通过组件ref值的 $ 获取组件实例
			// if (eleConfig.isComponent) {
			// 	context = context?.$ || null
			// }
			return context
		},
		// vue2 环境获取子组件实例
		getChildComponentContextInVue2(eleConfig, instance){
			let parent = instance.$parent
			eleConfig.context.forEach((item) => {
				parent = parent.$refs[item]
			})
			return parent
		},
		// #ifdef VUE3
		// vue3 环境获取子组件实例
		getChildComponentContextInVue3(eleConfig, instance){
			// #ifndef MP-ALIPAY
			return this.getChildComponentContextInVue2(eleConfig, instance)
			// #endif

			// #ifdef MP-ALIPAY
			let parent = instance.$parent
			eleConfig.context.forEach((item) => {
				parent = parent.$children.find((child) => {
					return child.$attrs['hz-ref-name'] == item
				})
			})
			return parent
			// #endif
		},
		// #endif
		// 获取页面滚动高度
		getPageScroll(context = null) {
			return new Promise((resolve, reject) => {
				// #ifndef H5
				const query = uni.createSelectorQuery().in(context)
				query.selectViewport().scrollOffset((res) => {
					resolve(res.scrollTop)
				}).exec()
				// #endif
				// #ifdef H5
				let scrollTop = document.documentElement.scrollTop
				// 这里判断是否存在页面标题，如果存在，scrollTop 需要减去标题高度
				const pageHeaderQuery = document.querySelector('.uni-page-head')
				if (pageHeaderQuery) {
					const pageHeaderRect = pageHeaderQuery.getBoundingClientRect()
					scrollTop += pageHeaderRect.height
				}
				resolve(scrollTop)
				// #endif
			})
		}
	}
}