<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: "我的"
        }
      ]
    }
  },
  created() {
    this.updateSelectedIndex();
  },
  methods: {
    switchTab(item, index) {
      if (this.selectedIndex === index) return;
      
      this.selectedIndex = index;
      uni.switchTab({
        url: item.pagePath
      });
    },
    updateSelectedIndex() {
      const pages = getCurrentPages();
      if (!pages.length) return;
      
      const currentPage = pages[pages.length - 1];
      const currentRoute = currentPage.route;
      
      const index = this.list.findIndex(item => 
        item.pagePath.includes(currentRoute)
      );
      
      if (index !== -1) {
        this.selectedIndex = index;
      }
    }
  }
}
</script>

<style scoped>
.custom-tabbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  height: 100rpx;
  background-color: #ffffff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  z-index: 9999;
}

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

.custom-tabbar-icon {
  width: 48rpx;
  height: 48rpx;
  margin-bottom: 6rpx;
}

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

.custom-tabbar-item-active .custom-tabbar-text {
  color: #3cc51f;
  font-weight: bold;
}
</style>