<template>
    <el-select v-model="value" :placeholder="placeholder" style="width: 100%;" clearable :filterable="filterable">
        <el-option v-for="item in options" :key="item.value" :label="item.label" style="max-width:480px;"
            :value="item.value" />
    </el-select>
</template>

<script setup lang="ts">
import {ref, computed, onMounted} from 'vue'
/**
 * SearchSelect 
 * @author nielang
 * @description 用于实时检索的下拉框
 * @property {String} placeholder input的placeholder
 * @property {Function} request 接口请求函数
 * @property {String} requestParam 接口请求参数名称
 * @property {Boolean} showOptionValue 选项中是否显示value属性
 * @property {String} optionValue 接口用于显示的属性（该属性将返回父组件用于检索）
 * @property {String} optionLabel 接口用于显示的属性
 * @property {Boolean} filterable 是否可搜索
 */
const props = defineProps({
    modelValue:{
        type: String,
        default: "",
    },
    placeholder: {
        type: String,
        default: "",
    },
    request:{
        type: Function,
        require: true
    },
    requestParam: {
        type: Object,
        default: {},
    },

    showOptionValue: {
        type: Boolean,
        default: true,
    },
    optionValue: {
        type: [String, Number],
        default: "id",
    },
    optionLabel: {
        type: [String, Number],
        default: "name",
    },
    filterable: {
        type: Boolean,
        default: false,
    },
})

const emit = defineEmits(['update:modelValue'])
const value = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  }
})

interface ListItem {
    value: string
    label: string
}
const options = ref<ListItem[]>([])
const initOptions = () => {
    if (props.request) {
        props.request(props.requestParam).then((data:any) => {
            options.value = data.map((item: any) => {
                return {
                    value: item[props.optionValue],
                    label: (props.showOptionValue ? `【${item[props.optionValue]}】` : '') + item[props.optionLabel]
                }
            })
        })
    }
}

onMounted(() => {
    initOptions();
});
</script>

<style scoped>

</style>