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

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

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

// 导航栏高度
const navBarHeight = ref('44px')
const navBarTop = ref('44px')

// 返回按钮点击事件
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="custom-navigation-bar"
        :style="{
            height: navBarHeight,
            top: navBarTop,
            backgroundColor: props.backgroundColor,
            color: props.textColor,
        }"
    >
        <!-- 返回按钮 -->
        <view v-if="props.showBack" class="nav-back-btn" @click="handleBack">
            <u-icon name="arrow-left" :color="props.textColor" size="18" class="back-icon" />
        </view>

        <!-- 标题 -->
        <view class="nav-title">
            {{ props.title }}
        </view>

        <!-- 占位元素，保持标题居中 -->
        <view v-if="props.showBack" class="nav-placeholder" />
    </view>
</template>

<style scoped>
.custom-navigation-bar {
  position: fixed;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  z-index: 999;
}

.nav-back-btn {
  position: absolute;
  left: 16px;
  /* display: flex;
  align-items: center;
  justify-content: center; */
  width: 44px;
  height: 100%;
}

.back-icon {
  font-size: 24px;
}

.nav-title {
  height: 100%;
  font-size: 18px;
  font-weight: 500;
  text-align: center;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-placeholder {
  height: 100%;
  position: absolute;
  right: 16px;
  width: 44px;
}
</style>
