<template>
	<view v-if="inited"
		class="l-overlay" 
		ref="overlayRef"
		:class="[lClass, classes]"
		:style="[styles, lStyle]"
		@click.stop="onClick" 
		@touchmove.stop="noop" 
		@transitionend="finished" 
		:aria-role="ariaRole" 
		:aria-label="ariaLabel">
		<slot></slot>
	</view>
</template>

<script lang="uts" setup>
	/**
	 * Overlay 遮罩层组件
	 * @description 用于创建模态遮罩层，通常配合弹窗、对话框等组件使用
	 * <br>插件类型：LOverlayComponentPublicInstance 
	 * @tutorial https://ext.dcloud.net.cn/plugin?name=lime-overlay
	 * 
	 * @property {string} ariaLabel 无障碍访问标签（需语义化描述作用）
	 * @property {string} ariaRole ARIA角色属性（默认：'presentation'）
	 * @property {string} lClass 自定义类名（会覆盖默认样式）
	 * @property {string} bgColor 背景颜色（默认：'rgba(0, 0, 0, 0.7)'）
	 * @property {string} lStyle 自定义样式（最高优先级，支持CSS字符串）
	 * @property {number} duration 背景过渡动画时长（单位：ms，默认：300）
	 * @property {boolean} preventScrollThrough 阻止滚动穿透（默认：true）
	 * @property {boolean} visible 是否显示遮罩层（支持v-model）
	 * @property {number} zIndex 层级（默认：1000）
	 * @event {Function} click 点击遮罩层时触发（常用于关闭操作）
	 * @event {Function} before-enter
	 * @event {Function} enter 
	 * @event {Function} after-enter
	 * @event {Function} before-leave
	 * @event {Function} leave
	 * @event {Function} after-leave
	 */
	import { useTransition, type UseTransitionOptions, type TransitionEmitStatus } from '@/uni_modules/lime-transition';
	import { OverlayProps } from './type';
	// defineOptions({
	// 	name:'l-overlay'	
	// })
	
	const props = withDefaults(defineProps<OverlayProps>(), {
		ariaLabel: '关闭',
		ariaRole: 'button',
		preventScrollThrough: true,
		zIndex: 998,
		visible: false,
		duration: 300,
	})
	
	const emit = defineEmits(['click', 'before-enter', 'enter', 'after-enter', 'before-leave', 'leave', 'after-leave'])
	
	const {inited, display, classes, finished} = useTransition({
		defaultName: 'fade',
		appear: props.visible,
		emits: (name:TransitionEmitStatus) => { emit(name) },
		visible: (): boolean => props.visible,
		duration: props.duration,
	} as UseTransitionOptions)
	
	const styles = computed<Map<string,any>>(():Map<string,any> => {
		const style = new Map<string,any>();
		if (props.bgColor != null) {
			style.set("background-color", props.bgColor!)
		}
		if (props.zIndex > 0) {
			style.set("z-index", props.zIndex)
		}
		// #ifndef APP || WEB
		style.set('transition-duration', props.duration + 'ms')
		if (!display.value) {
			style.set("display", "none")
		}
		// #endif
		return style
	})
	
	const noop = () => {}
	const onClick = (event: UniPointerEvent) =>{
		// event.stopPropagation()
		emit('click', !props.visible)
	}
	// #ifdef APP || WEB
	const overlayRef = ref<UniElement|null>(null)
	
	watchEffect(()=>{
		overlayRef.value?.style.setProperty('transition-duration', `${props.duration}ms`)
		if(!display.value){
			overlayRef.value?.style.setProperty('display', "none")
		} else {
			overlayRef.value?.style.setProperty('display', "flex")
		}
	})
	// #endif
	
</script>
<style lang="scss">
	@import './index';
</style>