<template>
    <el-autocomplete
        v-model="code"
        :fetch-suggestions="search"
        @select="handleSelect"
        @input="handleInput"
        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 { searchProduct } from '@/api/product'
    import _ from 'lodash'
    const props = defineProps({
        modelValue: {
            type: String,
            default: ''
        },
        width: {
            type: Number,
            default: 120
        },
        font: {
            type: Number,
            default: 12
        }
    })
    const emits = defineEmits(['update:modelValue','selected'])
    const code = ref(props.modelValue)

    watch(()  => props.modelValue, (newValue) => {
        if(newValue == '') {
            code.value = ''
        }
    })

    const search = (qs,cb) => _.debounce(search_list(qs,cb),500)
    const search_list = async (qs, cb) => {
        if(qs && qs.length >= 3) {
            try {
                const {data:slist} = await searchProduct(qs)
                var list = slist.data
                if (list.length == 0) {
                    list.push({
                        id: '-1',
                        value: '无匹配结果'
                    })
                    cb(list);
                } else {
                    list = list.map(item => ({
                            value:`${item.brand} ${item.code}`,
                            id: `${item.id}`,
                            code: `${item.code}`,
                            brand: `${item.brand}`
                        })
                    )
                    cb(list);
                }
            } catch (error) {
                console.log(error)
            }
        } else {
            cb([{
                value: '请输入至少3个字符',
                id: -1,
            }])
        }
    }

    const handleSelect = (item) => {
        if(item.id != -1) {
            emits('selected',{
                id: item.id,
                code: item.code,
            })
            code.value = item.code
        } else {
            emits('selected',{
                id: 0, code: code.value
            })
        }
    }

    const handleInput = (val) => {
        emits('update:modelValue',val)
    }
</script>
