<template>
  <view class="tab-bar">
    <view
      v-for="(tab, index) in tabs"
      :key="index"
      class="tab-item"
      @click="switchTab(tab)"
    >
      <view class="tab-inner" :class="{ active: current === index }">
        <AppIcon
          :name="tab.icon"
          :size="current === index ? 24 : 22"
          :color="current === index ? activeColor : inactiveColor"
        />
        <text class="tab-text" :class="{ active: current === index }">{{ tab.text }}</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, watch, onMounted, getCurrentInstance } from 'vue'

const instance = getCurrentInstance()
const activeColor = '#C6171E'
const inactiveColor = '#8C8C8C'

const tabs = [
  { pagePath: '/pages/index/index',  text: '首页', icon: 'home' },
  { pagePath: '/pages/order/list',   text: '订单', icon: 'clipboard' },
  { pagePath: '/pages/device/list',  text: '设备', icon: 'monitor' },
  { pagePath: '/pages/finance/index',text: '财务', icon: 'dollar' },
]

const current = ref(0)

const getCurrentRoute = () => {
  const pages = getCurrentPages()
  if (pages.length > 0) {
    const route = '/' + pages[pages.length - 1].route
    const idx = tabs.findIndex(t => t.pagePath === route)
    if (idx !== -1) current.value = idx
  }
}

onMounted(() => getCurrentRoute())

watch(() => instance?.proxy?.$route, () => getCurrentRoute(), { immediate: true })

const switchTab = (tab) => {
  uni.switchTab({ url: tab.pagePath })
}
</script>

<style scoped>
.tab-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: stretch;
  background: #FFFFFF;
  height: 104rpx;
  padding: 8rpx 16rpx;
  padding-bottom: calc(8rpx + env(safe-area-inset-bottom));
  box-shadow: 0 -2px 20px rgba(0, 0, 0, 0.06);
  z-index: 999;
}

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

.tab-inner {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4rpx;
  padding: 8rpx 24rpx;
  border-radius: 20rpx;
  transition: background 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  min-width: 120rpx;
}

.tab-inner.active {
  background: rgba(198, 23, 30, 0.06);
}

.tab-text {
  font-size: 22rpx;
  font-weight: 600;
  color: #8C8C8C;
  transition: color 0.25s;
  line-height: 1;
}

.tab-text.active {
  color: #C6171E;
  font-weight: 700;
}

</style>
