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

export default {
    props:{
        productType: [String, Number],
        value: [String, Number]
    },
    data(){
        return {
            index: null,
            list:[],
            loading: false
        }
    },
    watch:{
        index(val){
            this.$emit('input', (val!==''&&val !== null) ? this.list[val].id: null)
            this.$emit('change', (val!==''&&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.id == this.value)
            if(index < 0){
                getCustomer(this.value).then(res => {
                    this.list.unshift(res.data)
                    this.index = 0
                })
            }
        },
        remoteMethod(keyword){
            let params = {}
            params.searchKey = keyword
            this.loading = true
            getCustomerSelect(params)
                .then(res => this.list = res.data.list)
                .finally(() => this.loading = false)
        }
    }
}
</script>