
<template>
  <view class="segmented-control">
    <view 
      v-for="(item, index) in values" 
      :key="index"
      class="segmented-control-item"
      :class="{ active: current === index }"
      :style="getItemStyle(index)"
      @tap="onItemTap(index)"
    >
      <text class="segmented-control-text" :style="getTextStyle(index)">
        {{ item }}
      </text>
    </view>
  </view>
</template>

<script>
export default {
  name: "CustomSegmentedControl",
  props: {
    values: {
      type: Array,
      default: () => []
    },
    current: {
      type: Number,
      default: 0
    },
    fontSize: {
      type: Number,
      default: 16
    },
    activeColor: {
      type: String,
      default: "#20269B"
    },
    inactiveColor: {
      type: String,
      default: "#f5f5f5"
    },
    activeTextColor: {
      type: String,
      default: "#ffffff"
    },
    inactiveTextColor: {
      type: String,
      default: "#666666"
    },
    tabBg: {
      type: Boolean,
      default: false
    },
    // 添加下划线相关属性
    underlineHeight: {
      type: String,
      default: "4rpx"
    },
    underlineColor: {
      type: String,
      default: "#20269B"
    },
    underlineWidth: {
      type: String,
      default: "60%"
    }
  },
  methods: {
    onItemTap(index) {
      this.$emit('clickItem', index);
    },
    getItemStyle(index) {
      if (this.tabBg) {
        return {
          backgroundColor: this.current === index ? this.activeColor : this.inactiveColor,
          flex: 1
        };
      } else {
        return {
          // backgroundColor: this.current === index ? this.activeColor : this.inactiveColor,
          flex: 1
        };
      }
    },
    getTextStyle(index) {
      return {
        fontSize: `${this.fontSize}px`,
        color: this.current === index ? this.activeTextColor : this.inactiveTextColor
      };
    }
  }
}
</script>

<style scoped>
.segmented-control {
  display: flex;
  height: 70rpx;
  /* border-radius: 35rpx; */
  overflow: hidden;
  /* box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1); */
}

.segmented-control-item {
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  position: relative; /* 为下划线添加定位 */
}

.segmented-control-text {
  font-weight: 500;
  transition: all 0.3s;
}

/* 为激活项添加下划线 */
.segmented-control-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: v-bind(underlineWidth);
  height: v-bind(underlineHeight);
  background-color: v-bind(underlineColor);
  border-radius: 2rpx;
}
</style>