<template>
  <view class="header-bar">
    <StatusBar />
    <view
      class="header-content"
      :style="{
        alignItems: 'center'
      }"
    >
      <view v-if="enableBack" class="back-btn" @click="handleBack">
        <uni-icons type="back" size="24" color="#222"></uni-icons>
      </view>
      <image v-if="icon" :src="icon" class="header-icon" mode="aspectFit" />
      <text class="header-title" :class="{ 'has-back': enableBack }" :style="{ textAlign: textAlign }">{{ title }}</text>
    </view>
  </view>
</template>

<script>
import StatusBar from "@/components/StatusBar.vue";
/**
 * HeaderBar 头部导航栏组件
 * @prop {String} title 标题
 * @prop {String} icon 图标路径
 * @prop {Boolean} enableBack 是否显示返回按钮
 */
/* global wx, uni */
export default {
  name: 'HeaderBar',
  components: {
    StatusBar,
  },
  props: {
    title: {
      type: String,
      required: true
    },
    icon: {
      type: String,
      default: ''
    },
    textAlign: {
      type: String,
      default: 'left'
    },
    enableBack: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      statusBarHeight: 20,
    }
  },
  methods: {
    handleBack() {
      const pages = getCurrentPages()
      if (pages.length > 1) {
        uni.navigateBack()
      } else {
        uni.switchTab({
          url: '/pages/index/index'
        })
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.header-bar {
  width: 100%;
  .status-bar {
    width: 100%;
  }
  .header-content {
    display: flex;
    align-items: center;
    padding: 16rpx 24rpx 16rpx 24rpx;
    .back-btn {
      margin-right: 16rpx;
      padding: 8rpx;
      flex-shrink: 0;
      width: 48rpx;
    }
    .header-icon {
      width: 64rpx;
      height: 64rpx;
      margin-right: 16rpx;
      flex-shrink: 0;
    }
    .header-title {
      flex: 1;
      font-size: 36rpx;
      color: #222;
      text-align: center;
      padding: 0 8rpx;
    }
    .has-back {
      margin-right: 48rpx;
    }
  }
}
</style>