<template>
  <view class="custom-tabbar">
    <view 
      v-for="(item, index) in list" 
      :key="index"
      class="custom-tabbar-item"
      :class="{ 'custom-tabbar-item-active': selectedIndex === index }"
      @click="switchTab(item, index)"
    >
      <image 
        :src="selectedIndex === index ? item.selectedIcon : item.icon" 
        class="custom-tabbar-icon"
      />
      <text class="custom-tabbar-text">{{ item.text }}</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      selectedIndex: 0,
      list: [
        {
          pagePath: "/pages/index/index",
          icon: "/static/tabbar/home.png",
          selectedIcon: "/static/tabbar/home_selected.png",
          text: "首页"
        },
        {
          pagePath: "/pages/novel/list",
          icon: "/static/tabbar/novel.png",
          selectedIcon: "/static/tabbar/novel_selected.png",
          text: "小说"
        },
        {
          pagePath: "/pages/bookshelf/index",
          icon: "/static/tabbar/bookshelf.png",
          selectedIcon: "/static/tabbar/bookshelf_selected.png",
          text: "书架"
        },
        {
          pagePath: "/pages/me/index",
          icon: "/static/tabbar/mine.png",
          selectedIcon: "/static/tabbar/mine_selected.png",
          text: "我的"
        }
      ]
    }
  },
  mounted() {
    this.updateSelectedIndex();
  },
  methods: {
    switchTab(item, index) {
      if (this.selectedIndex === index) return;
      
      this.selectedIndex = index;
      uni.switchTab({
        url: item.pagePath
      });
    },
    // 添加 ref 引用以便外部调用
    updateSelectedIndex() {
      const pages = getCurrentPages();
      if (!pages.length) return;
      
      const currentPage = pages[pages.length - 1];
      const currentRoute = currentPage.route;
      
      const index = this.list.findIndex(item => 
        currentRoute.includes(item.pagePath.replace('/pages/', '').replace('/index', ''))
      );
      
      if (index !== -1) {
        this.selectedIndex = index;
      }
    }
  }
}
</script>

<style scoped>
.custom-tabbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  height: 120rpx; /* 增加高度 */
  background-color: #ffffff;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1); /* 增强阴影 */
  z-index: 99999;
}

.custom-tabbar-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10rpx 0;
}

.custom-tabbar-icon {
  width: 52rpx;
  height: 52rpx;
  margin-bottom: 8rpx;
}

.custom-tabbar-text {
  font-size: 26rpx;
  color: #7a7e83;
}

.custom-tabbar-item-active .custom-tabbar-text {
  color: #3a8ee6; /* 使用若依主题蓝色 */
  font-weight: bold;
  font-size: 28rpx;
}
</style>