<template>
  <div class="search-bar">
    <a-auto-complete
      :value="modelValue"
      :options="suggestOptions"
      :open="showSuggestions"
      @update:value="handleInput"
      @select="handleSelect"
      @blur="showSuggestions = false"
    >
      <template #default>
        <a-input-search
          :value="modelValue"
          :placeholder="placeholder"
          size="large"
          enter-button="搜索"
          :loading="loading"
          allow-clear
          @search="handleSearch"
          @pressEnter="handleSearch"
        />
      </template>
    </a-auto-complete>
  </div>
</template>

/**
 * 搜索栏组件
 * 封装 Ant Design 的 InputSearch + AutoComplete，支持 v-model 双向绑定、
 * 回车和点击触发搜索，输入时自动补全建议。
 */
<script setup lang="ts">
import { ref } from 'vue'
import { searchSuggest } from '@/api/search'

const props = defineProps<{
  modelValue: string
  placeholder?: string
  loading?: boolean
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: string): void
  (e: 'search', value: string): void
}>()

const suggestOptions = ref<{ value: string }[]>([])
const showSuggestions = ref(false)
let suggestTimer: ReturnType<typeof setTimeout> | undefined

function handleInput(value: string) {
  emit('update:modelValue', value)
  clearTimeout(suggestTimer)
  if (value.trim().length >= 2) {
    suggestTimer = setTimeout(async () => {
      try {
        const suggestions = await searchSuggest(value, 8)
        suggestOptions.value = suggestions.map(s => ({ value: s }))
        showSuggestions.value = suggestOptions.value.length > 0
      } catch {
        suggestOptions.value = []
        showSuggestions.value = false
      }
    }, 300)
  } else {
    suggestOptions.value = []
    showSuggestions.value = false
  }
}

function handleSelect(value: string) {
  emit('update:modelValue', value)
  showSuggestions.value = false
  emit('search', value)
}

function handleSearch() {
  showSuggestions.value = false
  emit('search', props.modelValue)
}
</script>

<style scoped lang="less">
.search-bar {
  max-width: 720px;
  margin: 0 auto;

  :deep(.ant-input-search) {
    width: 100%;
  }

  :deep(.ant-input-search-large) {
    .ant-input-affix-wrapper {
      height: 44px;
      padding: 0 16px;
      display: flex;
      align-items: center;
    }

    .ant-input {
      font-size: 16px;
      padding: 0;
    }

    .ant-input-search-button {
      font-size: 16px;
      height: 44px;
      padding: 0 24px;
    }
  }

  :deep(.ant-select-auto-complete) {
    width: 100%;
  }
}
</style>
