<template>
    <el-autocomplete
        v-model="brand_name"
        :fetch-suggestions="search"
        @select="handleSelect"
        clearable
        class="inline-input w-50"
        placeholder="品牌关键字"
        :style="{width: props.width + 'px','font-size': props.font + 'px'}"
    />
</template>

<script setup>
    import { ref, watch } from 'vue'
    import { searchBrand } from '@/api'
    const props = defineProps({
        modelValue: {
            type: Object,
            default: () => ({ id: 0, name: '' })
        },
        width: {
            type: Number,
            default: 140
        },
        font: {
            type: Number,
            default: 12
        }
    })
    const emits = defineEmits(['update:modelValue'])
    const brand_name = ref(props.modelValue.name)

    watch(() => props.modelValue,
        (newValue) => {
            brand_name.value = newValue.name
        },{ deep: true }
    )

    const search = async (qs, cb) => {
        if(qs && qs.length >= 2) {
            try {
                const {data:slist} = await searchBrand(qs)
                var list = slist.data
                if (list.length == 0) {
                    list.push({
                        id: '-1',
                        value: '无匹配结果'
                    })
                    cb(list);
                } else {
                    list = list.map(item => ({
                            value:`${item.name} ${item.name_en}`,
                            id: `${item.id}`,
                            name: item.name ? item.name : item.name_en
                        })
                    )
                    cb(list);
                }
            } catch (error) {
                console.log(error)
            }
        }
    }

    const handleSelect = (item) => {
        if(item.id != -1) {
            let selectedBrand = {
                id: item.id,
                name: item.name,
            }
            emits('update:modelValue',selectedBrand)
        } else {
            emits('update:modelValue',{ id: 0, name: brand_name.value })
        }
    }
</script>
