<template>
    <el-select
        v-model="index"
        filterable
        clearable
        remote
        reserve-keyword
        placeholder="请输入关键词"
        :remote-method="remoteMethod"
        :loading="loading">
        <el-option
        v-for="(item, index) in list"
        :key="item.id"
        :label="`${item.contactsName}(${item.customerName})`"
        :value="index">
        </el-option>
    </el-select>
</template>
<script>
import {getCustomerContactsSelect, getCustomerContacts} from '@/api/ecw/customerContacts'

export default {
    props:{
        value: [String, Number]
    },
    data(){
        return {
            index: null,
            list:[],
            loading: false,
            size: 20
        }
    },
    watch:{
        index(val){
            this.$emit('input', val !== null ? this.list[val].customerContactsId: null)
            this.$emit('change', val !== null ? this.list[val]: null)
        },
        value(val){
            this.init()
        }
    },
    created(){
        this.init()
    },
    methods:{
        init(){
            if(!this.value) return
            let index = this.list.findIndex(item => item.customerContactsId == this.value)
            if(index < 0){
                getCustomerContacts(this.value).then(res => {
                    this.list.unshift(res.data)
                    this.index = 0
                })
            }
        },
        remoteMethod(keyword){
            let params = {
                size: this.size
            }
            params.searchKey = keyword
            this.loading = true
            getCustomerContactsSelect(params)
                .then(res => this.list = res.data)
                .finally(() => this.loading = false)
        }
    }
}
</script>