<template>
  <cover-view class="tab-bar">
    <cover-view class="tab-bar-border"></cover-view>
    <cover-view
      class="tab-bar-item"
      v-for="(item, index) in tabBarList"
      :key="item.pagePath"
      @tap="switchTab(index, item.pagePath)">
      <cover-image :src="selected === index ? '/' +  item.selectedIconPath :  '/' + item.iconPath"/>
      <cover-view :style="{ color: selected === index ? selectedColor : color }">{{ item.text }}</cover-view>
    </cover-view>
  </cover-view>
</template>

<script setup lang="ts">
import {MINI_PROGRAM_USER_CONFIG} from "@/config";
import Taro from "@tarojs/taro";
import {useTabBarStore} from "@/store/tabBarStore";
import {storeToRefs} from "pinia";
import {useUserStore} from "@/store/userStore";
import {computed} from "vue";

const {tokenInfo} = storeToRefs(useUserStore())

/**
 * 默认 TabBar 与自定义 TabBar 的最大不同点在于 <p>默认 TabBar 在所有 TabBar 页共享一个组件实例，而自定义 TabBar 在各个 TabBar 页面初始化时都会创建一个新的组件实例。</p>
 * 也就是说各个 TabBar 页内的自定义 TabBar 组件实例的状态是不共享的。因此对 TabBar 的状态管理（例如 selected 选中态）则尤为重要。
 */
const tabBarStore = useTabBarStore()
const {selected} = storeToRefs(tabBarStore)

const color = '#000000'
const selectedColor = '#DC143C'

const tabBarList = computed(() => tokenInfo.value ? MINI_PROGRAM_USER_CONFIG[tokenInfo.value.extData.identity.value].tabBarList : []);

const switchTab = (index: number, path: string) => {
  tabBarStore.setSelected(index)
  Taro.switchTab({url: '/' + path})
}
</script>

<style lang="scss">
.tab-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100px;
  background: white;
  display: flex;
  padding-bottom: env(safe-area-inset-bottom);
}

.tab-bar-border {
  background-color: rgba(0, 0, 0, 0.33);
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 1px;
  transform: scaleY(0.5);
}

.tab-bar-item {
  flex: 1;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.tab-bar-item cover-image {
  width: 54px;
  height: 54px;
}

.tab-bar-item cover-view {
  font-size: 20px;
}
</style>
