<template>
  <div class="tag-container">
    <div class="tags-wrapper">
      <a-tag
        v-for="type in types"
        :key="type.value"
        @click="selectType(type.value)"
        class="label-tag"
        :class="{ 'active-tag': selectedType === type.value }"
      >
        {{ type.label }}
      </a-tag>
    </div>
    <div class="underline" :style="underlineStyle"></div>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: String,
      default: null,
    },
  },
  data () {
    return {
      selectedType: this.value,
      types: null,
      underlineStyle: {
        width: '0',
        left: '0',
      },
    }
  },
  watch: {
    selectedType (newValue) {
      this.$emit('input', newValue)
      this.updateUnderline()
    },
  },
  mounted () {
    this.updateUnderline()
  },
  methods: {
    init (params) {
      const {
        // 配置内容
        options
      } = params
      this.types = options
    },
    selectType (value) {
      this.selectedType = value
      if (this.selectedType) { // 检查选中内容是否不为空
        this.$emit('selected', this.selectedType) // 发送选中事件
      }
    },
    updateUnderline () {
      // 动态更新下划线位置和宽度
      this.$nextTick(() => {
        const activeTag = this.$el.querySelector('.active-tag')
        if (activeTag) {
          const { offsetWidth, offsetLeft } = activeTag
          this.underlineStyle.width = `${offsetWidth}px`
          this.underlineStyle.left = `${offsetLeft}px`
        }
      })
    }
  }
}
</script>

<style scoped>
/* 容器样式 */
.tag-container {
  position: relative;
  display: inline-block;
  width: 100%;
}

.tags-wrapper {
  display: inline-flex; /* 标签紧邻排列 */
  gap: 0; /* 去掉选项之间的空隙 */
}

.label-tag {
  padding: 5px 15px;
  font-size: 16px;
  color: #333;
  background: none;
  cursor: pointer;
  border: none;
  display: inline-block;
}

.label-tag.active-tag {
  color: #333; /* 不变色 */
  font-weight: bold;
}

.underline {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 2px;
  background-color: #1890ff;
  transition: all 0.3s ease; /* 平滑过渡效果 */
}
</style>
