<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { safeAreaInsets } from '@/utils'

const props = withDefaults(defineProps<Props>(), {
    title: '页面标题',
    showBack: true,
    backIconColor: '#000000',
    backgroundColor: '#ffffff',
    textColor: '#333333',
    height: '88rpx',
})

// Props
interface Props {
    title?: string
    showBack?: boolean
    backIconColor?: string
    backgroundColor?: string
    textColor?: string
}

// 导航栏高度
const navBarHeight = ref('44px')
const navBarTop = ref('44px')
const topSafeAreaHeight = safeAreaInsets?.top || 0

// 返回按钮点击事件
function handleBack() {
    uni.navigateBack({
        delta: 1, // 返回层数，1表示返回上一页
    })
}

// 计算导航栏高度
onMounted(() => {
    // #ifdef MP-WEIXIN
    uni.getSystemInfo({
        success: (res) => {
            const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
            console.log('设备顶部信息：', res)
            console.log('胶囊信息：', menuButtonInfo)
            // 顶部导航栏高度 = 状态栏高度 + 胶囊的高度
            navBarHeight.value = `${menuButtonInfo.height}px`
            navBarTop.value = `${menuButtonInfo.top}px`
        }
    })
    // #endif
})
</script>

<template>
    <view class="top-nav" :style="{
        paddingTop: `${topSafeAreaHeight}px`,
        backgroundColor: props.backgroundColor,
    }">
        <view class="custom-navbar">
            <view v-if="props.showBack" class="back-btn" @tap="handleBack">
                <up-icon name="arrow-left" size="36rpx" :color="props.textColor" />
            </view>
            <view class="nav-title" :style="{
                color: props.textColor,
            }">
                {{ props.title }}
            </view>
            <view v-if="props.showBack" class="right-space" />
        </view>
    </view>
</template>

<style scoped>
/* 顶部导航栏 */
.top-nav {
    background: #ffffff;
    box-shadow: 0rpx 8rpx 7rpx 0rpx rgba(233, 233, 233, 0.17);
    position: fixed;
    /* 固定定位 */
    top: 0;
    /* 顶部对齐 */
    left: 0;
    /* 左侧对齐 */
    right: 0;
    /* 右侧对齐 */
    z-index: 999;
    /* 确保在其他元素之上 */
    padding-top: var(--safe-area-inset-top);
    /* 适配安全区域 */
}

/* 自定义导航栏 */
.custom-navbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 30rpx;
    height: 88rpx;
    box-sizing: border-box;
}

/* 返回按钮 */
.back-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.back-icon {
    font-size: 36rpx;
    color: #000000;
    font-weight: bold;
}

/* 导航栏标题 */
.nav-title {
    font-size: 34rpx;
    font-weight: bold;
    flex: 1;
    text-align: center;
}

/* 右侧占位 */
.right-space {
    width: 60rpx;
}
</style>
