<template>
  <div class="search-input">
    <div class="input-wrapper">
      <div class="input-block">
        <van-icon class="search-icon" name="search" />
        <input 
          class="inner-input" 
          v-model="modelValue" 
          :placeholder="placeholder" 
        />
        <van-icon 
          class="close-icon" 
          name="clear" 
          v-if="modelValue !== ''" 
          @click="clearInput" 
        />
      </div>
      <!-- 右侧插槽：用于放置全部和筛选按钮 -->
      <div class="slot-wrapper" v-if="$slots.extra">
        <slot name="extra"></slot>
      </div>
    </div>
  </div>
</template>

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

const modelValue = defineModel('modelValue')

const props = defineProps({
  placeholder: {
    type: String,
    default: '请输入关键词'
  }
})

// 清空输入框
const clearInput = () => {
  modelValue.value = ''
}
</script>

<style scoped lang="scss">
.search-input {
  position: relative;
  height: 40px;
  width: 100%;
  margin-top: 8px;
  box-sizing: border-box;
}

.input-wrapper {
  display: flex;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #fff;
  border-radius: 4px;
  gap: 12px; // 输入框和按钮组间距
  padding-right: 12px; // 右侧内边距
  box-sizing: border-box;
}

.input-block {
  position: relative;
  flex: 1;
  height: 100%;
  display: flex;
  justify-content: center;
  box-sizing: border-box;

  .search-icon, .close-icon {
    position: absolute;
    top: 50%;
    left: 20px;
    transform: translateY(-50%);
    font-size: 20px;
    color: #9b9b9b;
    pointer-events: none; // 搜索图标不阻挡点击
  }
  
  .close-icon {
    left: unset;
    right: 20px;
    pointer-events: auto; // 清空图标可点击
    cursor: pointer;
    
    &:active {
      opacity: 0.6;
    }
  }
}

.inner-input {
  outline: none;
  border: none;
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
  text-align: center;
  font-size: 14px;
  background: transparent;
}

.slot-wrapper {
  display: flex;
  align-items: center;
  gap: 8px; // 按钮间距
  flex-shrink: 0; // 防止压缩
}
</style>