<template>
	<view class="nav-title"
		:style="{height:navBarHeight+'px',opacity: navOpacity,transition: 'opacity 0.3s ease-in-out',background: backgroundColor }">
		<view class="back-icon" :style="{paddingTop:(statusBarHeight-30)+'px'}" v-if="back" @click="backToPage">
			<zzx-icon name="back"></zzx-icon>
		</view>
		<view class="title-style" :style="{paddingTop:(statusBarHeight-30)+'px'}" v-if="title!=''">
			<text>{{title}}</text>
		</view>
		<view class="slot-style" v-else>
			<slot></slot>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, onMounted } from 'vue'
	import { onLoad, onPageScroll } from '@dcloudio/uni-app';
	const navBarHeight = ref(0);
	const statusBarHeight = ref(0);
	const titleBarHeight = ref(0);
	const navOpacity = ref(0);
	const backgroundColor = ref('#fff');
	interface Props {
		title ?: string 
		back ?: boolean //是否开启返回
		scrollable ?: boolean; //是否开启滚动显示
		bgColor ?: string; //自定义背景颜色
	}
	const props = withDefaults(defineProps<Props>(), {
		title: '',
		back: false,
		scrollable: false,
		bgColor: ''
	})
	onMounted(() => {
		get_navheight()
		backgroundColor.value = props.bgColor;
		if(props.scrollable){
			navOpacity.value=0
		}else{
			navOpacity.value=1
		}
	})
	onPageScroll((e) => {
		if (props.scrollable) {
			navOpacity.value = Math.min(Math.max(e.scrollTop / navBarHeight.value, 0), 1);
		}
	})

	const backToPage = () => {
		uni.navigateBack()
	}

	const get_navheight = () => {
		// #ifdef MP-WEIXIN
		const systemInfo = uni.getSystemInfoSync();
		statusBarHeight.value = systemInfo.statusBarHeight || 0;
		// 获取胶囊按钮信息
		const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
		// 计算标题栏高度：胶囊按钮距状态栏的上下边距总和 + 按钮高度
		const titleBarHeightCalc = (menuButtonInfo.top - statusBarHeight.value) * 2 + menuButtonInfo.height;
		titleBarHeight.value = titleBarHeightCalc;
		// 导航栏总高度 = 状态栏高度 + 标题栏高度
		navBarHeight.value = statusBarHeight.value + titleBarHeight.value;
		// #endif
	}
</script>

<style lang="less" scoped>
	.nav-title {
		position: fixed;
		width: 100%;
		background-color: #fff;
		text-align: center;
		font-size: 28rpx;
		z-index: 9999;
		display: flex;
		justify-content: center;
		align-items: center;
		.back-icon {
			position: absolute;
			left: 20rpx;
			top: 70%; 
			transform: translateY(-50%);
		}
		
		.title-style {
			margin-top: 60rpx;
			position: static;
		}
		
		.slot-style {
			margin-top:60rpx;
			position: static; 
		}
	}
</style>