<template>
  <view>
    <!-- 填充区，避免内容被导航栏遮挡 -->
    <view class="navbar-placeholder" :style="{ height: navBarHeight + 'px' }"></view>
    
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px', height: navBarHeight + 'px' }">
      <view class="navbar-left" @click="handleBack" :style="{ height: capsuleHeight + 'px', lineHeight: capsuleHeight + 'px' }">
        <image :src="backIcon" mode="aspectFit" class="back-icon"></image>
      </view>
      <view class="navbar-title" :style="{ height: capsuleHeight + 'px', lineHeight: capsuleHeight + 'px' }">{{ title }}</view>
      <view class="navbar-right" :style="{ height: capsuleHeight + 'px', lineHeight: capsuleHeight + 'px' }">
        <slot name="right"></slot>
      </view>
    </view>
  </view>
</template>

<script>
import CommonEnum from "../../enum/common";

export default {
  name: 'CustomNavbar',
  props: {
    title: {
      type: String,
      default: ''
    },
    backIcon: {
      type: String,
      default: CommonEnum.BACK_BUTTON
    },
    showBack: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      statusBarHeight: 0,
      navBarHeight: 0,
      menuButtonInfo: null,
      capsuleHeight: 0,
    }
  },
  mounted() {
    this.getSystemInfo();
  },
  methods: {
    getSystemInfo() {
      // 获取系统信息
      const systemInfo = uni.getSystemInfoSync();
      // 获取状态栏高度
      this.statusBarHeight = systemInfo.statusBarHeight;
      
      // 获取胶囊按钮信息
      this.menuButtonInfo = uni.getMenuButtonBoundingClientRect();
      
      // 计算胶囊高度
      this.capsuleHeight = this.menuButtonInfo.height;
      
      // 计算导航栏高度（胶囊底部到状态栏顶部的距离）
      this.navBarHeight = this.menuButtonInfo.bottom + 8;
    },
    handleBack() {
      if (this.showBack) {
        // 先触发自定义事件，让父组件有机会处理
        this.$emit('back');
        // 自动执行返回逻辑
        uni.navigateBack({
          delta: 1
        });
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/* 填充区样式 */
.navbar-placeholder {
  width: 100%;
  background-color: transparent;
}

/* 自定义导航栏样式 */
.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  padding-top: 0;
  background-color: #F5F0E7;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-left: 30rpx;
  padding-right: 30rpx;
  box-sizing: border-box;
}

.navbar-left {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60rpx;

  .back-icon {
    width: 56rpx;
    height: 56rpx;
  }
}

.navbar-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #695347;
  flex: 1;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.navbar-right {
  width: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style> 