<template>
    <el-autocomplete :class="[block ? 'block' : '', ui]" v-model="modelValues" :fetch-suggestions="queryFetch" :value-key="keys" :placeholder="placeholder" @select="handleFetchSelect" @change="handleFetchChange"/>
</template>

<script setup>
import {ref,watch} from "vue";
const props = defineProps({
    ui: {
        type: String,
        default: ''
    },
    modelValue: {
        type: String,
        default: ''
    },
    datas: {
        type: Array,
        default: () => ([])
    },
    keys: {
        type: String,
        default: 'userName'
    },
    placeholder: {
        type: String,
        default: '请选择或输入'
    },
    block: {
        type: Boolean,
        default: true
    },
})

//初始变量
const queryData = ref(props.datas)
const modelValues = ref(props.modelValue)

//监听
watch(() => [
    props.datas,
    props.modelValue,
], ([datas, val]) => {
    queryData.value = datas;
    modelValues.value = val;
})

//数据筛选处理
const queryFetch = (key, cb) => {
    const results = key ? queryData.value.filter(createFilter(key)) : queryData.value
    cb(results)
}
const createFilter = (key) => {
    return (item) => {
        const str = item[props.keys]
        return (str.toLowerCase().indexOf(key.toLowerCase()) === 0)
    }
}

//事件
const emit = defineEmits(['change', 'update:modelValue'])

//被选择
const handleFetchSelect = (item) => {
    const str = item[props.keys]
    emit('update:modelValue', str)
    emit('change', str)
}

//失去焦点
const handleFetchChange = (val) => {
    emit('update:modelValue', val)
    emit('change', val)
}
</script>
