<!--
  底部导航标签栏
  @author: 张文
  @date: 2022-03-01
-->
<template>
  <div class="ty-tab-bar-box">
    <van-tabbar
      v-model="active"
      :placeholder="true"
      @change="doTabChange"
    >
      <van-tabbar-item
        v-for="(i,k) in tabBar.menu"
        :key="k"
        :badge="maxBadge(i)"
        :name="i.name"
      >
        <span>{{ i.title }}</span>
        <template #icon="props">
          <img :style="{height:i.size || tabBar.size}" :src="props.active ? i.active : i.inactive" alt="" />
        </template>
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>


export default {
  name: "tyTabBar",
  props:{
    // 渲染的数据
    tabBarMenu: Object,
    // 显示角标
    badge:{
      type: Array,
      default: () => []
    }
  },
  /*computed:{
    tabBar(){
      return this.updateTabBar()
    }
  },*/
  watch:{
    badge(){
      this.updateTabBar()
    },
    tabBarMenu(){
      this.updateTabBar()
    }
  },
  data() {
    return {
      active: this.$route.name,
      tabBar:{}
    }
  },
  mounted() {
    this.updateTabBar()
  },
  methods: {
    // 底部导航栏图标被点击
    doTabChange (e) {
      this.$router.replace({ name: e })
    },

    // 手动触发更新
    updateTabBar(){
      this.tabBar = {}
      if (Object.keys(this.tabBarMenu || {}).length){
        this.tabBar = this.tabBarMenu
      }else {
        this.tabBar = this.$tyTabBar.get()
      }
    },

    // 计算角标数据
    badgeNum(i){
      if (!this.badge.length) return i.badge

      const list = this.badge.filter(item=>{
        if (item.name && item.name === i.name){
          return item
        }
      })

      if (!list.length) return i.badge

      return list[0].badge
    },

    // 计算角标是否超过最大值
    maxBadge(i){
      const badge = this.badgeNum(i)

      const num = Number(badge)
      const max = Number(this.tabBar.maxBadge || 9)

      if (isNaN(num) || isNaN(max)){
        return badge
      }

      if (max === 0) return num

      if (max < num){
        return max + '+'
      }

      return num

    }
  }
}
</script>

<style scoped lang="less">
/*
* 顶部导航栏
*/

.ty-tab-bar-box{

  /deep/.van-hairline--top-bottom{

    box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.3);
  }
}

</style>
