<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 ? 22 : 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 } from 'vue'

const props = defineProps({
  selected: {
    type: Number,
    default: 0
  }
})

const activeColor = '#C6171E'
const inactiveColor = '#999999'

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(props.selected)

watch(() => props.selected, (val) => {
  current.value = val
})

onMounted(() => {
  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
  }
})

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;
  padding: 8rpx 12rpx;
  padding-bottom: calc(8rpx + env(safe-area-inset-bottom));
  box-shadow: 0 -2px 16px rgba(0, 0, 0, 0.06);
  border-top: 1px solid #F0F0F0;
  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: 10rpx 24rpx;
  border-radius: 20rpx;
  transition: background 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}

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

.tab-text {
  font-size: 20rpx;
  font-weight: 500;
  color: #999999;
  transition: color 0.25s;
}

.tab-text.active {
  color: #C6171E;
  font-weight: 600;
}
</style>
