<template>
  <div class="code-fun-flex-col code-fun-justify-start section_3">
    <div class="view">
      <div class="image-wrapper">
        <!-- 搜索图标 -->
        <img class="image_7" :src="`assets/icons/drawable-xxhdpi/search_bar_left_icon.png`" />
        <!-- 搜索输入框 -->
        <input ref="searchInput" type="input" placeholder="搜索便签..." :value="modelValue" @input="handleInput" @keydown.enter="handleSearch" @focus="handleFocus" @blur="handleBlur" />
        <!-- 清除按钮 -->
        <img v-if="modelValue && modelValue.length > 0" class="clear-button" :src="`assets/icons/drawable-xxhdpi/search_clear_normal.png`" @click="handleClear" />
      </div>
    </div>
  </div>
</template>

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

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
})

const emit = defineEmits(['update:modelValue', 'search', 'clear', 'focus', 'blur'])

const searchInput = ref(null)

const handleInput = event => {
  emit('update:modelValue', event.target.value)
}

const handleSearch = event => {
  emit('search', event.target.value)
}

const handleClear = () => {
  emit('update:modelValue', '')
  emit('clear')
  if (searchInput.value) {
    searchInput.value.focus()
  }
}

const handleFocus = event => {
  emit('focus', event)
}

const handleBlur = event => {
  emit('blur', event)
}

// 暴露方法给父组件
defineExpose({
  focus: () => {
    if (searchInput.value) {
      searchInput.value.focus()
    }
  },
  blur: () => {
    if (searchInput.value) {
      searchInput.value.blur()
    }
  },
})
</script>

<style lang="less" scoped>
.section_3 {
  .view {
    .image-wrapper {
      position: relative;
      padding: 0.25rem 0.5rem;
      border-radius: 2rem;
      background: #f6f9fa;
      border: 1px solid #ccb8a3;
      display: flex;
      flex-direction: row;
      align-items: center;

      .image_7,
      .clear-button {
        width: 1.2rem;
        height: 1.2rem;
        object-fit: contain;
        margin-right: 0.1rem;
      }

      input {
        flex: 1;
        height: 1.2rem;
        line-height: 1.2rem;
        background: transparent;
        border: none;
        outline: none;
        font-size: 0.75rem;
        color: #333;
        padding: 0;
      }
    }
  }
}
</style>
